One error that you might encounter while using Python is:
ModuleNotFoundError: No module named 'pip'
This error occurs when the pip
module is not available in your Python environment.
This tutorial shows an example that causes this error and how to fix it.
How to reproduce the error
Suppose you want to import the pip
module in your source code as follows:
import pip
print(pip.__version__)
But you get the following error when running the code:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import pip
ModuleNotFoundError: No module named 'pip'
This error occurs when the pip
module is not available in your Python environment.
The pip
module is usually bundled with Python, so it should be available when you installed the Python program.
But if you see this error, then Python might have skipped building the pip
module when you install it.
How to fix this error
To resolve this error, you need to install the pip
module using the ensurepip
module.
Try to run one of the commands below:
python -m ensurepip
# For Python 3:
python3 -m ensurepip
# Windows:
py -m ensurepip
# For Linux, you can also use:
sudo apt install python3-pip
Once the module is installed, run one of the following commands to see if pip
is available:
pip -V
pip3 -V
# If pip not available in PATH, try:
python -m pip -V
python3 -m pip -V
If the command works, then you should be able to import pip
in your source code without receiving the error.
Alternative ways to install pip
If the command above doesn’t work, you can try using the get-pip.py
script to install the module.
First, download the script from https://bootstrap.pypa.io/get-pip.py into your computer. You need to open the context menu with right-click and select the ‘Save As..’ option.
Next, run the get-pip.py
script using Python from your terminal as follows:
python get-pip.py
# For Python 3:
python3 get-pip.py
# Windows:
py get-pip.py
You should have a similar output as follows:
You should be able to run pip
or pip3
from the terminal now.
If you still can’t access pip
, then try to install the module using commands specific to your Operating System:
# For Debian / Ubuntu
sudo apt update
sudo apt install python3-venv python3-pip
# For Fedora
sudo dnf update
sudo dnf install python3-pip python3-wheel
# For CentOS / RHEL
sudo yum update
sudo yum install python3 python3-pip
If you’re using Windows or macOS, you need to reinstall Python using the official installer, which should also take care of adding pip
to the system PATH.
Adding pip to PATH
If you can’t run pip -V
but able to run python -m pip -V
, that means the path to pip is not added to your PATH system.
In Windows, you can do this using the set PATH
command.
Get the location of Python using the where python
command as follows:
Output:
where python
C:\Users\nsebhastian\AppData\Local\Programs\Python\Python310\python.exe
C:\Users\nsebhastian\AppData\Local\Microsoft\WindowsApps\python.exe
Next, add the location to python.exe
to your PATH as follows:
set PATH=%PATH%;C:\Users\nsebhastian\AppData\Local\Programs\Python\Python310
That should allow the command prompt to find the pip
module for the current session. If you want to add the location permanently to the PATH, use the setx
command instead of set
.
For Linux and macOS, run the export PATH
command followed by the $PATH
variable:
export PATH="$PATH:/usr/local/bin/python"
You need to add the absolute path to the Python location as well.
Conclusion
The ModuleNotFoundError: No module named 'pip'
occurs in Python when the pip
module is not available in the current Python environment.
To resolve this error, run the ensurepip
or get-pip.py
script that will install pip
to your system.
I hope this tutorial is helpful. See you in other tutorials! 👍
PIP is a widely used Python package manager to manage and perform various operations. For instance, installing, removing, upgrading, and downgrading specific packages in Python.
However, if this module is not correctly installed in the system, the error named “ModuleNotFoundError” occurs in Python.
This write-up will explain the possible reasons and appropriate solutions for the “no module named pip” error in python using the following snippet:
- Reason: pip Not Installed
- Solution 1: Install pip Using ensurepip Command (Windows)
- Solution 2: Install pip Using get-pip.py (Windows)
- Solution 3: Installing pip on Linux
- How to Upgrade the pip Version?
- How to Downgrade the pip Version?
Reason: pip Not Installed
A common reason for the “ModuleNotFoundError: No module named pip” in Python is that the “pip” is not installed in the Python environment. The snippet below shows the stated error:
The above snippet shows that the “pip” module is not installed in our system.
Solution 1: Install pip Using ensurepip Command (Windows)
Open the command prompt and enter the following command to install the pip package:
> py -m ensurepip --upgrade
The below snippet shows that the pip version “21.2.3” has been successfully installed:
Solution 2: Install pip Using get-pip.py (Windows)
We can also install pip in our system using the bootstrapping logic method. For this, open the command prompt terminal and type the following command to download the “get-pip.py” file:
> curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
After downloading the “get-pip.py” file, the next thing is to install pip on windows using the given below command:
As you can see in the below snippet, the “pip-22.3.1” latest version installed in Python successfully:
Verify the Installation of pip (Windows)
In our system, we can check whether pip is correctly installed. First, enter the Python shell using the “python” command in CMD and after that, run the “import pip” command:
Solution 3: Installing pip on Linux
To install Python pip on “Ubuntu 22.04” you can follow the given below detailed tutorial: How to Install Python Pip on Ubuntu 22.04
To install Python pip on various other Linux distributions, for example, to install Python pip on Arch Linux type the given below commands in the terminal:
# Python 2 $ sudo pacman -S python2-pip # Python 3 $ sudo pacman -S python-pip
To install Python pip on Fedora, type the following command:
# Python 2 $ sudo dnf install python-pip # Python 3 $ sudo dnf install python3
Similarly to install Python pip package manager on CentOS and RHEL use the given below command:
$ sudo yum install epel-release #enabling the repository $ sudo yum install python-pip
How to Upgrade the pip Version?
To upgrade the pip package in the system, the first step is to check the current version of the “pip module” by typing the following command:
The above snippet shows that the pip version “22.3.1” is installed in our system.
To upgrade the pip package in Python, the following command is used in Python:
> python -m pip install --upgrade pip
From the above snippet, it is verified that the “pip” package installed in our system is up to date.
How to Downgrade the pip Version?
To downgrade or install the specific pip version, we use the following command in terminal windows (command prompt):
> python -m pip install pip==18.1
As we can see from the below snippet that version “18.1” is successfully installed. The previous version was successfully removed from the system:
Conclusion
The “ModuleNotFoundError: No module named pip” occurs in Python when the “pip” package is not installed in our system. To rectify this error, various methods are used to install “pip” such as using the official Python installer, using the “ensurepip” command, and using get-pip.py. The various solutions for installing pip in different Linux distributions are also provided in this article. Apart from that, the methods to upgrade or downgrade the pip version is also provided.
This error occurs when you try to use pip, but it is not installed in your Python environment. This can happen if you skip installing pip when installing Python or when creating a virtual environment, or after explicitly uninstalling pip.
You can solve this error by downloading pip using the following curl command
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then install pip by running:
python3 get-pip.py
If this does not work, you can use ensurepip to bootstrap the pip installer into an existing Pip installation or virtual environment. For example,
# Linux python3 -m ensurepip --upgrade # MacOS python3 -m ensurepip --upgrade # Windows py -m ensurepip --upgrade
This tutorial will go through the ways to ensure pip is installed in your environment.
Table of contents
- Install pip by Downloading get-pip.py
- Bootstrap pip using ensurepip
- Install pip using Operating System Specific command
- Installing pip for Linux
- Installing pip for Mac Operating System
- Upgrading pip
- Check pip and Python version
- Recreate Virtual Environment
- Summary
Install pip by Downloading get-pip.py
Download pip by running the following curl command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
The curl
command allows you to specify a direct download link. Using the -o
option sets the name of the downloaded file.
Install pip by running:
python3 get-pip.py
Bootstrap pip using ensurepip
You can use ensurepip to bootstrap the pip installer into an existing Pip installation or virtual environment. For example,
# Linux python3 -m ensurepip --upgrade # MacOS python3 -m ensurepip --upgrade # Windows py -m ensurepip --upgrade
Install pip using Operating System Specific command
If the above solutions do not work, you can try to install pip using the command specific to your operating system.
Installing pip for Linux
All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.
Installing pip for Ubuntu, Debian, and Linux Mint
sudo apt install python-pip3
Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
sudo dnf install python-pip3
Installing pip for CentOS 6 and 7, and older versions of Red Hat
sudo yum install epel-release sudo yum install python-pip3
Installing pip for Arch Linux and Manjaro
sudo pacman -S python-pip
Installing pip for OpenSUSE
sudo zypper python3-pip
Installing pip for Mac Operating System
You can install Python3 and pip3 using brew with the following command:
brew install python
Upgrading pip
You may also need to upgrade pip, which you can do with the following commands:
# Linux python3 -m pip install --upgrade pip # MacOS python3 -m pip install --upgrade pip # Windows py -m pip install --upgrade pip
Check pip and Python version
Ensure that the Python version in use matches the pip version. You can check versions from the command line using the --version
flag. For example,
python --version
Python 3.8.8
pip --version
pip 21.2.4 from /Users/Research/opt/anaconda3/lib/python3.8/site-packages/pip (python 3.8)
Note that the –version returns the version of Python is 3.8.8, and the pip installer in use is for 3.8.
Recreate Virtual Environment
If you are using a virtual environment and the error persists despite trying the above solutions, you can recreate the environment. For example,
# deactivate environment deactivate # remove the virtual environment folder rm -rf venv # Initial a new virtual environment python3 -m venv venv # Activate on Linux/MacOS source venv/bin/activate # Activate on Windows (cmd.exe) venv\Scripts\activate.bat # Activate on Windows (PowerShell) venv\Scripts\Activate.ps1
Summary
Congratulations on reading to the end of this tutorial.
Go to the online courses page on Python to learn more about Python for data science and machine learning.
For further reading on missing modules in Python, go to the article:
- How to Solve ModuleNotFoundError: no module named ‘plotly’.
- How to Solve Python ModuleNotFoundError: no module named ‘pymongo’
- How to Solve Python ModuleNotFoundError: no module named ‘xgboost’
Have fun and happy researching!
Если вы являетесь разработчиком Python, вы могли столкнуться с ошибкой «ModuleNotFoundError: No module named ‘pip’». Эта ошибка возникает, когда вы пытаетесь запустить скрипт Python, для которого требуется пакет, не установленный на вашем компьютере.
В этом сообщении блога мы рассмотрим, что вызывает эту ошибку и как ее исправить.
Что такое ПИП?
PIP — это менеджер пакетов для Python. Он помогает вам устанавливать и управлять пакетами (также известными как библиотеки или модули), которые не являются частью стандартной библиотеки Python. PIP — это инструмент командной строки, который устанавливается с Python 2.7.9 и более поздними версиями (включая Python 3).
С помощью PIP вы можете легко устанавливать пакеты из индекса пакетов Python (PyPI) или из локального каталога. Вы также можете удалить пакеты и обновить их до последних версий.
Если вы получаете сообщение об ошибке «ModuleNotFoundError: No module named ‘pip’», это означает, что PIP не установлен на вашем компьютере или установлен неправильно.
В зависимости от версии Python, которую вы используете, существуют разные способы установки PIP. В некоторых случаях PIP также может отсутствовать из-за неполной или поврежденной установки Python.
Как исправить ModuleNotFoundError для PIP
Вы можете попробовать выполнить следующие шаги, чтобы исправить ошибку «ModuleNotFoundError: No module named ‘pip’».
1. Проверьте, установлен ли PIP
Первое, что нужно сделать, это проверить, установлен ли PIP на вашем компьютере. Для этого откройте командную строку или терминал и введите:
python -m pip --version
Если PIP установлен, вы должны увидеть номер версии. Например, «пункт 21.1.3».
Если вы получаете сообщение об ошибке типа «python: нет модуля с именем pip», это означает, что PIP не установлен на вашем компьютере или установлен неправильно.
2. Установите PIP вручную
Если PIP не установлен на вашем компьютере, вы можете загрузить и установить его вручную. Для этого перейдите на официальный сайт PIP (https://pypi.org/project/pip/#files) и загрузите соответствующую версию для вашей установки Python.
После загрузки файла откройте командную строку или терминал и перейдите в каталог, в котором вы сохранили файл. Затем введите:
python get-pip.py
Это установит PIP на вашем компьютере.
3. Обновление PIP
Если PIP уже установлен на вашем компьютере, но вы по-прежнему получаете сообщение об ошибке «ModuleNotFoundError: No module named ‘pip’», это может быть связано с тем, что ваша версия PIP устарела. Чтобы обновить PIP, откройте командную строку или терминал и введите:
python -m pip install --upgrade pip
Это обновит PIP до последней версии.
4. Проверьте установку Python
Если ни один из вышеперечисленных шагов не работает, это может быть связано с тем, что ваша установка Python не завершена или повреждена. Чтобы проверить установку Python, откройте командную строку или терминал и введите:
python --version
Это покажет вам версию Python, которую вы используете. Если вы используете устаревшую версию, вы можете загрузить последнюю версию с официального сайта Python (https://www.python.org/downloads/).
Вы также можете попробовать переустановить Python на своем компьютере.
Заключение
Ошибка «ModuleNotFoundError: нет модуля с именем «pip»» — частая проблема разработчиков Python. Это происходит, когда PIP не установлен на вашем компьютере или установлен неправильно. Чтобы исправить эту ошибку, вы можете попробовать проверить, установлен ли PIP, установить PIP вручную, обновить PIP или проверить установку Python.
Следуя шагам, описанным в этом сообщении блога, вы сможете исправить ошибку «ModuleNotFoundError: No module named ‘pip’» и продолжить беспрепятственную разработку приложений Python.
Environment
- pip version: 9.0.3
- Python version: 3.6
- OS: Windows Server 2016 Datacenter
Description
My system admin installed Python 3.6 for me in my AWS workspace and i requested him to update the pip version to 18 but while he was trying to upgrade the version, he ran into error. All below-mentioned commands were executed from a Powershell window in Administrative mode:
Output
PS D:\python\3.6\scripts> pip install --upgrade pip
Collecting pip
Downloading https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940
/pip-18.0-py2.py3-none-any.whl (1.3MB)
100% |████████████████████████████████| 1.3MB 720kB/s
Installing collected packages: pip
Found existing installation: pip 9.0.3
Uninstalling pip-9.0.3:
Exception:
Traceback (most recent call last):
File "d:\python\3.6\lib\shutil.py", line 544, in move
os.rename(src, real_dst)
OSError: [WinError 17] The system cannot move the file to a different disk drive: 'd:\\python\\3.6\\scripts\\pip.exe' ->
'C:\\Users\\sdgadmin\\AppData\\Local\\Temp\\pip-o9ithn08-uninstall\\python\\3.6\\scripts\\pip.exe'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\python\3.6\lib\site-packages\pip\basecommand.py", line 215, in main
File "d:\python\3.6\lib\site-packages\pip\commands\install.py", line 342, in run
File "d:\python\3.6\lib\site-packages\pip\req\req_set.py", line 778, in install
File "d:\python\3.6\lib\site-packages\pip\req\req_install.py", line 754, in uninstall
File "d:\python\3.6\lib\site-packages\pip\req\req_uninstall.py", line 115, in remove
File "d:\python\3.6\lib\site-packages\pip\utils\__init__.py", line 267, in renames
File "d:\python\3.6\lib\shutil.py", line 559, in move
os.unlink(src)
PermissionError: [WinError 5] Access is denied: 'd:\\python\\3.6\\scripts\\pip.exe'
PS D:\python\3.6\scripts> pip list
Traceback (most recent call last):
File "d:\python\3.6\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "d:\python\3.6\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\Python\3.6\Scripts\pip.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'
PS D:\python\3.6\scripts> pip3 install --upgrade pip
Traceback (most recent call last):
File "d:\python\3.6\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "d:\python\3.6\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\Python\3.6\Scripts\pip3.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'
PS D:\python\3.6\scripts> pip3 install --upgrade pip3
Traceback (most recent call last):
File "d:\python\3.6\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "d:\python\3.6\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\Python\3.6\Scripts\pip3.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'
PS D:\python\3.6\scripts> pip install --upgrade pip
Traceback (most recent call last):
File "d:\python\3.6\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "d:\python\3.6\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\Python\3.6\Scripts\pip.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'
PS D:\python\3.6\scripts> pip.exe install --upgrade pip
Traceback (most recent call last):
File "d:\python\3.6\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "d:\python\3.6\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\Python\3.6\Scripts\pip.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'
Are we doing something wrong here? I also checked few links that suggested using easy_install. I tried that as well but ran into issues.
PS D:\python\3.6\scripts> .\easy_install.exe pip
Searching for pip
Reading https://pypi.python.org/simple/pip/
d:\python\3.6\lib\site-packages\setuptools\pep425tags.py:89: RuntimeWarning: Config variable 'Py_DEBUG' is unset, Python
ABI tag may be incorrect
warn=(impl == 'cp')):
d:\python\3.6\lib\site-packages\setuptools\pep425tags.py:93: RuntimeWarning: Config variable 'WITH_PYMALLOC' is unset, P
ython ABI tag may be incorrect
warn=(impl == 'cp')):
Downloading https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/p
ip-18.0-py2.py3-none-any.whl#sha256=070e4bf493c7c2c9f6a08dd797dd3c066d64074c38e9e8a0fb4e6541f266d96c
error: Download error for https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3
703d2ddaf940/pip-18.0-py2.py3-none-any.whl#sha256=070e4bf493c7c2c9f6a08dd797dd3c066d64074c38e9e8a0fb4e6541f266d96c: [SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)