Меню

Ошибка при установке модулей python

In my case, it is permission problem. The package was somehow installed with root rw permission only, other user just cannot rw to it!

nbro's user avatar

nbro

14.7k29 gold badges107 silver badges192 bronze badges

answered May 4, 2013 at 17:55

Paul Wang's user avatar

Paul WangPaul Wang

1,6361 gold badge12 silver badges19 bronze badges

7

I had the same problem: script with import colorama was throwing and ImportError, but sudo pip install colorama was telling me «package already installed».

My fix: run pip without sudo: pip install colorama. Then pip agreed it needed to be installed, installed it, and my script ran.

My environment is Ubuntu 14.04 32-bit; I think I saw this before and after I activated my virtualenv.

UPDATE: even better, use python -m pip install <package>. The benefit of this is, since you are executing the specific version of python that you want the package in, pip will unequivocally install the package in to the «right» python. Again, don’t use sudo in this case… then you get the package in the right place, but possibly with (unwanted) root permissions.

answered Jan 14, 2016 at 19:12

Dan H's user avatar

Dan HDan H

13.6k6 gold badges38 silver badges32 bronze badges

3

It’s the python path problem.

In my case, I have python installed in:

/Library/Frameworks/Python.framework/Versions/2.6/bin/python,

and there is no site-packages directory within the python2.6.

The package(SOAPpy) I installed by pip is located

/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/

And site-package is not in the python path, all I did is add site-packages to PYTHONPATH permanently.

  1. Open up Terminal

  2. Type open .bash_profile

  3. In the text file that pops up, add this line at the end:

    export PYTHONPATH=$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/
    
  4. Save the file, restart the Terminal, and you’re done

desertnaut's user avatar

desertnaut

55.9k21 gold badges133 silver badges163 bronze badges

answered Apr 22, 2014 at 17:45

user1552891's user avatar

user1552891user1552891

5095 silver badges4 bronze badges

3

I was able to correct this issue with a combined approach. First, I followed Chris’ advice, opened a command line and typed ‘pip show packagename’
This provided the location of the installed package.

Next, I opened python and typed ‘import sys’, then ‘sys.path’ to show where my python searches for any packages I import. Alas, the location shown in the first step was NOT in the list.

Final step, I typed ‘sys.path.append(‘package_location_seen_in_step_1’). You optionally can repeat step two to see the location is now in the list.

Test step, try to import the package again… it works.

The downside? It is temporary, and you need to add it to the list each time.

answered Apr 1, 2018 at 20:19

MJ_'s user avatar

MJ_MJ_

5141 gold badge5 silver badges10 bronze badges

The Python import mechanism works, really, so, either:

  1. Your PYTHONPATH is wrong,
  2. Your library is not installed where you think it is
  3. You have another library with the same name masking this one

answered Jan 12, 2013 at 17:19

Ali Afshar's user avatar

Ali AfsharAli Afshar

40.5k12 gold badges93 silver badges109 bronze badges

8

I have been banging my head against my monitor on this until a young-hip intern told me the secret is to «python setup.py install» inside the module directory.

For some reason, running the setup from there makes it just work.

To be clear, if your module’s name is «foo»:

[burnc7 (2016-06-21 15:28:49) git]# ls -l
total 1
drwxr-xr-x 7 root root  118 Jun 21 15:22 foo
[burnc7 (2016-06-21 15:28:51) git]# cd foo
[burnc7 (2016-06-21 15:28:53) foo]# ls -l
total 2
drwxr-xr-x 2 root root   93 Jun 21 15:23 foo
-rw-r--r-- 1 root root  416 May 31 12:26 setup.py
[burnc7 (2016-06-21 15:28:54) foo]# python setup.py install
<--snip-->

If you try to run setup.py from any other directory by calling out its path, you end up with a borked install.

DOES NOT WORK:

python /root/foo/setup.py install

DOES WORK:

cd /root/foo
python setup.py install

answered Jun 21, 2016 at 22:32

Locane's user avatar

LocaneLocane

2,7662 gold badges22 silver badges33 bronze badges

I encountered this while trying to use keyring which I installed via sudo pip install keyring. As mentioned in the other answers, it’s a permissions issue in my case.

What worked for me:

  1. Uninstalled keyring:
  • sudo pip uninstall keyring
  1. I used sudo’s -H option and reinstalled keyring:
  • sudo -H pip install keyring

bad_coder's user avatar

bad_coder

10.3k20 gold badges43 silver badges65 bronze badges

answered Sep 4, 2018 at 5:56

blackleg's user avatar

blacklegblackleg

3513 silver badges3 bronze badges

In PyCharm, I fixed this issue by changing the project interpreter path.

File -> Settings -> Project -> Project Interpreter

File -> Invalidate Caches… may be required afterwards.

miken32's user avatar

miken32

41k16 gold badges105 silver badges148 bronze badges

answered Feb 27, 2019 at 18:40

Amit D's user avatar

Amit DAmit D

611 silver badge2 bronze badges

1

I couldn’t get my PYTHONPATH to work properly. I realized adding export fixed the issue:

(did work)

export PYTHONPATH=$PYTHONPATH:~/test/site-packages

vs.

(did not work)

PYTHONPATH=$PYTHONPATH:~/test/site-packages

buczek's user avatar

buczek

2,0097 gold badges28 silver badges39 bronze badges

answered Dec 6, 2016 at 16:32

George Weber's user avatar

This problem can also occur with a relocated virtual environment (venv).

I had a project with a venv set up inside the root directory. Later I created a new user and decided to move the project to this user. Instead of moving only the source files and installing the dependencies freshly, I moved the entire project along with the venv folder to the new user.

After that, the dependencies that I installed were getting added to the global site-packages folder instead of the one inside the venv, so the code running inside this env was not able to access those dependencies.

To solve this problem, just remove the venv folder and recreate it again, like so:

$ deactivate
$ rm -rf venv
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install -r requirements.txt

Karl Knechtel's user avatar

Karl Knechtel

60.6k11 gold badges93 silver badges138 bronze badges

answered Nov 24, 2020 at 5:34

Jaikishan's user avatar

1

Something that worked for me was:

python -m pip install -user {package name}

The command does not require sudo. This was tested on OSX Mojave.

answered Aug 19, 2019 at 21:35

IShaan's user avatar

IShaanIShaan

831 gold badge1 silver badge6 bronze badges

0

In my case I had run pip install Django==1.11 and it would not import from the python interpreter.

Browsing through pip’s commands I found pip show which looked like this:

> pip show Django
Name: Django
Version: 1.11
...
Location: /usr/lib/python3.4/site-packages
...

Notice the location says ‘3.4’. I found that the python-command was linked to python2.7

/usr/bin> ls -l python
lrwxrwxrwx 1 root root 9 Mar 14 15:48 python -> python2.7

Right next to that I found a link called python3 so I used that. You could also change the link to python3.4. That would fix it, too.

answered Apr 6, 2017 at 14:05

Chris's user avatar

ChrisChris

5,4204 gold badges29 silver badges39 bronze badges

In my case it was a problem with a missing init.py file in the module, that I wanted to import in a Python 2.7 environment.

Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an init.py file.

answered Apr 26, 2019 at 9:26

jens_laufer's user avatar

jens_lauferjens_laufer

1572 silver badges10 bronze badges

Had this problem too.. the package was installed on Python 3.8.0 but VS Code was running my script using an older version (3.4)

fix in terminal:

py .py

Make sure you’re installing the package on the right Python Version

answered Nov 21, 2019 at 20:39

Aramich100's user avatar

I had colorama installed via pip and I was getting «ImportError: No module named colorama»

So I searched with «find», found the absolute path and added it in the script like this:

import sys
sys.path.append("/usr/local/lib/python3.8/dist-packages/")
import colorama 

And it worked.

answered Aug 25, 2020 at 13:01

DimiDak's user avatar

DimiDakDimiDak

4,3782 gold badges23 silver badges31 bronze badges

I had just the same problem, and updating setuptools helped:

python3 -m pip install --upgrade pip setuptools wheel

After that, reinstall the package, and it should work fine 🙂

The thing is, the package is built incorrectly if setuptools is old.

answered Jul 28, 2022 at 8:00

Ivan Konovalov's user avatar

If the other answers mentioned do not work for you, try deleting your pip cache and reinstalling the package. My machine runs Ubuntu14.04 and it was located under ~/.cache/pip. Deleting this folder did the trick for me.

answered Aug 7, 2019 at 1:29

Scrotch's user avatar

ScrotchScrotch

1,2561 gold badge15 silver badges25 bronze badges

Also, make sure that you do not confuse pip3 with pip. What I found was that package installed with pip was not working with python3 and vice-versa.

answered Nov 14, 2019 at 14:14

Devansh Maurya's user avatar

I had similar problem (on Windows) and the root cause in my case was ANTIVIRUS software! It has «Auto-Containment» feature, that wraps running process with some kind of a virtual machine.
Symptoms are: pip install somemodule works fine in one cmd-line window and import somemodule fails when executed from another process with the error

ModuleNotFoundError: No module named 'somemodule'

bad_coder's user avatar

bad_coder

10.3k20 gold badges43 silver badges65 bronze badges

answered May 7, 2018 at 6:42

Dima G's user avatar

Dima GDima G

1,82516 silver badges22 bronze badges

In my case (an Ubuntu 20.04 VM on WIN10 Host), I have a disordered situation with many version of Python installed and variuos point of Shared Library (installed with pip in many points of the File System). I’m referring to 3.8.10 Python version.
After many tests, I’ve found a suggestion searching with google (but’ I’m sorry, I haven’t the link). This is what I’ve done to resolve the problem :

  1. From shell session on Ubuntu 20.04 VM, (inside the Home, in my case /home/hduser), I’ve started a Jupyter Notebook session with the command «jupyter notebook».

  2. Then, when jupyter was running I’ve opened a .ipynb file to give commands.

  3. First : pip list —> give me the list of packages installed, and, sympy
    wasn’t present (although I had installed it with «sudo pip install sympy»
    command.

  4. Last with the command !pip3 install sympy (inside jupyter notebook
    session) I’ve solved the problem, here the screen-shot :
    enter image description here

  5. Now, with !pip list the package «sympy» is present, and working :
    enter image description here

answered Jan 9, 2022 at 11:43

Colonna Maurizio's user avatar

In my case, I assumed a package was installed because it showed up in the output of pip freeze. However, just the site-packages/*.dist-info folder is enough for pip to list it as installed despite missing the actual package contents (perhaps from an accidental deletion). This happens even when all the path settings are correct, and if you try pip install <pkg> it will say «requirement already satisfied».

The solution is to manually remove the dist-info folder so that pip realizes the package contents are missing. Then, doing a fresh install should re-populate anything that was accidentally removed

answered Oct 4, 2022 at 17:59

Addison Klinke's user avatar

Addison KlinkeAddison Klinke

9172 gold badges11 silver badges23 bronze badges

When you install via easy_install or pip, is it completing successfully? What is the full output? Which python installation are you using? You may need to use sudo before your installation command, if you are installing modules to a system directory (if you are using the system python installation, perhaps). There’s not a lot of useful information in your question to go off of, but some tools that will probably help include:

  • echo $PYTHONPATH and/or echo $PATH: when importing modules, Python searches one of these environment variables (lists of directories, : delimited) for the module you want. Importing problems are often due to the right directory being absent from these lists

  • which python, which pip, or which easy_install: these will tell you the location of each executable. It may help to know.

  • Use virtualenv, like @JesseBriggs suggests. It works very well with pip to help you isolate and manage the modules and environment for separate Python projects.

answered Jan 12, 2013 at 17:26

Ryan Artecona's user avatar

Ryan ArteconaRyan Artecona

5,8453 gold badges18 silver badges18 bronze badges

0

I had this exact problem, but none of the answers above worked. It drove me crazy until I noticed that sys.path was different after I had imported from the parent project. It turned out that I had used importlib to write a little function in order to import a file not in the project hierarchy. Bad idea: I forgot that I had done this. Even worse, the import process mucked with the sys.path—and left it that way. Very bad idea.

The solution was to stop that, and simply put the file I needed to import into the project. Another approach would have been to put the file into its own project, as it needs to be rebuilt from time to time, and the rebuild may or may not coincide with the rebuild of the main project.

answered Apr 17, 2016 at 19:08

ivanlan's user avatar

ivanlanivanlan

9596 silver badges8 bronze badges

I had this problem with 2.7 and 3.5 installed on my system trying to test a telegram bot with Python-Telegram-Bot.

I couldn’t get it to work after installing with pip and pip3, with sudo or without. I always got:

Traceback (most recent call last):
  File "telegram.py", line 2, in <module>
    from telegram.ext import Updater
  File "$USER/telegram.py", line 2, in <module>
    from telegram.ext import Updater
ImportError: No module named 'telegram.ext'; 'telegram' is not a package

Reading the error message correctly tells me that python is looking in the current directory for a telegram.py. And right, I had a script lying there called telegram.py and this was loaded by python when I called import.

Conclusion, make sure you don’t have any package.py in your current working dir when trying to import. (And read error message thoroughly).

answered Jan 10, 2017 at 7:09

Patrick B.'s user avatar

Patrick B.Patrick B.

11.5k8 gold badges58 silver badges98 bronze badges

I had a similar problem using Django. In my case, I could import the module from the Django shell, but not from a .py which imported the module.
The problem was that I was running the Django server (therefore, executing the .py) from a different virtualenv from which the module had been installed.

Instead, the shell instance was being run in the correct virtualenv. Hence, why it worked.

mx0's user avatar

mx0

6,10711 gold badges51 silver badges53 bronze badges

answered May 9, 2019 at 17:41

aleclara95's user avatar

This Works!!!

This often happens when module is installed to an older version of python or another directory, no worries as solution is simple.
— import module from directory in which module is installed.
You can do this by first importing the python sys module then importing from the path in which the module is installed

import sys
sys.path.append("directory in which module is installed")

import <module_name>

answered Jul 4, 2019 at 1:56

Terrence_Freeman's user avatar

Most of the possible cases have been already covered in solutions, just sharing my case, it happened to me that I installed a package in one environment (e.g. X) and I was importing the package in another environment (e.g. Y). So, always make sure that you’re importing the package from the environment in which you installed the package.

answered Aug 2, 2019 at 16:45

Pedram's user avatar

PedramPedram

2,3362 gold badges29 silver badges45 bronze badges

For me it was ensuring the version of the module aligned with the version of Python I was using.. I built the image on a box with Python 3.6 and then injected into a Docker image that happened to have 3.7 installed, and then banging my head when Python was telling me the module wasn’t installed…

36m for Python 3.6
bsonnumpy.cpython-36m-x86_64-linux-gnu.so

37m for Python 3.7 bsonnumpy.cpython-37m-x86_64-linux-gnu.so

answered Sep 18, 2019 at 15:43

mkst's user avatar

mkstmkst

5546 silver badges16 bronze badges

4

I know this is a super old post but for me, I had an issue with a 32 bit python and 64 bit python installed. Once I uninstalled the 32 bit python, everything worked as it should.

answered Sep 24, 2019 at 13:18

Moultrie's user avatar

I have solved my issue that same libraries were working fine in one project(A) but importing those same libraries in another project(B) caused error. I am using Pycharm as IDE at Windows OS.
So, after trying many potential solutions and failing to solve the issue, I did these two things (deleted «Venv» folder, and reconfigured interpreter):

1-In project(B), there was a folder named(«venv»), located in External Libraries/. I deleted that folder.

2-Step 1 (deleting «venv» folder) causes error in Python Interpreter Configuration, and
there is a message shown at top of screen saying «Invalid python interpreter selected
for the project» and «configure python interpreter», select that link and it opens a
new window. There in «Project Interpreter» drop-down list, there is a Red colored line
showing previous invalid interpreter. Now, Open this list and select the Python
Interpreter(in my case, it is Python 3.7). Press «Apply» and «OK» at the bottom and you
are good to go.

Note: It was potentially the issue where Virtual Environment of my Project(B) was not recognizing the already installed and working libraries.

answered Sep 29, 2019 at 12:06

Hasnain Haider's user avatar

I have a difficult time using pip to install almost anything. I’m new to coding, so I thought maybe this is something I’ve been doing wrong and have opted out to easy_install to get most of what I needed done, which has generally worked. However, now I’m trying to download the nltk library, and neither is getting the job done.

I tried entering

sudo pip install nltk

but got the following response:

/Library/Frameworks/Python.framework/Versions/2.7/bin/pip run on Sat May  4 00:15:38 2013
Downloading/unpacking nltk

  Getting page https://pypi.python.org/simple/nltk/
  Could not fetch URL [need more reputation to post link]: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>

  Will skip URL [need more reputation to post link]/simple/nltk/ when looking for download links for nltk

  Getting page [need more reputation to post link]/simple/
  Could not fetch URL https://pypi.python. org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>

  Will skip URL [need more reputation to post link] when looking for download links for nltk

  Cannot fetch index base URL [need more reputation to post link]

  URLs to search for versions for nltk:
  * [need more reputation to post link]
  Getting page [need more reputation to post link]
  Could not fetch URL [need more reputation to post link]: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>

  Will skip URL [need more reputation to post link] when looking for download links for nltk

  Could not find any downloads that satisfy the requirement nltk

No distributions at all found for nltk

Exception information:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/basecommand.py", line 139, in main
    status = self.run(options, args)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/commands/install.py", line 266, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/req.py", line 1026, in prepare_files
    url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/index.py", line 171, in find_requirement
    raise DistributionNotFound('No distributions at all found for %s' % req)
DistributionNotFound: No distributions at all found for nltk

--easy_install installed fragments of the library and the code ran into trouble very quickly upon trying to run it.

Any thoughts on this issue? I’d really appreciate some feedback on how I can either get pip working or something to get around the issue in the meantime.

ROMANIA_engineer's user avatar

asked May 4, 2013 at 4:29

contentclown's user avatar

1

I found it sufficient to specify the pypi host as trusted. Example:

pip install --trusted-host pypi.python.org pytest-xdist
pip install --trusted-host pypi.python.org --upgrade pip

This solved the following error:

  Could not fetch URL https://pypi.python.org/simple/pytest-cov/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) - skipping
  Could not find a version that satisfies the requirement pytest-cov (from versions: )
No matching distribution found for pytest-cov

Update April 2018:
To anyone getting the TLSV1_ALERT_PROTOCOL_VERSION error: it has nothing to do with trusted-host/verification issue of the OP or this answer. Rather the TLSV1 error is because your interpreter does not support TLS v1.2, you must upgrade your interpreter. See for example https://news.ycombinator.com/item?id=13539034, http://pyfound.blogspot.ca/2017/01/time-to-upgrade-your-python-tls-v12.html and https://bugs.python.org/issue17128.

Update Feb 2019:
For some it may be sufficient to upgrade pip. If the above error prevents you from doing this, use get-pip.py. E.g. on Linux,

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

More details at https://pip.pypa.io/en/stable/installing/.

answered Aug 12, 2016 at 1:16

Oliver's user avatar

OliverOliver

26.3k9 gold badges66 silver badges96 bronze badges

16

I used pip version 9.0.1 and had the same issue, all the answers above didn’t solve the problem, and I couldn’t install python / pip with brew for other reasons.

Upgrading pip to 9.0.3 solved the problem. And because I couldn’t upgrade pip with pip I downloaded the source and installed it manually.

  1. Download the correct version of pip from — https://pypi.org/simple/pip/
  2. sudo python3 pip-9.0.3.tar.gz — Install pip

Or you can install newer pip with:

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

El Developer's user avatar

El Developer

3,3201 gold badge20 silver badges40 bronze badges

answered Apr 12, 2018 at 14:12

rom's user avatar

romrom

9998 silver badges16 bronze badges

4

Pypi removed support for TLS versions less than 1.2

You need to re-install Pip, do

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

or for global Python:

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

BenJi's user avatar

BenJi

3534 silver badges11 bronze badges

answered Apr 22, 2018 at 15:10

Parth Choudhary's user avatar

2

I used pip3 version 9.0.1 and was unable to install any packages recently via the commandpip3 install.

Mac os version: EI Captain 10.11.5.

python version: 3.5

I tried the command:

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

It didn’t work for me.

So I uninstalled the older pip and installed the newest version10.0.0 by entering this:

python3 -m pip uninstall pip setuptools
curl https://bootstrap.pypa.io/get-pip.py | python3

Now my problem was solved.
If you are using the python2, you can substitute the python3 with python. I hope it also works for you.

By the way, for some rookies like me, you have to enter the code:
sudo -i

to gain the root right 🙂 Good luck!

answered Apr 15, 2018 at 9:28

Aachen's user avatar

AachenAachen

4214 silver badges5 bronze badges

2

You’re probably seeing this bug; see also here.

The easiest workaround is to downgrade pip to one that doesn’t use SSL: easy_install pip==1.2.1. This loses you the security benefit of using SSL. The real solution is to use a Python distribution linked to a more recent SSL library.

Community's user avatar

answered May 4, 2013 at 4:54

Danica's user avatar

DanicaDanica

28k6 gold badges89 silver badges120 bronze badges

9

Solution — Install any package by marking below hosts trusted

  • pypi.python.org
  • pypi.org
  • files.pythonhosted.org

Temporary solution

pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org {package name}

Permanent solution — Update your PIP(problem with version 9.0.1) to latest.

pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org pytest-xdist

python -m pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --upgrade pip

answered May 4, 2018 at 17:33

RollerCosta's user avatar

RollerCostaRollerCosta

4,8928 gold badges52 silver badges71 bronze badges

4

Another cause of SSL errors can be a bad system time – certificates won’t validate if it’s too far off from the present.

answered Jan 24, 2014 at 5:07

pidge's user avatar

pidgepidge

7927 silver badges25 bronze badges

1

I tried some of the popular answers, but still could not install any libraries/packages using pip install.

My specific error was 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain using Miniconda for Windows (installer Miniconda3-py37_4.8.3-Windows-x86.exe).

It finally works when I did this:
pip install -r requirements.txt --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org

Specifically, I added this to make it work: --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org

answered Aug 11, 2020 at 17:34

datchung's user avatar

datchungdatchung

3,08624 silver badges23 bronze badges

1

As posted above by blackjar, the below lines worked for me

pip --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org install xxx

You need to give all three --trusted-host options. I was trying with only the first one after looking at the answers but it didn’t work for me like that.

Blue's user avatar

Blue

22.2k7 gold badges56 silver badges89 bronze badges

answered Jul 31, 2018 at 11:50

abhi's user avatar

abhiabhi

1851 silver badge10 bronze badges

2

I solved a similar problem by adding the --trusted-host pypi.python.org option

answered Aug 9, 2016 at 20:51

Ruben's user avatar

RubenRuben

3315 silver badges13 bronze badges

0

To install any other package I have to use the latest version of pip, since the 9.0.1 has this SSL problem. To upgrade the pip by pip itself, I have to solve this SSL problem first.
To jump out of this endless loop, I find this only way that works for me.

  1. Find the latest version of pip in this page:
    https://pypi.org/simple/pip/
  2. Download the .whl file of the latest version.
  3. Use pip to install the latest pip. (Use your own latest version here)

sudo pip install pip-10.0.1-py2.py3-none-any.whl

Now the pip is the latest version and can install anything.

answered Apr 22, 2018 at 21:12

Jianzhe Gu's user avatar

Jianzhe GuJianzhe Gu

711 silver badge2 bronze badges

macOS Sierra 10.12.6. Wasn’t able to install anything through pip (python installed through homebrew). All the answers above didn’t work.

Eventually, upgrade from python 3.5 to 3.6 worked.

brew update
brew doctor #(in case you see such suggestion by brew)

then follow any additional suggestions by brew, i.e. overwrite link to python.

answered Apr 11, 2018 at 22:21

apatsekin's user avatar

apatsekinapatsekin

1,4649 silver badges12 bronze badges

1

I had the same problem. I just updated the python from 2.7.0 to 2.7.15. It solves the problem.

You can download here.

answered May 16, 2018 at 8:36

Günay Gültekin's user avatar

Günay GültekinGünay Gültekin

4,3168 gold badges32 silver badges36 bronze badges

1

tried

pip --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org install xxx 

and finally worked out, not quite understand why the domain pypi.python.org is changed.

answered Jun 21, 2018 at 14:11

blackjar's user avatar

You can also use conda to install packages: See http://conda.pydata.org

conda install nltk

The best way to use conda is to download Miniconda, but you can also try

pip install conda
conda init
conda install nltk

answered Jun 14, 2014 at 21:58

Travis Oliphant's user avatar

2

For me, the latest pip (1.5.6) works fine with the insecure nltk package if you just tell it not to be so picky about security:

pip install --upgrade --force-reinstall --allow-all-external --allow-unverified ntlk nltk

answered Sep 19, 2014 at 18:26

hobs's user avatar

hobshobs

17.8k10 gold badges78 silver badges100 bronze badges

2

If you’re connecting through a proxy, execute export https_proxy=<your_proxy> (on Unix or Git Bash) and then retry installation.

If you’re using Windows cmd, this changes to set https_proxy=<your_proxy>.

answered Jun 23, 2017 at 13:22

lostsoul29's user avatar

lostsoul29lostsoul29

7362 gold badges10 silver badges19 bronze badges

I did the following on Windows 7 to solve this problem.

c:Program FilesPython36Scripts> pip install beautifulsoup4 —trusted-host *

The —trusted-host seems to fix the SSL issue and * means every host.

Of course this does not work because you get other errors since there is no version that satisfies the requirement beautifulsoup4, but I don’t think that issue is related to the general question.

answered Jan 4, 2018 at 22:27

user9175040's user avatar

Just uninstall and reinstall pip packages it will workout for you guys.

Mac os version: high Sierra 10.13.6

python version: 3.7

So I uninstalled the older pip and installed the newest version10.0.0 by entering this:

python3 -m pip uninstall pip setuptools

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

Now my problem was solved. If you are using the python2, you can substitute the python3 with python. I hope it also works for you.

answered Sep 25, 2018 at 0:08

Yash Patel's user avatar

Yash PatelYash Patel

791 silver badge5 bronze badges

If it is only about nltk, I once faced similar problem. Try following guide for installation.
Install NLTK

If you are sure it doesn’t work with any other module, you may have problem with different versions of Python installed.

Or Give It a Try to see if it says pip is already installed.:

sudo apt-get install python-pip python-dev build-essential 

and see if it works.

answered May 4, 2013 at 7:09

akshayb's user avatar

akshaybakshayb

1,1992 gold badges17 silver badges44 bronze badges

I solved this issue with the following steps (on sles 11sp2)

zypper remove pip
easy_install pip=1.2.1
pip install --upgrade scons

Here are the same steps in puppet (which should work on all distros)

  package { 'python-pip':
    ensure => absent,
  }
  exec { 'python-pip':
    command  => '/usr/bin/easy_install pip==1.2.1',
    require  => Package['python-pip'],
  }
  package { 'scons': 
    ensure   => latest,
    provider => pip,
    require  => Exec['python-pip'],
  }

answered Jul 31, 2014 at 17:02

spuder's user avatar

spuderspuder

16.8k19 gold badges86 silver badges148 bronze badges

I had this with PyCharm and upgrading pip to 10.0.1 broke pip with «‘main’ not found in module» error.

I could solve this problem by installing pip 9.0.3 as seen in some other thread. These are the steps I did:

  1. Downloaded 9.0.3 version of pip from https://pypi.org/simple/pip/ (since pip couldn’t be used to install it).
  2. Install pip 9.0.3 from tar.gz
    python -m pip install pip-9.0.3.tar.gz

Everything started to work after that.

answered Apr 25, 2018 at 20:33

Yuriy M's user avatar

This video tutorial worked for me:

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

Generic Bot's user avatar

Generic Bot

3091 gold badge4 silver badges8 bronze badges

answered Jul 10, 2018 at 21:59

Golangg Go's user avatar

Try installing xcode and then using homebrew to install pipenv using «brew install pipenv».

Community's user avatar

answered Jun 14, 2021 at 15:23

MiThCeKi's user avatar

1

I have a difficult time using pip to install almost anything. I’m new to coding, so I thought maybe this is something I’ve been doing wrong and have opted out to easy_install to get most of what I needed done, which has generally worked. However, now I’m trying to download the nltk library, and neither is getting the job done.

I tried entering

sudo pip install nltk

but got the following response:

/Library/Frameworks/Python.framework/Versions/2.7/bin/pip run on Sat May  4 00:15:38 2013
Downloading/unpacking nltk

  Getting page https://pypi.python.org/simple/nltk/
  Could not fetch URL [need more reputation to post link]: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>

  Will skip URL [need more reputation to post link]/simple/nltk/ when looking for download links for nltk

  Getting page [need more reputation to post link]/simple/
  Could not fetch URL https://pypi.python. org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>

  Will skip URL [need more reputation to post link] when looking for download links for nltk

  Cannot fetch index base URL [need more reputation to post link]

  URLs to search for versions for nltk:
  * [need more reputation to post link]
  Getting page [need more reputation to post link]
  Could not fetch URL [need more reputation to post link]: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>

  Will skip URL [need more reputation to post link] when looking for download links for nltk

  Could not find any downloads that satisfy the requirement nltk

No distributions at all found for nltk

Exception information:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/basecommand.py", line 139, in main
    status = self.run(options, args)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/commands/install.py", line 266, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/req.py", line 1026, in prepare_files
    url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/index.py", line 171, in find_requirement
    raise DistributionNotFound('No distributions at all found for %s' % req)
DistributionNotFound: No distributions at all found for nltk

--easy_install installed fragments of the library and the code ran into trouble very quickly upon trying to run it.

Any thoughts on this issue? I’d really appreciate some feedback on how I can either get pip working or something to get around the issue in the meantime.

ROMANIA_engineer's user avatar

asked May 4, 2013 at 4:29

contentclown's user avatar

1

I found it sufficient to specify the pypi host as trusted. Example:

pip install --trusted-host pypi.python.org pytest-xdist
pip install --trusted-host pypi.python.org --upgrade pip

This solved the following error:

  Could not fetch URL https://pypi.python.org/simple/pytest-cov/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) - skipping
  Could not find a version that satisfies the requirement pytest-cov (from versions: )
No matching distribution found for pytest-cov

Update April 2018:
To anyone getting the TLSV1_ALERT_PROTOCOL_VERSION error: it has nothing to do with trusted-host/verification issue of the OP or this answer. Rather the TLSV1 error is because your interpreter does not support TLS v1.2, you must upgrade your interpreter. See for example https://news.ycombinator.com/item?id=13539034, http://pyfound.blogspot.ca/2017/01/time-to-upgrade-your-python-tls-v12.html and https://bugs.python.org/issue17128.

Update Feb 2019:
For some it may be sufficient to upgrade pip. If the above error prevents you from doing this, use get-pip.py. E.g. on Linux,

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

More details at https://pip.pypa.io/en/stable/installing/.

answered Aug 12, 2016 at 1:16

Oliver's user avatar

OliverOliver

26.3k9 gold badges66 silver badges96 bronze badges

16

I used pip version 9.0.1 and had the same issue, all the answers above didn’t solve the problem, and I couldn’t install python / pip with brew for other reasons.

Upgrading pip to 9.0.3 solved the problem. And because I couldn’t upgrade pip with pip I downloaded the source and installed it manually.

  1. Download the correct version of pip from — https://pypi.org/simple/pip/
  2. sudo python3 pip-9.0.3.tar.gz — Install pip

Or you can install newer pip with:

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

El Developer's user avatar

El Developer

3,3201 gold badge20 silver badges40 bronze badges

answered Apr 12, 2018 at 14:12

rom's user avatar

romrom

9998 silver badges16 bronze badges

4

Pypi removed support for TLS versions less than 1.2

You need to re-install Pip, do

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

or for global Python:

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

BenJi's user avatar

BenJi

3534 silver badges11 bronze badges

answered Apr 22, 2018 at 15:10

Parth Choudhary's user avatar

2

I used pip3 version 9.0.1 and was unable to install any packages recently via the commandpip3 install.

Mac os version: EI Captain 10.11.5.

python version: 3.5

I tried the command:

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

It didn’t work for me.

So I uninstalled the older pip and installed the newest version10.0.0 by entering this:

python3 -m pip uninstall pip setuptools
curl https://bootstrap.pypa.io/get-pip.py | python3

Now my problem was solved.
If you are using the python2, you can substitute the python3 with python. I hope it also works for you.

By the way, for some rookies like me, you have to enter the code:
sudo -i

to gain the root right 🙂 Good luck!

answered Apr 15, 2018 at 9:28

Aachen's user avatar

AachenAachen

4214 silver badges5 bronze badges

2

You’re probably seeing this bug; see also here.

The easiest workaround is to downgrade pip to one that doesn’t use SSL: easy_install pip==1.2.1. This loses you the security benefit of using SSL. The real solution is to use a Python distribution linked to a more recent SSL library.

Community's user avatar

answered May 4, 2013 at 4:54

Danica's user avatar

DanicaDanica

28k6 gold badges89 silver badges120 bronze badges

9

Solution — Install any package by marking below hosts trusted

  • pypi.python.org
  • pypi.org
  • files.pythonhosted.org

Temporary solution

pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org {package name}

Permanent solution — Update your PIP(problem with version 9.0.1) to latest.

pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org pytest-xdist

python -m pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --upgrade pip

answered May 4, 2018 at 17:33

RollerCosta's user avatar

RollerCostaRollerCosta

4,8928 gold badges52 silver badges71 bronze badges

4

Another cause of SSL errors can be a bad system time – certificates won’t validate if it’s too far off from the present.

answered Jan 24, 2014 at 5:07

pidge's user avatar

pidgepidge

7927 silver badges25 bronze badges

1

I tried some of the popular answers, but still could not install any libraries/packages using pip install.

My specific error was 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain using Miniconda for Windows (installer Miniconda3-py37_4.8.3-Windows-x86.exe).

It finally works when I did this:
pip install -r requirements.txt --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org

Specifically, I added this to make it work: --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org

answered Aug 11, 2020 at 17:34

datchung's user avatar

datchungdatchung

3,08624 silver badges23 bronze badges

1

As posted above by blackjar, the below lines worked for me

pip --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org install xxx

You need to give all three --trusted-host options. I was trying with only the first one after looking at the answers but it didn’t work for me like that.

Blue's user avatar

Blue

22.2k7 gold badges56 silver badges89 bronze badges

answered Jul 31, 2018 at 11:50

abhi's user avatar

abhiabhi

1851 silver badge10 bronze badges

2

I solved a similar problem by adding the --trusted-host pypi.python.org option

answered Aug 9, 2016 at 20:51

Ruben's user avatar

RubenRuben

3315 silver badges13 bronze badges

0

To install any other package I have to use the latest version of pip, since the 9.0.1 has this SSL problem. To upgrade the pip by pip itself, I have to solve this SSL problem first.
To jump out of this endless loop, I find this only way that works for me.

  1. Find the latest version of pip in this page:
    https://pypi.org/simple/pip/
  2. Download the .whl file of the latest version.
  3. Use pip to install the latest pip. (Use your own latest version here)

sudo pip install pip-10.0.1-py2.py3-none-any.whl

Now the pip is the latest version and can install anything.

answered Apr 22, 2018 at 21:12

Jianzhe Gu's user avatar

Jianzhe GuJianzhe Gu

711 silver badge2 bronze badges

macOS Sierra 10.12.6. Wasn’t able to install anything through pip (python installed through homebrew). All the answers above didn’t work.

Eventually, upgrade from python 3.5 to 3.6 worked.

brew update
brew doctor #(in case you see such suggestion by brew)

then follow any additional suggestions by brew, i.e. overwrite link to python.

answered Apr 11, 2018 at 22:21

apatsekin's user avatar

apatsekinapatsekin

1,4649 silver badges12 bronze badges

1

I had the same problem. I just updated the python from 2.7.0 to 2.7.15. It solves the problem.

You can download here.

answered May 16, 2018 at 8:36

Günay Gültekin's user avatar

Günay GültekinGünay Gültekin

4,3168 gold badges32 silver badges36 bronze badges

1

tried

pip --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org install xxx 

and finally worked out, not quite understand why the domain pypi.python.org is changed.

answered Jun 21, 2018 at 14:11

blackjar's user avatar

You can also use conda to install packages: See http://conda.pydata.org

conda install nltk

The best way to use conda is to download Miniconda, but you can also try

pip install conda
conda init
conda install nltk

answered Jun 14, 2014 at 21:58

Travis Oliphant's user avatar

2

For me, the latest pip (1.5.6) works fine with the insecure nltk package if you just tell it not to be so picky about security:

pip install --upgrade --force-reinstall --allow-all-external --allow-unverified ntlk nltk

answered Sep 19, 2014 at 18:26

hobs's user avatar

hobshobs

17.8k10 gold badges78 silver badges100 bronze badges

2

If you’re connecting through a proxy, execute export https_proxy=<your_proxy> (on Unix or Git Bash) and then retry installation.

If you’re using Windows cmd, this changes to set https_proxy=<your_proxy>.

answered Jun 23, 2017 at 13:22

lostsoul29's user avatar

lostsoul29lostsoul29

7362 gold badges10 silver badges19 bronze badges

I did the following on Windows 7 to solve this problem.

c:Program FilesPython36Scripts> pip install beautifulsoup4 —trusted-host *

The —trusted-host seems to fix the SSL issue and * means every host.

Of course this does not work because you get other errors since there is no version that satisfies the requirement beautifulsoup4, but I don’t think that issue is related to the general question.

answered Jan 4, 2018 at 22:27

user9175040's user avatar

Just uninstall and reinstall pip packages it will workout for you guys.

Mac os version: high Sierra 10.13.6

python version: 3.7

So I uninstalled the older pip and installed the newest version10.0.0 by entering this:

python3 -m pip uninstall pip setuptools

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

Now my problem was solved. If you are using the python2, you can substitute the python3 with python. I hope it also works for you.

answered Sep 25, 2018 at 0:08

Yash Patel's user avatar

Yash PatelYash Patel

791 silver badge5 bronze badges

If it is only about nltk, I once faced similar problem. Try following guide for installation.
Install NLTK

If you are sure it doesn’t work with any other module, you may have problem with different versions of Python installed.

Or Give It a Try to see if it says pip is already installed.:

sudo apt-get install python-pip python-dev build-essential 

and see if it works.

answered May 4, 2013 at 7:09

akshayb's user avatar

akshaybakshayb

1,1992 gold badges17 silver badges44 bronze badges

I solved this issue with the following steps (on sles 11sp2)

zypper remove pip
easy_install pip=1.2.1
pip install --upgrade scons

Here are the same steps in puppet (which should work on all distros)

  package { 'python-pip':
    ensure => absent,
  }
  exec { 'python-pip':
    command  => '/usr/bin/easy_install pip==1.2.1',
    require  => Package['python-pip'],
  }
  package { 'scons': 
    ensure   => latest,
    provider => pip,
    require  => Exec['python-pip'],
  }

answered Jul 31, 2014 at 17:02

spuder's user avatar

spuderspuder

16.8k19 gold badges86 silver badges148 bronze badges

I had this with PyCharm and upgrading pip to 10.0.1 broke pip with «‘main’ not found in module» error.

I could solve this problem by installing pip 9.0.3 as seen in some other thread. These are the steps I did:

  1. Downloaded 9.0.3 version of pip from https://pypi.org/simple/pip/ (since pip couldn’t be used to install it).
  2. Install pip 9.0.3 from tar.gz
    python -m pip install pip-9.0.3.tar.gz

Everything started to work after that.

answered Apr 25, 2018 at 20:33

Yuriy M's user avatar

This video tutorial worked for me:

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

Generic Bot's user avatar

Generic Bot

3091 gold badge4 silver badges8 bronze badges

answered Jul 10, 2018 at 21:59

Golangg Go's user avatar

Try installing xcode and then using homebrew to install pipenv using «brew install pipenv».

Community's user avatar

answered Jun 14, 2021 at 15:23

MiThCeKi's user avatar

1

Что означает ошибка ModuleNotFoundError: No module named

Что означает ошибка ModuleNotFoundError: No module named

Python ругается, что не может найти нужный модуль

Python ругается, что не может найти нужный модуль

Ситуация: мы решили заняться бигдатой и обработать большой массив данных на Python. Чтобы было проще, мы используем уже готовые решения и находим нужный нам код в интернете, например такой:

import numpy as np
x = [2, 3, 4, 5, 6]
nums = np.array([2, 3, 4, 5, 6])
type(nums)
zeros = np.zeros((5, 4))
lin = np.linspace(1, 10, 20)

Копируем, вставляем в редактор кода и запускаем, чтобы разобраться, как что работает. Но вместо обработки данных Python выдаёт ошибку:

❌ModuleNotFoundError: No module named numpy

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

Что это значит: Python пытается подключить библиотеку, которую мы указали, но не может её найти у себя.

Когда встречается: когда библиотеки нет или мы неправильно написали её название.

Что делать с ошибкой ModuleNotFoundError: No module named

Самый простой способ исправить эту ошибку — установить библиотеку, которую мы хотим подключить в проект. Для установки Python-библиотек используют штатную команду pip или pip3, которая работает так: pip install <имя_библиотеки>. В нашем случае Python говорит, что он не может подключить библиотеку Numpy, поэтому пишем в командной строке такое:

pip install numpy

Это нужно написать не в командной строке Python, а в командной строке операционной системы. Тогда компьютер скачает эту библиотеку, установит, привяжет к Python и будет ругаться на строчку в коде import numpy.

Ещё бывает такое, что библиотека называется иначе, чем указано в команде pip install. Например, для работы с телеграм-ботами нужна библиотека telebot, а для её установки надо написать pip install pytelegrambotapi. Если попробовать подключить библиотеку с этим же названием, то тоже получим ошибку:

Что означает ошибка ModuleNotFoundError: No module named

А иногда такая ошибка — это просто невнимательность: пропущенная буква в названии библиотеки или опечатка. Исправляем и работаем дальше.

Вёрстка:

Кирилл Климентьев

В Python может быть несколько причин возникновения ошибки ModuleNotFoundError: No module named ...:

  • Модуль Python не установлен.
  • Есть конфликт в названиях пакета и модуля.
  • Есть конфликт зависимости модулей Python.

Рассмотрим варианты их решения.

Модуль не установлен

В первую очередь нужно проверить, установлен ли модуль. Для использования модуля в программе его нужно установить. Например, если попробовать использовать numpy без установки с помощью pip install будет следующая ошибка:

Traceback (most recent call last):
   File "", line 1, in 
 ModuleNotFoundError: No module named 'numpy'

Для установки нужного модуля используйте следующую команду:

pip install numpy
# или
pip3 install numpy

Или вот эту если используете Anaconda:

conda install numpy

Учтите, что может быть несколько экземпляров Python (или виртуальных сред) в системе. Модуль нужно устанавливать в определенный экземпляр.

Конфликт имен библиотеки и модуля

Еще одна причина ошибки No module named — конфликт в названиях пакета и модуля. Предположим, есть следующая структура проекта Python:

demo-project
 └───utils
         __init__.py
         string_utils.py
         utils.py

Если использовать следующую инструкцию импорта файла utils.py, то Python вернет ошибку ModuleNotFoundError.


>>> import utils.string_utils
Traceback (most recent call last):
File "C:demo-projectutilsutils.py", line 1, in
import utils.string_utils
ModuleNotFoundError: No module named 'utils.string_utils';
'utils' is not a package

В сообщении об ошибке сказано, что «utils is not a package». utils — это имя пакета, но это также и имя модуля. Это приводит к конфликту, когда имя модуля перекрывает имя пакета/библиотеки. Для его разрешения нужно переименовать файл utils.py.

Иногда может существовать конфликт модулей Python, который и приводит к ошибке No module named.

Следующее сообщение явно указывает, что _numpy_compat.py в библиотеке scipy пытается импортировать модуль numpy.testing.nosetester.

Traceback (most recent call last):
   File "C:demo-projectvenv
Libsite-packages
         scipy_lib_numpy_compat.py", line 10, in
     from numpy.testing.nosetester import import_nose
 ModuleNotFoundError: No module named 'numpy.testing.nosetester'

Ошибка ModuleNotFoundError возникает из-за того, что модуль numpy.testing.nosetester удален из библиотеки в версии 1.18. Для решения этой проблемы нужно обновить numpy и scipy до последних версий.

pip install numpy --upgrade
pip install scipy --upgrade 

При попытке установки практически любой библиотеки через pip возникает ошибка:
На примере библиотеки requests:

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0499A760>: Failed to establish a new 
connection: [Errno 11002] getaddrinfo failed')': /packages/ca/91/6d9b8ccacd0412c08820f72cebaa4f0c0441b5cda699c90f618b6f8a1b42/requests-2.28.1-py3-none-any.whl
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0499A910>: Failed to establish a new 
connection: [Errno 11002] getaddrinfo failed')': /packages/ca/91/6d9b8ccacd0412c08820f72cebaa4f0c0441b5cda699c90f618b6f8a1b42/requests-2.28.1-py3-none-any.whl
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0499A9E8>: Failed to establish a new 
connection: [Errno 11002] getaddrinfo failed')': /packages/ca/91/6d9b8ccacd0412c08820f72cebaa4f0c0441b5cda699c90f618b6f8a1b42/requests-2.28.1-py3-none-any.whl
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0499AAC0>: Failed to establish a new 
connection: [Errno 11002] getaddrinfo failed')': /packages/ca/91/6d9b8ccacd0412c08820f72cebaa4f0c0441b5cda699c90f618b6f8a1b42/requests-2.28.1-py3-none-any.whl
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0499AB98>: Failed to establish a new 
connection: [Errno 11002] getaddrinfo failed')': /packages/ca/91/6d9b8ccacd0412c08820f72cebaa4f0c0441b5cda699c90f618b6f8a1b42/requests-2.28.1-py3-none-any.whl
ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/ca/91/6d9b8ccacd0412c08820f72cebaa4f0c0441b5cda699c90f618b6f8a1b42/requests-2.2
8.1-py3-none-any.whl (Caused by NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0499AC70>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

Однако, например с библиотекой aiogram всё работает исправно 🙂 Так же ошибка начала появляться только сегодня, вчера я мог устанавливать все библиотеки без труда через терминал
Как исправить эту ошибку для установки нужных мне библиотек?
Важно: я использую интерпретатор PyCharm, устанавливаю библиотеки через него, однако при установке через cmd происходит аналогичная ситуация и та же ошибка

Содержание

  1. Как исправить ошибку PIP, которая не распознается в командной строке Windows? [Новости MiniTool]
  2. Резюме :
  3. PIP не распознается
  4. Исправления для PIP Not Recognized
  5. Проверьте, добавлен ли PIP в переменную PATH
  6. Добавить PIP в переменную PATH
  7. Заключительные слова
  8. Питон не видит модули, не получается импортировать
  9. 1 ответ 1
  10. Всё ещё ищете ответ? Посмотрите другие вопросы с метками python modules или задайте свой вопрос.
  11. Связанные
  12. Похожие
  13. Подписаться на ленту
  14. Питон не видит модуль после установки его через pip install
  15. Решение проблем с модулями и пакетами Python
  16. Отсутствие модуля Python
  17. Пакет Python установлен, но программа его не видит
  18. Установлена новая версия модуля, но программа видит старую версию
  19. Ошибки с фразой «AttributeError: ‘NoneType’ object has no attribute»
  20. Модуль установлен, но при обновлении или обращении к нему появляется ошибки
  21. Заключение
  22. Ошибка «PIP» или «Python» не является внутренней или внешней командой Windows 10
  23. Простое решение проблемы в Windows 10

Как исправить ошибку PIP, которая не распознается в командной строке Windows? [Новости MiniTool]

How Fix Pip Is Not Recognized Windows Command Prompt

Резюме :

how fix pip is not recognized windows command prompt

При установке пакетов Python в командной строке вы можете получить сообщение об ошибке «pip не распознается как внутренняя или внешняя команда, работающая программа или командный файл». Как решить проблему? MiniTool покажу вам некоторые методы в этом посте.

PIP не распознается

PIP, Pip Installs Package, представляет собой стандартную систему управления пакетами. Он используется для установки и обработки программных пакетов, написанных на Python. По умолчанию в большинстве версий Python установлен PIP.

При установке пакетов Python в окне командной строки Windows покажет вам ошибку, в которой говорится, что «’pip’ не распознается как внутренняя или внешняя команда, работающая программа или командный файл».

Основные причины того, что PIP не распознается, заключаются в том, что установка PIP не добавляется в системную переменную или установка неправильно добавлена ​​в ваш PATH. Чтобы решить эту проблему, вы можете использовать следующие методы.

Исправления для PIP Not Recognized

Проверьте, добавлен ли PIP в переменную PATH

Во-первых, вы должны знать, добавлена ​​ли ваша установка PIP в переменную PATH. Просто сделайте это, выполнив следующие действия:

Добавить PIP в переменную PATH

Вот три варианта выполнения этой работы: использовать графический интерфейс Windows, командную строку и исполняемый установщик Python.

Графический интерфейс Windows

Команда «Выполнить» обеспечивает удобство доступа к некоторым конкретным программам. В этом посте показано 6 способов открыть окно «Выполнить».

how fix pip is not recognized windows command prompt 3

Шаг 1. Запустите командную строку.

Шаг 3: Затем запустите установочный пакет Python, чтобы проверить, исправлено ли «PIP не распознается как внутренняя или внешняя команда».

Использовать исполняемый установщик Python

Шаг 1: запустить python –version в окне CMD, чтобы проверить установленную версию Python.

Шаг 2: Перейдите на Python.org, чтобы загрузить ту же версию исполняемого установщика.

Шаг 4: Убедитесь, что выбрана опция pip.

Заключительные слова

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

Источник

Питон не видит модули, не получается импортировать

Я установил все нужные модули для проекта, они уже находятся в папке site-packages с питоном

N8ARf

mf6ML

Я использую python 3.9.5, 32 разрядности, после установки модулей, я перезагружал IDE, компьютер, и интерпретатор (я использую VSCode)

При запуске командная строка в IDE выдаёт это

Более современное решение: pip install pypiwin32 Это содержит файлы.whl, которые помогут установить в Windows. ответил(а) 4 месяца назад David Metcalfe

1 ответ 1

нашёл решение проблемы, вроде (ну по крайней мере этот импорт больше не подсвечивается жёлтым в VSC и не просит починить) итак к сути: пишем pip install cryptohash и заменяем from Crypto.Hash import SHA512 на from cryptohash import sha512 (в моём случае) программу не тестировал, ещё не пофиксил другие проблемы, поэтому работоспособность программы с этим методом незнаю.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками python modules или задайте свой вопрос.

Связанные

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

дизайн сайта / логотип © 2022 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2022.11.1.40614

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Питон не видит модуль после установки его через pip install

Я уже часов семь пытаюсь как-то сделать, чтобы он его увидел: и разные версии питона ставил и переменные среды прописывал (PATH, PYTHONHOME и PYTHONPATH), и в общем-то никуда не сдвинулся.

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

tickПосле установки компонента, делфи не видит его классы
requires rtl, vcl; Устанавливаю, всё нормально устанавливается, но не вылезает окно с.

Установить модуль msgpack через pip
У меня возникла такая проблема: пакет msgpack установлен (pip list отображает пакет версией 0.5.6).

Модуль Wi-Fi не видит сети после его смены. Не могу установить драйвера
Поменяли модуль Wi-Fi, после этого нетбук ASUS 1005 PXD не видит сети и не работает Bluetooth.

tickУстановить модуль selenium через pip на Windows
Привет программисты питон. есть проблема с установкой библиотеки селениум. версия питона 3.4.1.

Добавлено через 4 минуты
ещё надо попробовать установить модуль через pycharm, иногда помогает.

Добавлено через 4 минуты
Вероятно, вы установили библиотеку для другого интерпретатора. Для того, чтобы поставилось к нужному интерпретатору, попробуйте запустить pip следующим образом:

Добавлено через 12 минут
ещё тут что-то про интерпретатор https://stackoverflow.com/ques. in-pycharm
—-
ещё в cmd ввести советую
echo %PATH%
посмотреть все пути переменных окружений

Добавлено через 3 минуты
windows 10 использует power shell вместо cmd вроде

pip install
Когда ввожу pip install importhook Выдаёт ошибку: ImportError: cannot import name «HTTPSHandler»

Pip install pyinstaller
В чем проблема, форумчане? CMD с правами админа F:Python>pip install pyinstaller Collecting.

tickPip install Из директории Не работает
Подскажите что не так. Скачал дистрибутив selenium распаковал его и пытаюсь запустить в проект.

Источник

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

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

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

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

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

12 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

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

Источник

Ошибка «PIP» или «Python» не является внутренней или внешней командой Windows 10

Сегодня поговорим об установке Python и о первых проблемах с которыми могут столкнуться начинающие программисты. После установки Python все советую проверит правильность его установки введя в командной строке Python, после этого вы должны увидеть установленную версию питона. Так же вы сможете вводим простенькие команды и выполнять их через командную строку например, введя print(«привет»), код должен выполниться и отобразить просто «Привет».

Для установки различных модулей используется PIP, например, для установки requests в командной строке нужно ввести pip install requests. Вообще большинство пользователей после установки питона и введя в командной строке «PIP» или «Python» получает сообщение об ошибке «не является внутренней или внешней командой, исполняемой программой или пакетным файлом».

Решение данный проблемы очень простое, в интернете очень много ответов, но все они очень краткие, сжатые, без скриншотов. Разобраться новичку будет достаточно сложно. Большинство ответов имеют вот такой вид

«Вам нужно установить путь к pip в переменные окружения»

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

Простое решение проблемы в Windows 10

И так при вводе в командной строке PIP вы видите сообщение.

«PIP» не является внутренней или внешней командой, исполняемой программой или пакетным файлом

1 41

Тоже самое и с Python

«Python» не является внутренней или внешней командой, исполняемой программой или пакетным файлом

2 31

Вам нужно добавить значения в переменную Path, рассказывать что это не буду, просто открываем свойства компьютера и выбираем «Дополнительные параметры системы».

3 28

Далее в свойствах системы переходим во вкладку «Дополнительно» и снижу нажимаем «Переменные среды».

4 21

В открывшемся окне в верхней части отмечаем переменную «Path» и нажимаем изменить.

5 18

В поле «Значение переменной» дописываем путь до папки в которой у вас установлен Питон, в моем случае это С:Python, так же нужно указать путь до папки где лежит файл pip.exe у меня это С:PythonScripts. Дописываем через ; вот так.

Рекомендую изменять стандартный путь установки Питона на С:Python.

7 11

Теперь проверяем результат запускаем командную строку и пишем сначала «PIP».

8 8

Потом пробуем написать «Python», после шеврона (>>>) можно уже написать какой нибудь код например, print(«Привет!»).

9 3

Если выше описанное для вас сложно, то можно переустановить сам Питон, отметив в главном окне пункт «Add Python 3.9 to PATH».

6 15

В процессе установки все пути будут прописаны автоматически. Вот так можно избавиться от ошибки «не является внутренней или внешней командой, исполняемой программой или пакетным файлом», которая появляется в командной строке при вводе «PIP» или «Python».

Источник

You might encounter a problem when installing a Python package in the project settings or in the Python Package tool window. Eventually, most of the issues are out of IDE control as PyCharm uses the pip package manager to perform the actual installation.

This article provides troubleshooting tips and covers some typical cases.

Install a package using the Terminal

The most viable troubleshooting action is to try installing the problematic package on the selected Python interpreter using the terminal. If you get an identical error message, then the problem is not in the IDE and you should review the rationales and typical cases, or search for a solution on the Internet.

Install a package on a virtual environment

  1. Press Ctrl+Alt+S to open the IDE settings and select .

  2. Expand the list of the available interpreters and click Show All.

    Show all available interpreters

  3. Locate the target interpreter and press edit interpreter.

    Discover the interpreter path for the selected venv

    Copy or memorize the path of the virtual environment and close the dialogs.

  4. Open the terminal and run the following commands:

    source <venv path>/bin/activate
    pip install <package name>

    Installing a Python package on a virtual environment

  5. Inspect and parse the results.

Install a package on a Conda environment

  1. Open the terminal and run the following commands:

    Conda < 4.6

    Conda >= 4.6

    activate <conda env name>
    conda install <package name>

    conda activate <conda env name>
    conda install <package name>

    Conda < 4.6

    Conda >= 4.6

    source activate <conda env name>
    conda install <package name>

    conda activate <conda env name>
    conda install <package name>

    See Conda documentation for more information on how to activate an environment.

    Installing a Python package on a virtual environment

    One of the possible failure cases occurs when the target package is not available in the repositories supported by the Conda package manager.

    Fail to install a package on a Conda environment

  2. Inspect and parse the results.

Install a package on a system interpreter

  1. To check the path of the currently selected system interpreter that you were trying to install a package on, press Ctrl+Alt+S and go to .

  2. Expand the list of the project interpreters and scroll it down, then select the item.

    Selected Python interpreter

  3. Locate the interpreter and press edit interpreter.

    Discover the interpreter path for the selected venv

    Copy or memorize the path of the environment and close the dialogs.

  4. Open the terminal and run the following commands:

    cd <interpreter path>
    -m pip install <package name>

    Installing a Python package on a system environment

    You might need the admin privileges to install packages on a system interpreter.

  5. Inspect and parse the results.

Parse the results

Result

Action

The package cannot be installed because the Python version doesn’t satisfy the package requirement.

Try to create another Python interpreter that is based on the Python version that meets the requirement.

The package cannot be installed because you don’t have permissions to install it.

Try to install the package using super-user privileges, for example, sudo pip install <package name>.

The package cannot be installed because the package is not available in the repository that is supported by the selected package manager. Example: you’re trying to install a package that is not available in the Conda package manager repositories.

Try to configure another type of Python interpreter for your project and install the package on it. See how to add and modify a Python interpreter in Configure a Python interpreter.

The package cannot be installed and it matches one of the typical package installation failure cases.

Check the cases and apply related workarounds.

The package is successfully installed.

File an issue in the PyCharm issue tracker and provide explicit details about the case including all console output, error messages, and screenshots indicating that you tried to install the package on the same interpreter in the terminal and in the project settings or in the Python Packages tool window.

Review typical cases

Last modified: 16 December 2022

ModuleNotFoundError: no module named Python Error [Fixed]

When you try to import a module in a Python file, Python tries to resolve this module in several ways. Sometimes, Python throws the ModuleNotFoundError afterward. What does this error mean in Python?

As the name implies, this error occurs when you’re trying to access or use a module that cannot be found. In the case of the title, the «module named Python» cannot be found.

Python here can be any module. Here’s an error when I try to import a numpys module that cannot be found:

import numpys as np

Here’s what the error looks like:

image-341

Here are a few reasons why a module may not be found:

  • you do not have the module you tried importing installed on your computer
  • you spelled a module incorrectly (which still links back to the previous point, that the misspelled module is not installed)…for example, spelling numpy as numpys during import
  • you use an incorrect casing for a module (which still links back to the first point)…for example, spelling numpy as NumPy during import will throw the module not found error as both modules are «not the same»
  • you are importing a module using the wrong path

How to fix the ModuleNotFoundError in Python

As I mentioned in the previous section, there are a couple of reasons a module may not be found. Here are some solutions.

1. Make sure imported modules are installed

Take for example, numpy. You use this module in your code in a file called «test.py» like this:

import numpy as np

arr = np.array([1, 2, 3])

print(arr)

If you try to run this code with python test.py and you get this error:

ModuleNotFoundError: No module named "numpy"

Then it’s most likely possible that the numpy module is not installed on your device. You can install the module like this:

python -m pip install numpy

When installed, the previous code will work correctly and you get the result printed in your terminal:

[1, 2, 3]

2. Make sure modules are spelled correctly

In some cases, you may have installed the module you need, but trying to use it still throws the ModuleNotFound error. In such cases, it could be that you spelled it incorrectly. Take, for example, this code:

import nompy as np

arr = np.array([1, 2, 3])

print(arr)

Here, you have installed numpy but running the above code throws this error:

ModuleNotFoundError: No module named "nompy"

This error comes as a result of the misspelled numpy module as nompy (with the letter o instead of u). You can fix this error by spelling the module correctly.

3. Make sure modules are in the right casing

Similar to the misspelling issue for module not found errors, it could also be that you are spelling the module correctly, but in the wrong casing. Here’s an example:

import Numpy as np

arr = np.array([1, 2, 3])

print(arr)

For this code, you have numpy installed but running the above code will throw this error:

ModuleNotFoundError: No module named 'Numpy'

Due to casing differences, numpy and Numpy are different modules. You can fix this error by spelling the module in the right casing.

4. Make sure you use the right paths

In Python, you can import modules from other files using absolute or relative paths. For this example, I’ll focus on absolute paths.

When you try to access a module from the wrong path, you will also get the module not found here. Here’s an example:

Let’s say you have a project folder called test. In it, you have two folders demoA and demoB.

demoA has an __init__.py file (to show it’s a Python package) and a test1.py module.

demoA also has an __init__.py file and a test2.py module.

Here’s the structure:

└── test
    ├── demoA
        ├── __init__.py
    │   ├── test1.py
    └── demoB
        ├── __init__.py
        ├── test2.py

Here are the contents of test1.py:

def hello():
  print("hello")

And let’s say you want to use this declared hello function in test2.py. The following code will throw a module not found error:

import demoA.test as test1

test1.hello()

This code will throw the following error:

ModuleNotFoundError: No module named 'demoA.test'

The reason for this is that we have used the wrong path to access the test1 module. The right path should be demoA.test1. When you correct that, the code works:

import demoA.test1 as test1

test1.hello()
# hello

Wrapping up

For resolving an imported module, Python checks places like the inbuilt library, installed modules, and modules in the current project. If it’s unable to resolve that module, it throws the ModuleNotFoundError.

Sometimes you do not have that module installed, so you have to install it. Sometimes it’s a misspelled module, or the naming with the wrong casing, or a wrong path. In this article, I’ve shown four possible ways of fixing this error if you experience it.

I hope you learned from it 🙂



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

It’s not uncommon for new Pythonistas to have trouble installing packages and using their modules. Frustrating errors like this often arise, even if you think you’ve installed a package properly:

>>>

ImportError: No module named <package_name>

This is caused by the fact that the version of Python you’re running your script with is not configured to search for modules where you’ve installed them. This happens when you use the wrong installation of pip to install packages.

In general, each Python installation comes bundled with its own pip executable, used for installing packages. By default, that pip executable will install packages in a location where that specific Python installation can find them.

The problem is that it’s very common to have multiple Python interpreters installed (and by extension, multiple pip executables.) Depending on your shell’s PATH, running pip may invoke the pip executable linked to the version of Python you’re using, or to a different one. If the wrong pip is invoked, then the packages it installs will likely not be visible to the Python interpreter you’re using, causing the ImportError.

To use the version of pip specific to your desired Python version, you can use python -m pip. Here, python is the path to the desired Python interpreter, so something like /usr/local/bin/python3.7 -m pip will use the pip executable for /usr/local/bin/python3.7. However, this still has its limitations.

There are also other ways to get around this issue. You can modify your shell’s PATH so it uses the correct pip executable, or change the PYTHONPATH so that your desired version of Python can find the packages located in a different directory. But these can all get messy fast.

Instead, virtual environments are often used to isolate Python installations from one another. A virtual environment contains, among other things, a Python interpreter, a pip executable, and a site-packages directory, which is the standard location for most packages downloaded with pip.

By activating a virtual environment within your shell, you expose it to only the pip and Python executables installed within your virtual environments, ensuring that the right versions of both applications are invoked and that packages are always installed to the correct location. Virtual environments also allow you to run different versions of the same package with different projects, something not possible if you are using a global Python installation.

There are many different virtual environments to choose from. This course uses Conda, bundled with Anaconda. You can learn more about virtual environments in Working With Python Virtual Environments.

00:00

A common error that new Pythonistas will come across is that the packages they think they’ve installed are not actually being recognized by Python. This will present itself as an ImportError, meaning that the module you’ve tried to import cannot be located. To learn why this is, we have to take a little tour around our operating system.

00:25

When you run a Python program, what you’re really doing is running the Python interpreter and passing it your Python script to interpret and run. The Python interpreter is simply an executable file located somewhere within your system, meaning that it’s literally a program whose job it is to run your Python program. It’s kind of trippy if you think about it. On Windows, this is called python.exe, and on Mac and other Unix environments, it’s just an executable called python.

01:01

There’s a good chance that you’ve got multiple Python interpreters installed. In fact, macOS and most Linux distributions come bundled with an older version of Python, Python 2, which is used for internal system functionality.

01:17

That’s why—if you’ve ever set up a brand new macOS installation and tried to run Python in the terminal—you’ll see a prompt for Python 2. Aside from this built-in Python, you can install other Python versions, like Python 3—or more specifically, 3.7 or 3.8—and they will all live in different locations on your system.

01:42

This is important because new Python versions are not entirely backwards compatible with old versions. Just look at Python 2 versus 3 and how they differ regarding printing to stdout (standard out).

01:56

If you code a program with Python 3 and try to run it with 2, all of your print statements—among other things—will break. The same will happen if you code for Python 2 and try to run it in 3. Apple can’t replace Python 2 with 3 in macOS because the inner workings of macOS still rely on functionality that’s present in Python 2, and that functionality might not exist—or it’ll just be different—in Python 3.

02:28

It’s not worth their time to re-engineer the OS to use Python 3, so they just leave it alone.

02:37

Having the ability to install different Python interpreters on one system is great for compatibility with older software, but it can complicate things when trying to develop new software. That’s because almost every Python interpreter comes bundled with its own version of pip, the package manager you’ll learn about in the rest of this course.

03:00

In that pip application, we’ll install its packages to a specific folder on disk often called site-packages, which sometimes corresponds to a single pip executable.

03:14

This means that invoking the wrong pip executable within your terminal will result in packages being installed in the wrong location. If I accidentally run the pip executable that came with my Python 3.7 installation, the packages it installed may not be searched for by Python 3 because it may install to a different site-packages/ folder.

03:40

So then, how do we fix this? There are many ways around this—for example, by modifying your shell’s path so that it uses the correct pip executable, or changing the Python path so that your desired version of Python can find the packages located somewhere else.

03:58

But these can all get messy pretty quickly, so instead, I almost always recommend using what’s called a virtual environment.

04:09

A virtual environment is a folder containing—among many things—a Python interpreter for a specific version of Python, a pip executable for installing and managing packages, and a site-packages/ folder that corresponds to that exact Python interpreter and pip executable.

04:30

Everything you need to develop your application is self-contained within this folder, isolated from any other Python installations you may have on your system.

04:41

In fact, virtual environments often allow you to activate them from within the shell, temporarily blinding the shell from any other versions of pip and Python installed on your system.

04:55

And, you can have many different virtual environments using different Python versions and different sets of packages. A common practice is to create a different virtual environment for each Python project you work on. This is especially helpful when two different projects require different versions of the same package.

05:17

Having a separate virtual environment for each project will allow each one to use a different version of the package.

05:26

There are many tools you can use to create and manage virtual environments. My personal favorite is called Conda, which is often used in data science and scientific computing. Conda comes as a part of Anaconda, which gives you access to not only Python packages that can be installed with pip, but also its own package manager and package repository.

05:52

This is a course on pip, so I’m not going to go any further in-depth on virtual environments. If you’re interested in learning more, we’ve got a great article on realpython.com that will get you up and running with virtual environments.

06:07

I’ll have a link for that down in the video notes below. You don’t have to use a virtual environment to follow along, but I recommend doing so. It’s also important to note that while Anaconda does come with its own package manager, I won’t be using it in this course.

06:26

I’ll just use Anaconda to create a virtual environment with Python and pip.

06:32

Then, I’ll use pip as the package manager for our new virtual environment.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ятрогенная патология врачебные ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка при установке модов от джова