No module named pip что делать windows

OS: Mac OS X 10.7.5 Python Ver: 2.7.5 I have installed setuptools 1.0 with ez_setup.py from https://pypi.python.org/pypi/setuptools Then I download pip.1.4.1 pkg from https://pypi.python.org/pypi...

OS: Mac OS X 10.7.5
Python Ver: 2.7.5

I have installed setuptools 1.0 with ez_setup.py from https://pypi.python.org/pypi/setuptools
Then I download pip.1.4.1 pkg from https://pypi.python.org/pypi/pip/1.4.1.

Run (sudo) python setup.py install in iTerm shows that

running install
running bdist_egg running egg_info writing requirements to
pip.egg-info/requires.txt writing pip.egg-info/PKG-INFO writing
top-level names to pip.egg-info/top_level.txt writing dependency_links
to pip.egg-info/dependency_links.txt writing entry points to
pip.egg-info/entry_points.txt warning: manifest_maker: standard file
'setup.py' not found

reading manifest file 'pip.egg-info/SOURCES.txt' writing manifest file
'pip.egg-info/SOURCES.txt' installing library code to
build/bdist.macosx-10.6-intel/egg running install_lib warning:
install_lib: 'build/lib' does not exist -- no Python modules to
install

creating build/bdist.macosx-10.6-intel/egg creating
build/bdist.macosx-10.6-intel/egg/EGG-INFO copying
pip.egg-info/PKG-INFO -> build/bdist.macosx-10.6-intel/egg/EGG-INFO
copying pip.egg-info/SOURCES.txt ->
build/bdist.macosx-10.6-intel/egg/EGG-INFO copying
pip.egg-info/dependency_links.txt ->
build/bdist.macosx-10.6-intel/egg/EGG-INFO copying
pip.egg-info/entry_points.txt ->
build/bdist.macosx-10.6-intel/egg/EGG-INFO copying
pip.egg-info/not-zip-safe ->
build/bdist.macosx-10.6-intel/egg/EGG-INFO copying
pip.egg-info/requires.txt ->
build/bdist.macosx-10.6-intel/egg/EGG-INFO copying
pip.egg-info/top_level.txt ->
build/bdist.macosx-10.6-intel/egg/EGG-INFO creating
'dist/pip-1.4.1-py2.7.egg' and adding
'build/bdist.macosx-10.6-intel/egg' to it removing
'build/bdist.macosx-10.6-intel/egg' (and everything under it)
Processing pip-1.4.1-py2.7.egg removing
'/Users/dl/Library/Python/2.7/lib/python/site-packages/pip-1.4.1-py2.7.egg'
(and everything under it) creating
/Users/dl/Library/Python/2.7/lib/python/site-packages/pip-1.4.1-py2.7.egg
Extracting pip-1.4.1-py2.7.egg to
/Users/dl/Library/Python/2.7/lib/python/site-packages pip 1.4.1 is
already the active version in easy-install.pth Installing pip script
to /Users/dl/Library/Python/2.7/bin Installing pip-2.7 script to
/Users/dl/Library/Python/2.7/bin

Installed
/Users/dl/Library/Python/2.7/lib/python/site-packages/pip-1.4.1-py2.7.egg
Processing dependencies for pip==1.4.1 Finished processing
dependencies for pip==1.4.1

Then I inputed pip install, the error message showed like that

Traceback (most recent call last):   File
"/Library/Frameworks/Python.framework/Versions/2.7/bin/pip", line 9,
in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()   File "build/bdist.macosx-10.6-intel/egg/pkg_resources.py", line 357, in
load_entry_point   File
"build/bdist.macosx-10.6-intel/egg/pkg_resources.py", line 2394, in
load_entry_point   File
"build/bdist.macosx-10.6-intel/egg/pkg_resources.py", line 2108, in
load ImportError: No module named pip

Anyone who met the same problem before and can give me some tips to solve it?

Fredrick Gauss's user avatar

asked Aug 21, 2013 at 16:34

David Lu's user avatar

6

I had the same problem.
My solution:

For Python 3

sudo apt-get install python3-pip

For Python 2

sudo apt-get install python-pip

lmiguelvargasf's user avatar

answered Jun 14, 2016 at 8:15

5

With macOS 10.15 and Homebrew 2.1.6 I was getting this error with Python 3.7. I just needed to run:

python3 -m ensurepip

Now python3 -m pip works for me.

answered Jul 5, 2019 at 3:14

kainjow's user avatar

kainjowkainjow

3,3551 gold badge19 silver badges17 bronze badges

6

On Mac using brew is a better option as apt-get is not available.
Command:

brew install python

In case you have both python2 & python3 installed on machine

python2.7 -m ensurepip --default-pip

simply should solve the issue.

If instead you are missing pip from python 3 then simply change python2.7 to python3 in the command above.

Jonathan Cabrera's user avatar

answered Oct 8, 2017 at 12:17

iosCurator's user avatar

iosCuratoriosCurator

4,2762 gold badges21 silver badges25 bronze badges

4

After installing ez_setup, you should have easy_install available. To install pip just do:

easy_install pip

answered Oct 27, 2014 at 14:21

Manu's user avatar

ManuManu

3,0531 gold badge15 silver badges14 bronze badges

4

for Windows:

python -m ensurepip

after activate your env ex : venv

(venv) PS D:your path> d:your pathvenvscriptspython.exe -m pip install --upgrade pip

sample of result:

Collecting pip

Using cached pip-21.3-py3-none-any.whl (1.7 MB)

Installing collected packages: pip

Attempting uninstall: pip

Found existing installation: pip 20.1.1

Uninstalling pip-20.1.1:

  Successfully uninstalled pip-20.1.1

Successfully installed pip-21.3

answered Oct 20, 2021 at 23:42

Fethi Pounct's user avatar

1

Run

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Then run the following command in the folder where you downloaded: get-pip.py

python get-pip.py

answered Nov 29, 2020 at 16:52

AllisLove's user avatar

AllisLoveAllisLove

3892 silver badges11 bronze badges

1

On some kind of Linux, like distros based on Debian, you might want to consider updating your ‘apt-get‘ first, in case you are installing python-pip through it.

sudo apt-get update

This might help apt-get to update its indexes and locate the python-pip package.
After this, u might install pip like this-

sudo apt-get install python-pip (Python2)
sudo apt-get install python3-pip (Python3)

answered Apr 21, 2020 at 18:23

ANUP SAJJAN's user avatar

ANUP SAJJANANUP SAJJAN

1,38812 silver badges17 bronze badges

1

I encountered the same error with Python 3.8.6 on MacOS Big Sur.

Whether I used pip or pip3 I’d get this error:

 File "/Users/marcelloromani/dev/<repository>/venv/bin/pip", line 5, in <module>
    from pip._internal.cli.main import main
ModuleNotFoundError: No module named 'pip'

It turns out my virtualenv was out of date.
This fixed the issue for me:

  1. Remove the old virtualenv
$ deactivate
$ rm -rf venv
  1. Initialise a new virtualenv
$ virtualenv venv
$ . venv/bin/activate
  1. Install the new requirements then worked:
$ pip install -r src/requirements.txt

answered Jan 21, 2021 at 15:49

Marcello Romani's user avatar

1

Try to re-install the pip
use curl command to download the get-pip.py file:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

if curl is not working then open this link :
get-pip.py

create a get-pip.py file in your directory
copy the code from this link and put it in the get-pip.py file and save the file in the same directory.
then run the command

python get-pip.py

answered Apr 12, 2021 at 10:12

Deepesh ranjan's user avatar

2

If you get «No module named pip» in ubuntu, try this.

$python3 -m pip --version
/usr/bin/python3: No module named pip

$sudo apt-get install python3-pip

It worked for me.

After successful installation validate using

$python3 -m pip --version

To upgrade to latest pip version

$python3 -m pip install --upgrade pip

answered Jun 2, 2021 at 1:58

Vijay's user avatar

VijayVijay

791 silver badge1 bronze badge

1

I ran into this same issue when I attempted to install the nova client.

spencers-macbook-pro:python-novaclient root# python  setup.py install    
running install
/usr/bin/python: No module named pip
error: /usr/bin/python -m pip.__init__ install   'pbr>=0.5.21,<1.0' 'iso8601>=0.1.4' 'PrettyTable>=0.6,<0.8' 'requests>=1.1' 'simplejson>=2.0.9' 'six' 'Babel>=0.9.6' returned 1

I use homebrew so I worked around the issue with sudo easy_install pip

spencers-macbook-pro:python-novaclient root# brew search pip
aespipe     brew-pip    lesspipe    pipebench   pipemeter   spiped  pipeviewer

If you meant "pip" precisely:

Homebrew provides pip via: `brew install python`. However you will then
have two Pythons installed on your Mac, so alternatively you can:
    sudo easy_install pip
spencers-macbook-pro:python-novaclient root# sudo easy_install pip

The commands should be similar if you use macports.

answered Sep 9, 2013 at 19:22

spuder's user avatar

spuderspuder

16.8k19 gold badges86 silver badges149 bronze badges

I know this thread is old, but I just solved the problem for myself on OS X differently than described here.

Basically I reinstalled Python 2.7 through brew, and it comes with pip.

Install Xcode if not already:

xcode-select –install

Install Brew as described here:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then install Python through Brew:

brew install python

And you’re done. In my case I just needed to install pyserial.

pip install pyserial

meaning-matters's user avatar

answered Aug 31, 2016 at 18:03

ScottyC's user avatar

ScottyCScottyC

1,4071 gold badge15 silver badges22 bronze badges

1

Download:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Then Install pip:

py get-pip.py

Then Install biopython:

py -m pip install biopython

I wish it would be useful

answered Mar 15, 2021 at 9:31

Khaled Al Halabee's user avatar

I downloaded pip binaries from here and it resolved the issue.

answered Jun 11, 2014 at 8:51

MadeOfAir's user avatar

MadeOfAirMadeOfAir

2,8734 gold badges29 silver badges39 bronze badges

I think none of these answers above can fix your problem.

I was also confused by this problem once. You should manually install pip following the official guide pip installation (which currently involves running a single get-pip.py Python script)

after that, just sudo pip install Django.
The error will be gone.

The Red Pea's user avatar

The Red Pea

16.7k18 gold badges96 silver badges127 bronze badges

answered Oct 28, 2015 at 13:59

sudoz's user avatar

sudozsudoz

3,1151 gold badge21 silver badges19 bronze badges

1

I encountered the issue ModuleNotFoundError: No module named 'pip' when I created a new Python 3 virtual environment using the command

python3 -m venv ~/venv/ontology    ## << note: "python3" (problematic)

which is a command often suggested (here, elsewhere). When I entered that venv, pip was nowhere to be found.

In the interim, since first using that command to create Python virtual environments, my system Python had upgraded (Arch Linux system updates) from Python 3.7.4 to Python 3.9.2.

The solution is to use the command

python -m venv <your_venv>  ## e.g. python -m ~/venv/ontology

When I did that (python -m ... not python3 -m ...), that venv now contained pip

To upgrade pip within that venv, use

<your_venv_path>/bin/python -m pip install --upgrade pip

## e.g.
## /home/victoria/venv/ontology/bin/python -m pip install --upgrade pip

answered Apr 5, 2021 at 16:50

Victoria Stuart's user avatar

Victoria StuartVictoria Stuart

4,3762 gold badges41 silver badges36 bronze badges

In terminal try this:

ls -lA /usr/local/bin | grep pip

in my case i get:

-rwxr-xr-x 1 root  root      284 Сен 13 16:20 pip
-rwxr-xr-x 1 root  root      204 Окт 27 16:37 pip2
-rwxr-xr-x 1 root  root      204 Окт 27 16:37 pip2.7
-rwxr-xr-x 1 root  root      292 Сен 13 16:20 pip-3.4

So pip2 || pip2.7 in my case works, and pip

answered Oct 27, 2014 at 13:55

Artem Zinoviev's user avatar

0

I am using Debian, but this solution can also be applied for Ubuntu.

  1. Usually, pip comes with python by default, in order to check if pip is installed in your system run.
python -m pip --version
  1. If pip is not there, install it using Aptitude Linux Package Manager,
# For Python 2
sudo apt install python-pip

# For Python 3
sudo apt install python3-venv python3-pip
  1. I wouldn’t use the get-pip.py script in Debian/Ubuntu, because in the documentation page mentions the following.

Be cautious if you are using a Python install that is managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.

Sources here and there.

answered Apr 15, 2021 at 5:36

Georgios Syngouroglou's user avatar

python -m ensurepip —user

this if your mac is not above big sur

and you installed py 3 —

I did this and I have no problems now

back to the legacy version of 2.7 I guess.

answered Aug 21, 2022 at 22:25

Mark Antony's user avatar

1

Here’s a minimal set of instructions for upgrading to Python 3 using MacPorts:

sudo port install py37-pip
sudo port select --set pip pip37
sudo port select --set pip3 pip37
sudo pip install numpy, scipy, matplotlib

I ran some old code and it works again after this upgrade.

grooveplex's user avatar

grooveplex

2,4514 gold badges28 silver badges30 bronze badges

answered Oct 16, 2019 at 19:58

StevenJD's user avatar

I was facing the same error on win11, so the main problem was on executing pip command without admin permissions, so openup your terminal with administrator permission and then execute again the pip command. Hope it helps,

answered Aug 31, 2022 at 13:06

Marielys Brijaldo's user avatar

I solved a similar error on Linux by setting PYTHONPATH to the site-packages location. This was after running python get-pip.py --prefix /home/chet/pip.

[chet@rhel1 ~]$ ~/pip/bin/pip -V
Traceback (most recent call last):
  File "/home/chet/pip/bin/pip", line 7, in <module>
    from pip import main
ImportError: No module named pip

[chet@rhel1 ~]$ export PYTHONPATH=/home/chet/pip/lib/python2.6/site-packages

[chet@rhel1 ~]$ ~/pip/bin/pip -V
pip 9.0.1 from /home/chet/pip/lib/python2.6/site-packages (python 2.6)

answered Oct 24, 2017 at 21:54

GargantuChet's user avatar

GargantuChetGargantuChet

5,6111 gold badge30 silver badges41 bronze badges

Tested below for Linux:
You can directly download pip from https://pypi.org/simple/pip/
untar and use directly with your latest python.

tar -xvf  pip-0.2.tar.gz
cd pip-0.2

Check for the contents.

anant$ ls
docs  pip.egg-info  pip-log.txt  pip.py  PKG-INFO  regen-docs  scripts  setup.cfg  setup.py  tests

Execute directly:

anant$ python pip.py --help
Usage: pip.py COMMAND [OPTIONS]

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -E DIR, --environment=DIR
                        virtualenv environment to run pip in (either give the
                        interpreter or the environment base directory)
  -v, --verbose         Give more output
  -q, --quiet           Give less output
  --log=FILENAME        Log file where a complete (maximum verbosity) record
                        will be kept
  --proxy=PROXY         Specify a proxy in the form
                        user:passwd@proxy.server:port. Note that the
                        user:password@ is optional and required only if you
                        are behind an authenticated proxy.  If you provide
                        user@proxy.server:port then you will be prompted for a
                        password.
  --timeout=SECONDS     Set the socket timeout (default 15 seconds)

answered Oct 1, 2019 at 10:42

Anant Bhasu's user avatar

I just needed to replace pip with pip3 so I ended up running the command as follows: pip3 install matplotlib

answered Oct 1, 2020 at 20:42

Ben Calvert's user avatar

I had a similar problem with virtualenv that had python3.8 while installing dependencies from requirements.txt file. I managed to get it to work by activating the virtualenv and then running the command python -m pip install -r requirements.txt and it worked.

answered Oct 16, 2020 at 5:44

Asim's user avatar

AsimAsim

5234 silver badges18 bronze badges

my py version is 3.7.3, and this cmd worked

python3.7 -m pip install requests

requests library — for retrieving data from web APIs.

This runs the pip module and asks it to find the requests library on PyPI.org (the Python Package Index) and install it in your local system so that it becomes available for you to import

answered May 1, 2019 at 13:25

Mahi's user avatar

MahiMahi

4625 silver badges7 bronze badges

1

For Windows:

If pip is not available when Python is downloaded: run the command

python get-pip.py

MarianD's user avatar

MarianD

12.4k12 gold badges39 silver badges53 bronze badges

answered Feb 10, 2021 at 15:00

KavithaV's user avatar

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:python3.6scripts> 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:python3.6libshutil.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:python3.6libsite-packagespipbasecommand.py", line 215, in main
  File "d:python3.6libsite-packagespipcommandsinstall.py", line 342, in run
  File "d:python3.6libsite-packagespipreqreq_set.py", line 778, in install
  File "d:python3.6libsite-packagespipreqreq_install.py", line 754, in uninstall
  File "d:python3.6libsite-packagespipreqreq_uninstall.py", line 115, in remove
  File "d:python3.6libsite-packagespiputils__init__.py", line 267, in renames
  File "d:python3.6libshutil.py", line 559, in move
    os.unlink(src)
PermissionError: [WinError 5] Access is denied: 'd:\python\3.6\scripts\pip.exe'

PS D:python3.6scripts> pip list
Traceback (most recent call last):
  File "d:python3.6librunpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "d:python3.6librunpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:Python3.6Scriptspip.exe__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'

PS D:python3.6scripts> pip3 install --upgrade pip
Traceback (most recent call last):
  File "d:python3.6librunpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "d:python3.6librunpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:Python3.6Scriptspip3.exe__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'

PS D:python3.6scripts> pip3 install --upgrade pip3
Traceback (most recent call last):
  File "d:python3.6librunpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "d:python3.6librunpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:Python3.6Scriptspip3.exe__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'

PS D:python3.6scripts> pip install --upgrade pip
Traceback (most recent call last):
  File "d:python3.6librunpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "d:python3.6librunpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:Python3.6Scriptspip.exe__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip'

PS D:python3.6scripts> pip.exe install --upgrade pip
Traceback (most recent call last):
  File "d:python3.6librunpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "d:python3.6librunpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:Python3.6Scriptspip.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:python3.6scripts> .easy_install.exe pip
Searching for pip
Reading https://pypi.python.org/simple/pip/
d:python3.6libsite-packagessetuptoolspep425tags.py:89: RuntimeWarning: Config variable 'Py_DEBUG' is unset, Python
 ABI tag may be incorrect
  warn=(impl == 'cp')):
d:python3.6libsite-packagessetuptoolspep425tags.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)

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)

venvScriptsactivate.bat

# Activate on Windows (PowerShell)

venvScriptsActivate.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!

1. Overview

In this tutorial, we’ll see how to solve a popular Python error on Linux Mint and Ubuntu:

ImportError: No module named pip

The error is raised when you try to install new package or running command like:

python3 -m pip list

In the next sections we will see how to solve the error

To install pip module on Linux Mint or Ubuntu we can use apt-get and install it as follows:

sudo apt-get install python3-pip

Now after running:

python3 -m pip list

you should get something like:

Package                  Version             
------------------------ --------------------
apt-clone                0.2.1               
apturl                   0.5.2               
attrs                    19.3.0        

3. Install pip with ensurepip module

Alternatively we can install pip from Python itself by running. Most python versions are shipped with module ensurepip which can be used for installation:

python -m ensurepip --upgrade

The command above will work for Linux distros. If you like to learn more you can check: pip documentation v22.0.3.

4. Manual Installation of pip module

Finally if you prefer to manually download and install pip you can follow next steps:

  • Download the script, from https://bootstrap.pypa.io/get-pip.py
  • Open Terminal
  • move to the folder containing the get-pip.py file
  • Run python get-pip.py

Or simply:

cd ~/Downloads
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

This method is perfect if you need to install pip offline.

5. Conclusion

To conclude, this article shows how to solve the «ImportError: No module named pip» error in several different ways.

All solutions are tested on Linux Mint and Ubuntu. Some of them might work on Windows or Mac with small changes. For further reference please check the official documentation: pip installation on Linux, MacOS and Windows.

Quick Fix: Python raises the ImportError: No module named 'pip' when it cannot find the library pip. The most frequent source of this error is that you haven’t installed pip explicitly with pip install pip. Alternatively, you may have different Python versions on your computer, and pip is not installed for the particular version you’re using.

Problem Formulation

You’ve just learned about the awesome capabilities of the pip library and you want to try it out, so you start your code with the following statement:

import pip

This is supposed to import the Pandas library into your (virtual) environment. However, it only throws the following ImportError: No module named pip:

>>> import pip
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    import pip
ModuleNotFoundError: No module named 'pip'

Solution Idea 1: Install Library pip

The most likely reason is that Python doesn’t provide pip in its standard library. You need to install it first!

Before being able to import the Pandas module, you need to install it using Python’s package manager pip. Make sure pip is installed on your machine.

To fix this error, you can run the following command in your Windows shell:

$ pip install pip

This simple command installs pip in your virtual environment on Windows, Linux, and MacOS. It assumes that your pip version is updated. If it isn’t, use the following two commands in your terminal, command line, or shell (there’s no harm in doing it anyways):

$ python -m pip install --upgrade pip
$ pip install pandas

💡 Note: Don’t copy and paste the $ symbol. This is just to illustrate that you run it in your shell/terminal/command line.

Solution Idea 2: Fix the Path

The error might persist even after you have installed the pip library. This likely happens because pip is installed but doesn’t reside in the path you can use. Although pip may be installed on your system the script is unable to locate it. Therefore, it is unable to install the library using pip in the correct path.

To fix the problem with the path in Windows follow the steps given next.

Step 1: Open the folder where you installed Python by opening the command prompt and typing where python

Step 2: Once you have opened the Python folder, browse and open the Scripts folder and copy its location. Also verify that the folder contains the pip file.

Step 3: Now open the Scripts directory in the command prompt using the cd command and the location that you copied previously.

Step 4: Now install the library using pip install pip command. Here’s an analogous example:

After having followed the above steps, execute our script once again. And you should get the desired output.

Other Solution Ideas

  • The ModuleNotFoundError may appear due to relative imports. You can learn everything about relative imports and how to create your own module in this article.
  • You may have mixed up Python and pip versions on your machine. In this case, to install pip for Python 3, you may want to try python3 -m pip install pip or even pip3 install pip instead of pip install pip
  • If you face this issue server-side, you may want to try the command pip install --user pip
  • If you’re using Ubuntu, you may want to try this command: sudo apt install pip
  • You can check out our in-depth guide on installing pip here.
  • You can also check out this article to learn more about possible problems that may lead to an error when importing a library.

Understanding the “import” Statement

import pip

In Python, the import statement serves two main purposes:

  • Search the module by its name, load it, and initialize it.
  • Define a name in the local namespace within the scope of the import statement. This local name is then used to reference the accessed module throughout the code.

What’s the Difference Between ImportError and ModuleNotFoundError?

What’s the difference between ImportError and ModuleNotFoundError?

Python defines an error hierarchy, so some error classes inherit from other error classes. In our case, the ModuleNotFoundError is a subclass of the ImportError class.

You can see this in this screenshot from the docs:

You can also check this relationship using the issubclass() built-in function:

>>> issubclass(ModuleNotFoundError, ImportError)
True

Specifically, Python raises the ModuleNotFoundError if the module (e.g., pip) cannot be found. If it can be found, there may be a problem loading the module or some specific files within the module. In those cases, Python would raise an ImportError.

If an import statement cannot import a module, it raises an ImportError. This may occur because of a faulty installation or an invalid path. In Python 3.6 or newer, this will usually raise a ModuleNotFoundError.

Related Videos

The following video shows you how to resolve the ImportError:

How to Fix : “ImportError: Cannot import name X” in Python?

The following video shows you how to import a function from another folder—doing it the wrong way often results in the ModuleNotFoundError:

How to Call a Function from Another File in Python?

How to Fix “ModuleNotFoundError: No module named ‘pip’” in PyCharm

If you create a new Python project in PyCharm and try to import the pip library, it’ll raise the following error message:

Traceback (most recent call last):
  File "C:/Users/.../main.py", line 1, in <module>
    import pip
ModuleNotFoundError: No module named 'pip'

Process finished with exit code 1

The reason is that each PyCharm project, per default, creates a virtual environment in which you can install custom Python modules. But the virtual environment is initially empty—even if you’ve already installed pip on your computer!

Here’s a screenshot exemplifying this for the pandas library. It’ll look similar for pip.

The fix is simple: Use the PyCharm installation tooltips to install Pandas in your virtual environment—two clicks and you’re good to go!

First, right-click on the pandas text in your editor:

Second, click “Show Context Actions” in your context menu. In the new menu that arises, click “Install Pandas” and wait for PyCharm to finish the installation.

The code will run after your installation completes successfully.

As an alternative, you can also open the Terminal tool at the bottom and type:

$ pip install pip

If this doesn’t work, you may want to set the Python interpreter to another version using the following tutorial: https://www.jetbrains.com/help/pycharm/2016.1/configuring-python-interpreter-for-a-project.html

You can also manually install a new library such as pip in PyCharm using the following procedure:

  • Open File > Settings > Project from the PyCharm menu.
  • Select your current project.
  • Click the Python Interpreter tab within your project tab.
  • Click the small + symbol to add a new library to the project.
  • Now type in the library to be installed, in your example Pandas, and click Install Package.
  • Wait for the installation to terminate and close all popup windows.

Here’s an analogous example:

Here’s a full guide on how to install a library on PyCharm.

  • How to Install a Library on PyCharm

Nerd Humor

Oh yeah, I didn’t even know they renamed it the Willis Tower in 2009, because I know a normal amount about skyscrapers. — xkcd (source)

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

ModuleNotFoundError: No module named ‘pip’ #5710

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

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.

Решение проблем с модулями и пакетами Python

Я с завидной регулярностью сталкиваюсь со всевозможными ошибками, так или иначе связанными с модулями Python. Существует огромное количество разнообразных модулей Python, которые разработчики активно используют, но далеко не всегда заботятся об установке зависимостей. Некоторые даже не удосуживаются их документировать. Параллельно существует две мажорные версии Python: 2 и 3. В разных дистрибутивах отдано предпочтение одной или другой версии, по этой причине самостоятельно установленную программу в зависимости от дистрибутива нужно при запуске предварять python или python2/python3. Например:

Причём обычно не происходит никаких проверок и угадали ли вы с выбором версии или нет вы узнаете только при появлении первых ошибок, вызванных неправильным синтаксисом программного кода для данной версии.

Также прибавляет путаницу то, что модули можно установить как из стандартного репозитория дистрибутивов, так и с помощью pip (инструмент для установки пакетов Python).

Цель этой заметки — рассмотреть некоторые характерные проблемы модулей Python. Все возможные ошибки вряд ли удастся охватить, но описанное здесь должно помочь понять, в каком примерно направлении двигаться.

Отсутствие модуля Python

Большинство ошибок модулей Python начинаются со строк:

В них трудно разобраться, поэтому поищите фразы вида:

  • ModuleNotFoundError: No module named
  • No module named
  • ImportError: No module named

За ними следует название модуля.

Поищите по указанному имени в системном репозитории, или попробуйте установить командой вида:

Пакет Python установлен, но программа его не видит

Причина может быть в том, что вы установили модуль для другой версии. Например, программа написана на Python3, а вы установили модуль с этим же названием, но написанный на Python2. В этом случае он не будет существовать для программы. Поэтому нужно правильно указывать номер версии.

Команда pip также имеет свои две версии: pip2 и pip3. Если версия не указана, то это означает, что используется какая-то из двух указанных (2 или 3) версий, которая является основной в системе. Например, сейчас в Debian и производных по умолчанию основной версией Python является вторая. Поэтому в репозитории есть два пакета: python-pip (вторая версия) и python3-pip (третья).

В Arch Linux и производных по умолчанию основной версией является третья, поэтому в репозиториях присутствует пакет python-pip (третья версия) и python2-pip (вторая).

Это же самое относится к пакетам Python и самому Python: если версия не указана, значит имеется ввиду основная для вашего дистрибутива версия. По этой причине многие пакеты в репозитории присутствуют с двумя очень похожими названиями.

Установлена новая версия модуля, но программа видит старую версию

Я несколько раз сталкивался с подобными необъяснимыми ошибками.

Иногда помогает удаление модуля командой вида:

Также попробуйте удалить его используя системный менеджер пакетов.

Если модуль вам нужен, попробуйте вновь установить его и проверьте, решило ли это проблему.

Если проблема не решена, то удалите все файлы модуля, обычно они расположены в папках вида:

  • /usr/lib/python2.7/site-packages/модуль
  • /usr/lib/python3.7/site-packages/модуль

Ошибки с фразой «AttributeError: ‘NoneType’ object has no attribute»

Ошибки, в которых присутствует слово AttributeError, NoneType, object has no attribute обычно вызваны не отсутствием модуля, а тем, что модуль не получил ожидаемого аргумента, либо получил неправильное число аргументов. Было бы правильнее сказать, что ошибка вызвана недостаточной проверкой данных и отсутствием перехвата исключений (то есть программа плохо написана).

В этих случаях обычно ничего не требуется дополнительно устанавливать. В моей практике частыми случаями таких ошибок является обращение программы к определённому сайту, но сайт может быть недоступен, либо API ключ больше недействителен, либо программа не получила ожидаемые данные по другим причинам. Также программа может обращаться к другой программе, но из-за ошибки в ней получит не тот результат, который ожидала, и уже это вызывает приведённые выше ошибки, которые мы видим.

Опять же, хорошо написанная программа в этом случае должна вернуть что-то вроде «информация не загружена», «работа программы N завершилась ошибкой» и так далее. Как правило, нужно разбираться с причиной самой первой проблемы или обращаться к разработчику.

Модуль установлен, но при обновлении или обращении к нему появляется ошибки

Это самая экзотическая ошибка, которая вызвана, видимо, повреждением файлов пакета. К примеру, при попытке обновления я получал ошибку:

При этом сам модуль установлен как следует из самой первой строки.

Проблема может решиться удалением всех файлов пакета (с помощью rm) и затем повторной установки.

К примеру в рассматриваемом случае, удаление:

После этого проблема с модулем исчезла.

Заключение

Пожалуй, это далеко не полный «справочник ошибок Python», но если вы можете сориентироваться, какого рода ошибка у вас возникла:

  • отсутствует модуль
  • модуль неправильной версии
  • модуль повреждён
  • внешняя причина — программа не получила ожидаемые данные

Так вот, если вы хотя бы примерно поняли главную причину, то вам будет проще понять, в каком направлении двигаться для её решения.

Почему я получаю ImportError: No module named pip ‘сразу после установки pip?

Я установил pip и ez setup. Я также проверил системный путь и вижу модуль в структуре папок. Тем не менее, когда я пытаюсь запустить команду pip, я получаю сообщение об ошибке импорта, в котором говорится, что нет модуля с именем pip. Я запускаю 32-битный питон на машине с windows7

Просто убедитесь, что вы включили python в переменную PATH Windows, затем запустите python -m ensurepip

После запуска get_pip.py с помощью встраивания python вам необходимо изменить свой pythonXX._pth файл. Добавьте Libsite-packages , чтобы получить что-то вроде этого:

Если вы этого не сделаете, вы получите эту ошибку:

ModuleNotFoundError: No module named ‘pip’

python-3.8.2-embed-amd64python.exe: No module named pip

Что решило проблему в моем случае, так это перейти к:

И запустите команду ниже:

  1. Откройте pythonxx.__pth файл, расположенный в папке Python.
  2. Отредактируйте содержимое (например, D:Pythonx.x.x на следующее):

Эта проблема возникает у меня, когда я пытался обновить версию pip. Это было решено с помощью следующих команд:

Вышеупомянутая команда восстанавливает пип, а упомянутая ниже обновляет его.

попробуйте ввести pip3 вместо pip. также для обновления pip не используйте pip3 в команде

может это поможет

оказалось, что у меня на ноутбуке было 2 версии python

обе команды работали для меня

оба с другим путем установки

только первый путь был в моей переменной% PATH%

ensurepip Модуль был добавлен в версии 3.4 , а затем портированном к 2.7.9.

Поэтому убедитесь, что ваша версия Python не ниже 2.7.9 при использовании Python 2 и не ниже 3.4 при использовании Python 3.

Мне помогло выполнение этих двух команд:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Я решил эту ошибку, установив правильные переменные пути

Я нашел этот пост, когда искал решение той же проблемы. Я использовал встроенный дистрибутив Python. В этом случае решение — раскомментировать import site файл python<version>._pth .

Я столкнулся с той же проблемой и решил, выполнив следующие действия.

1) Перейдите в свой пакет paython и переименуйте python37._pth в python37._pth.save.

3) затем запустите python get-pip.py

4) pip install django

Надеюсь на эту помощь

Я решил эту ошибку, загрузив исполняемый файл для python 3.7. Я загрузил встраиваемую версию и получил эту ошибку. Теперь это работает! : D

Если вы написали

тогда вы удалили pip вместо установки pip. Это могло быть причиной вашей проблемы.

Ответ Городецкого Дмитрия работает для меня.

Метод, который я собираюсь рассказать, может быть неправильным. Но этот метод решил мою проблему. Я перепробовал все решения на YouTube и методах StackOverflow.

Если у вас установлено две версии Python. Удалите один. У меня установлены версии Python 3.8.1 и 3.9.0. Я удалил версию 3.9.0 из каталога C.

Теперь перейдите в панель управления> Система и безопасность> Система> Расширенные настройки системы.

введите описание изображения здесь

Щелкните «переменные среды».

введите описание изображения здесь

Выберите путь и нажмите «изменить».

Теперь добавьте путь к python, а также путь к модулю pip. В моем случае это были c: python38 и c: python38 scripts

#python #windows-7 #pip

Вопрос:

Я установил установку pip и ez. Я также проверил системный путь и вижу модуль в структуре папок. Тем не менее, когда я пытаюсь запустить команду pip, я получаю сообщение об ошибке импорта, в котором говорится, что модуль с именем pip отсутствует. Я запускаю 32-битный python на машине windows7

Комментарии:

1. Просто используйте установщик python, и pip будет загружен вместе с ним.

Ответ №1:

Просто убедитесь, что у вас есть переменная пути включения python в Windows, а затем запустите python -m ensurepip

Комментарии:

1. Ошибка: python.exe: No module named ensurepip . Я использую последнюю версию 3.7.1.

2. @Subin_Learner Мне пришлось использовать установщик — ZIP-версия Python просто не работает с PIP afaict

3. @PeterX Да, вы правы. я использовал установщик, он работал.

4. не забудьте добавить C:Users…AppDataLocalProgramsPythonPython36Scripts к переменной PATH, чтобы вы могли использовать pip после

5. @PeterX, А что, если нельзя использовать установщик?

Ответ №2:

После запуска get_pip.py с python embedded вам необходимо изменить свой pythonXX._pth файл. Добавьте Libsite-packages , чтобы получить что-то вроде этого:

 pythonXX.zip
.
Libsite-packages
# Uncomment to run site.main() automatically
#import site
 

Если вы этого не сделаете, вы получите эту ошибку:

ModuleNotFoundError: Нет модуля с именем «pip»

или

python-3.8.2-embed-amd64python.exe: Нет модуля с именем pip

 λ pip
Traceback (most recent call last):
  File "runpy.py", line 193, in _run_module_as_main
  File "runpy.py", line 86, in _run_code
  File "python-3.8.2-embed-amd64Scriptspip.exe__main__.py", line 4, in <module>
ModuleNotFoundError: No module named 'pip'

λ python -m pip
python-3.8.2-embed-amd64python.exe: No module named pip
 

Комментарии:

1. Спасибо! Это помогает для моей установки Windows 10 embedded python 3.8!

2. Будьте осторожны, если вы используете virtualenv со встроенным python, окружающая среда отличается от обычной установки. Некоторые установки (с pip) могут завершиться с ошибкой типа ModuleNotFoundError: No module named '*******' .

Ответ №3:

Что решило проблему в моем случае, так это перейти к:

 cd C:Program FilesPython37Scripts
 

И выполните команду ниже:

 easy_install.exe pip
 

Комментарии:

1. Работал на меня с 2019 года. Огромное спасибо

2. У меня тоже получалось.

Ответ №4:

Комментарии:

1. Это работает; в моей установке каталог был Lib, а не lib.

2. Другой проблемой было bugs.python.org/issue34841 . Текущий каталог не был добавлен в путь. печать(sys.путь) не включала пустую строку.

Ответ №5:

Эта проблема возникает со мной, когда я пытался обновить версию pip. Это было решено с помощью следующих команд:

 python -m ensurepip
 

Приведенная выше команда восстанавливает pip и, как указано ниже, обновляет его.

 python -m pip install --upgrade pip 
 

Ответ №6:

попробуйте ввести pip3 вместо pip. также для обновления pip не используйте pip3 в команде

 python -m pip install -U pip
 

может быть, это поможет

Ответ №7:

оказалось, что у меня на ноутбуке было 2 версии python

обе команды работали на меня

 python -m ensurepip
py -m ensurepip
 

оба с другим путем установки

 c:toolspythonlibsite-packages
c:program files (x86)microsoft visual studiosharedpython36_64libsite-packages 
 

только первый путь был в моей переменной %PATH%

Ответ №8:

ensurepip Модуль был добавлен в версии 3.4, а затем перенесен обратно в 2.7.9.

Поэтому убедитесь, что ваша версия Python составляет не менее 2.7.9 при использовании Python 2 и не менее 3.4 при использовании Python 3.

Ответ №9:

Выполнение этих 2 команд помогло мне:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

python get-pip.py

Ответ №10:

Я решил эту ошибку, установив правильные переменные пути

     C:UsersnameAppDataLocalProgramsPythonPython37Scripts
    C:UsersnameAppDataLocalProgramsPythonPython37Libsite-packages
 

Ответ №11:

Я нашел этот пост, когда искал решение той же проблемы. Я использовал встроенный дистрибутив python. В этом случае решение состоит в том, чтобы раскомментировать import site файл python<version>._pth .

Ответ №12:

Я столкнулся с той же проблемой и решил ее, выполнив следующие действия

1) Перейдите в свой пакет paython и переименуйте «python37._pth» в python37._pth.сохранить

2) завиток https://bootstrap.pypa.io/get-pip.py -о get-pip.py

3) затем запустите python get-pip.py

4) pip устанавливает django

Надеюсь, это поможет

Ответ №13:

Если бы вы написали

 pip install --upgrade pip
 

и ты получил

 Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.2.1
    Uninstalling pip-20.2.1:
ERROR: Could not install packages due to an EnvironmentError...
 

затем вы удалили pip вместо установки pip.
Это может быть причиной вашей проблемы.

Ответ Городецкого Дмитрия работает для меня.

 python -m ensurepip
 

Ответ №14:

Я решил эту ошибку, загрузив исполняемый файл для python 3.7. Я загрузил встроенную версию и получил эту ошибку. Теперь это работает! 😀

Ответ №15:

Метод, о котором я собираюсь рассказать, может оказаться неправильным способом сделать это. Но этот метод решил мою проблему. Я перепробовал все решения на YouTube и методы StackOverflow.

  1. Если у вас установлены две версии python. Удалите один. У меня установлены версии python 3.8.1 и 3.9.0. Я удалил версию 3.9.0 из каталога C.
  2. Теперь перейдите в панель управления > Система и безопасность >> Система >>> Дополнительные системные настройки.

введите описание изображения здесь

Нажмите на «переменные среды».

введите описание изображения здесь

Выберите путь и нажмите «изменить».

Теперь добавьте путь к python, а также путь к модулю pip. В моем случае это было c:python38 и c:python38scripts

Этот метод решил мою проблему.

Понравилась статья? Поделить с друзьями:
  • No module named numpy python windows
  • No module named lxml python windows
  • No module named encodings python windows
  • No module named crypto python windows
  • No mci device open windows 10