Borislav Hadzhiev
Mon Apr 25 2022·2 min read
Photo by Matteo Kutufa
If you get a "SyntaxError: invalid syntax" when trying to install a module
using pip
, make sure to run the command from your shell, e.g. bash or
PowerShell, and not by running a Python file that contains the
pip install your_module
command.
Here is an example of how the error occurs.
# ⛔️ SyntaxError: invalid syntax pip install requests
Running the main.py
file with python main.py
causes the error because we
aren't supposed to run pip
commands by running a Python script.
pip install some_module
command from the Python interpreter in your shell. You can use CTRL + D
to exit the Python interpreter and install the specific module.Instead, run the pip install your_module
command from your shell, e.g. bash
,
PowerShell or CMD.
pip install requests
The example above installs the requests
module. Make sure to adjust the name
of the module if you have to.
If you get an error when running the pip install some_module
command from your
shell, try the following commands.
# 👇️ in a virtual environment or using Python 2 pip install requests # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install requests # 👇️ if you get permissions error sudo pip3 install requests # 👇️ if you don't have pip in your PATH environment variable python -m pip install requests # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install requests
After you install the specific package, you can import it and use it in your Python script.
Here is an example that imports and uses requests
.
import requests def make_request(): res = requests.get('https://reqres.in/api/users') print(res.json()) make_request()
If you aren't sure what command you should run to install the module, google for "Pypi your_module_name", e.g. "Pypi requests".
Click on the pypi.org
website and look at the pip install
command.
If the suggestions didn't help, try creating a virtual environment by running the following commands from your shell.
# 👇️ use correct version of Python when creating VENV python3 -m venv venv # 👇️ activate on Unix or MacOS source venv/bin/activate # 👇️ activate on Windows (cmd.exe) venv\Scripts\activate.bat # 👇️ activate on Windows (PowerShell) venv\Scripts\Activate.ps1 # 👇️ install any modules you need in virtual environment pip install requests
Your virtual environment will use the version of Python that was used to create it.
If the error persists and you can't install the specific module, watch a quick video on how to use Virtual environments in Python.
This one is for using using virtual environments (VENV) on Windows
:
This one is for using using virtual environments (VENV) on MacOS
and Linux
: