Last updated: Apr 10, 2024
Reading timeยท2 min
The "NameError: name 'pip' is not defined" occurs for multiple reasons:
pip
command in an interactive shell session.pip
command inside of a Python module.If you entered an interactive shell session by typing "python", "python3" or
"py" in your terminal, use the exit()
, exit
or press CTRL + D
to quit the
shell session.
exit()
Once you exit the shell session, you can issue any pip
command.
pip install requests # ๐๏ธ Or with pip3 pip3 install requests
Another common cause of the error is trying to run a pip
command from a Python
module.
Here is an example of how you would install a module in a Python script.
The following file is named main.py
.
import sys import subprocess python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'], stdout=subprocess.DEVNULL )
You can run the file with python main.py
, python3 main.py
or py main.py
to
install the requests
module.
requests
with the name of the module you're trying to install.You can also remove the stdout
keyword argument if you want to see the output
of the pip
command when running python main.py
.
# โ Shows output of the pip install command import sys import subprocess python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'] )
pip
Here is an example of how you would install a package from your shell (e.g. CMD, PowerShell, bash, etc).
pip install requests pip3 install requests # ๐๏ธ If you don't have pip in your PATH environment variable python -m pip install requests python3 -m pip install requests # ๐๏ธ Using py alias (Windows) py -m pip install requests # ๐๏ธ If you get a permissions error pip install requests --user
Make sure to replace requests
with the name of the package you're trying to
install.
pip
If the error persists, try to run the following command to upgrade pip
.
# ๐๏ธ On Linux or macOS python -m ensurepip --upgrade # ๐๏ธ Using python 3 python3 -m ensurepip --upgrade # ๐๏ธ On Windows py -m ensurepip --upgrade
If you get an error that pip
is not found or "no module named pip", check out
my other article with instructions on how to install and upgrade pip
.
To solve the "NameError: name 'pip' is not defined", make sure:
pip
command in an interactive shell session.pip
command directly in a Python module.