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
14.7k29 gold badges107 silver badges192 bronze badges
answered May 4, 2013 at 17:55
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 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.
-
Open up Terminal
-
Type open .bash_profile
-
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/ -
Save the file, restart the Terminal, and you’re done
desertnaut
55.9k21 gold badges133 silver badges163 bronze badges
answered Apr 22, 2014 at 17:45
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_MJ_
5141 gold badge5 silver badges10 bronze badges
The Python import mechanism works, really, so, either:
- Your PYTHONPATH is wrong,
- Your library is not installed where you think it is
- You have another library with the same name masking this one
answered Jan 12, 2013 at 17:19
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
![]()
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:
- Uninstalled keyring:
sudo pip uninstall keyring
- I used sudo’s
-Hoption and reinstalled keyring:
sudo -H pip install keyring
![]()
bad_coder
10.3k20 gold badges43 silver badges65 bronze badges
answered Sep 4, 2018 at 5:56
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
41.1k16 gold badges105 silver badges148 bronze badges
answered Feb 27, 2019 at 18:40
![]()
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
2,0097 gold badges28 silver badges39 bronze badges
answered Dec 6, 2016 at 16:32
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
60.6k11 gold badges93 silver badges138 bronze badges
answered Nov 24, 2020 at 5:34
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
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
![]()
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_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
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
![]()
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
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
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
![]()
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
10.3k20 gold badges43 silver badges65 bronze badges
answered May 7, 2018 at 6:42
![]()
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 :
-
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».
-
Then, when jupyter was running I’ve opened a .ipynb file to give commands.
-
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. -
Last with the command !pip3 install sympy (inside jupyter notebook
session) I’ve solved the problem, here the screen-shot :

-
Now, with !pip list the package «sympy» is present, and working :

answered Jan 9, 2022 at 11:43
![]()
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 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 $PYTHONPATHand/orecho $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, orwhich 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
pipto help you isolate and manage the modules and environment for separate Python projects.
answered Jan 12, 2013 at 17:26
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
![]()
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.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
6,10711 gold badges51 silver badges53 bronze badges
answered May 9, 2019 at 17:41
![]()
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
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
![]()
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
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
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
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.
![]()
asked May 4, 2013 at 4:29
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
![]()
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.
- Download the correct version of pip from — https://pypi.org/simple/pip/
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
3,3201 gold badge20 silver badges40 bronze badges
answered Apr 12, 2018 at 14:12
![]()
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
3534 silver badges11 bronze badges
answered Apr 22, 2018 at 15:10
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
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.
answered May 4, 2013 at 4:54
![]()
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
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
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
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
22.2k7 gold badges56 silver badges89 bronze badges
answered Jul 31, 2018 at 11:50
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
![]()
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.
- Find the latest version of pip in this page:
https://pypi.org/simple/pip/ - Download the
.whlfile of the latest version. - 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 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
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ü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
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
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
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
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
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 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
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
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:
- Downloaded 9.0.3 version of pip from https://pypi.org/simple/pip/ (since pip couldn’t be used to install it).
- 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
This video tutorial worked for me:
$ curl https://bootstrap.pypa.io/get-pip.py | python
![]()
Generic Bot
3091 gold badge4 silver badges8 bronze badges
answered Jul 10, 2018 at 21:59
![]()
Try installing xcode and then using homebrew to install pipenv using «brew install pipenv».
answered Jun 14, 2021 at 15:23
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.
![]()
asked May 4, 2013 at 4:29
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
![]()
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.
- Download the correct version of pip from — https://pypi.org/simple/pip/
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
3,3201 gold badge20 silver badges40 bronze badges
answered Apr 12, 2018 at 14:12
![]()
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
3534 silver badges11 bronze badges
answered Apr 22, 2018 at 15:10
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
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.
answered May 4, 2013 at 4:54
![]()
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
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
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
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
22.2k7 gold badges56 silver badges89 bronze badges
answered Jul 31, 2018 at 11:50
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
![]()
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.
- Find the latest version of pip in this page:
https://pypi.org/simple/pip/ - Download the
.whlfile of the latest version. - 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 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
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ü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
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
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
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
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
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 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
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
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:
- Downloaded 9.0.3 version of pip from https://pypi.org/simple/pip/ (since pip couldn’t be used to install it).
- 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
This video tutorial worked for me:
$ curl https://bootstrap.pypa.io/get-pip.py | python
![]()
Generic Bot
3091 gold badge4 silver badges8 bronze badges
answered Jul 10, 2018 at 21:59
![]()
Try installing xcode and then using homebrew to install pipenv using «brew install pipenv».
answered Jun 14, 2021 at 15:23
1

Что означает ошибка 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. Если попробовать подключить библиотеку с этим же названием, то тоже получим ошибку:

А иногда такая ошибка — это просто невнимательность: пропущенная буква в названии библиотеки или опечатка. Исправляем и работаем дальше.
Вёрстка:
Кирилл Климентьев
Содержание
- Что делать если pip не устанавливает пакеты
- Как исправить «Pip» не распознается как внутренняя или внешняя команда
- Причины ‘Pip‘ не распознается как внутренняя или внешняя управляющая программа или пакетный файл
- Установка Pip отсутствует в системе Переменная
- Установка была добавлена в ваш PATH неправильно
- Как исправить ‘Pip‘ не распознается как внутренняя или внешняя команда в Windows 10
- Исправление 1. Убедитесь, что Pip был добавлен в вашу переменную PATH
- Исправление 2. Добавьте пункт в переменную среды PATH
- Исправление 3. Откройте пакет Python без добавления переменной Pip
- Исправление 4. Убедитесь, что Pip включен в установку
- Как исправить ‘Pip‘ не распознается как внутренняя или внешняя команда в коде Visual Studio
- Решение 1. Убедитесь, что ‘Pip’ добавлен в вашу переменную PATH
- Исправить 2. Добавьте пункт в переменную среды PATH
- Исправление 3. Открытие пакета Python без добавления переменной pip
- Исправление 4. Убедитесь, что Pip включен в установку
- Переустановите Python, чтобы исправить ‘Pip’ не распознается как внутренняя или внешняя команда
- Pip теперь распознается
Что делать если pip не устанавливает пакеты
Здравствуйте,я хотел установить модули для python’а но pip выдает ошибки,как востановить работоспособность pip?

Идентифицировать и устранить указанную в ошибке проблему пробовал?

не получилось устранить ошибку по поиску в нете. вот сама ошибка: Traceback (most recent call last): File «/usr/bin/pip», line 6, in from pkg_resources import load_entry_point ModuleNotFoundError: No module named ‘pkg_resources’

Это модуль из состава setuptools. Есть идеи, как и чем ты сломал setuptools? Переустановить можешь?

идей нет,сам переставить не смогу.

при установке программ python выходят такие ошибки: предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/__pycache__/easy_install.cpython-37.opt-1.pyc предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/__pycache__/easy_install.cpython-37.pyc предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/easy_install.py предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/ предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/__init__.py предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/__pycache__/ предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/__pycache__/__init__.cpython-37.opt-1.pyc предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/__pycache__/__init__.cpython-37.pyc предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/__pycache__/py31compat.cpython-37.opt-1.pyc предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/__pycache__/py31compat.cpython-37.pyc предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/pkg_resources/py31compat.py предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/setuptools-41.2.0-py3.7.egg-info/ предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/setuptools-41.2.0-py3.7.egg-info/PKG-INFO предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/setuptools-41.2.0-py3.7.egg-info/SOURCES.txt предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/setuptools-41.2.0-py3.7.egg-info/dependency_links.txt предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/setuptools-41.2.0-py3.7.egg-info/entry_points.txt предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/setuptools-41.2.0-py3.7.egg-info/requires.txt предупреждение: не удалось получить информацию о файле для usr/lib/python3.7/site-packages/setuptools-41.2.0-py3.7.egg-info/top_level.txt предупреждение: не удалось получить информацию о файле для

Ищи, как в арче переустанавливать пакеты и переустанавливай setuptools.

В большинстве дистрибутивов Linux pip можно безопасно использовать только в virtualenv или в крайнем случае от пользователя с –user. Запуск pip от root за пределами virtualenv — верный способ заработать конфликты с системным менеджером пакетов. Так что переустанавливай arch полностью.

Проблема решается очень просто. Могу рассказать как.

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

С менеджером пакетов скорее всего нет, потому что pip кладёт в /usr/local даже при обновлении пакетов, которые через системный менеджер установлены, а вот проблем с совместимостью пакетов между собой огрести можно легко. Сам нарывался.
Источник
Как исправить «Pip» не распознается как внутренняя или внешняя команда

Pip Installs Packages (“pip”) – это система организации пакетов для установки и работы с программными пакетами Python. Обычно он используется для пакетов Python Package Index.
При установке пакетов Python многие пользователи сообщают о получении сообщение “’pip’“ не распознается как внутренняя или внешняя команда” и не знаете, как устранить неполадки. Если вы видите эту ошибку, прочитайте советы о том, как ее исправить.
Причины ‘Pip‘ не распознается как внутренняя или внешняя управляющая программа или пакетный файл
Давайте рассмотрим две наиболее распространенные причины этой ошибки:
Установка Pip отсутствует в системе Переменная
Чтобы команды Python запускались из командной строки Windows, путь установки pip необходимо добавить в системную переменную PATH. Он должен быть добавлен автоматически, если вы установили Python через установочный файл.
Установка была добавлена в ваш PATH неправильно
Если вы вручную добавили путь, проблема может быть просто опечатка. Одна пропущенная точка с запятой перед новым путем или лишний пробел где-нибудь вызовут ошибку.
Как исправить ‘Pip‘ не распознается как внутренняя или внешняя команда в Windows 10
Попробуйте следующие исправления, чтобы решить проблему в Windows 10:
Исправление 1. Убедитесь, что Pip был добавлен в вашу переменную PATH
Если вы уверены, что он был добавлен, продолжайте чтобы исправить 3.
Вот быстрый способ проверить:
- Откройте “Выполнить“ диалоговое окно, нажав клавишу Windows + R.

- Введите “cmd“ и нажмите Введите.

- для получения списка всех местоположений. добавленный в переменную PATH, введите “echo %PATH%“ в командную строку, затем нажмите Ввод.

- Если вы найдете путь вида “C:Python39Scripts” (в зависимости от вашей версии Python) путь был добавлен в переменную PATH.
Если пункт не был добавлен, попробуйте следующее исправление.
Исправление 2. Добавьте пункт в переменную среды PATH
Вот как вручную добавьте pip в среду PATH с помощью графического интерфейса Windows и командной строки. После добавления пути откройте новое командное окно и попробуйте установить пакет pip, чтобы увидеть, решена ли проблема.
Добавить pip в PATH с помощью графического интерфейса Windows:
- Откройте “Выполнить“ диалоговое окно, нажав клавишу Клавиша Windows + R.

- Введите “ sysdm.cpl“ и нажмите Ввод, чтобы открыть Свойства системы.

- Выберите вкладку Дополнительно, затем Переменные среды.
- Перейдите к Системные переменные и выберите Путь.
- Нажмите кнопку Изменить.
- Нажмите Создать.чтобы добавить путь установки pip. Расположение по умолчанию: “C:users“ваше имя пользователя“AppDataProgramsPythonPython39“ для Python 3.9.

Добавить пункт в PATH с помощью CMD:
- Откройте диалоговое окно Выполнить, нажав клавишу Windows + R.

- Чтобы открыть новое окно командной строки, введите “cmd“ и нажмите Ввод.

- Введите команду “setx PATH “%PATH%; C:Python39Scripts“ и нажмите Enter, чтобы запустить его.

Примечание. Если вы установили Python в другом месте, измените путь после “;“ соответственно.
Исправление 3. Откройте пакет Python без добавления переменной Pip
Выполните следующие действия, чтобы открыть установочные пакеты Python в CMD без добавления переменной pip:
- Нажмите клавишу Windows + R, чтобы откройте Выполнить.

- Введите “ cmd“ и нажмите Ввод, чтобы открыть командную строку.

- Введите команду “python -m pip install (имя пакета)“ и запустите его.

Исправление 4. Убедитесь, что Pip включен в установку
Некоторые установщики Python исключают pip из установки по умолчанию. Это можно исправить, изменив установку Python, включив в нее pip. Вот как это сделать:
- Нажмите клавишу Windows + R, чтобы открыть Выполнить.

- Введите “appwiz.cpl“ и Введите.

- В Программы и компоненты, щелкните правой кнопкой мыши Python и выберите Изменить.

- Выберите Изменить.

- В разделе Дополнительные функции установите флажок pip и нажмите Далее.

- Чтобы применить изменения, нажмите Установить.

- По завершении установки откройте окно CMD, чтобы проверить, можете ли вы установить пакет Python без появления ошибки.
Если вы все еще видите ошибку, перейдите к последнему разделу в этой статье приведены инструкции по удалению и переустановке Python 3.9.
Как исправить ‘Pip‘ не распознается как внутренняя или внешняя команда в коде Visual Studio
Если вы видите это сообщение об ошибке при работе с Visual Code, это обычно означает, что возникла проблема с установкой Python или PATH был задан неправильно. Воспользуйтесь следующими советами, чтобы решить эту проблему:
Решение 1. Убедитесь, что ‘Pip’ добавлен в вашу переменную PATH
Если вы уверены, что пункт был добавлен, перейдите к исправлению 3.
Чтобы проверить, что пункт был добавлен в вашу переменную PATH:
- Нажмите клавишу Windows + R, чтобы открыть Выполнить.

- Введите “cmd“ а затем нажмите Ввод для командной строки.

- Список местоположений, добавленных в вашей переменной PATH, введите “echo %PATH%“ и нажмите Ввод.

- Увидев путь типа “C:Python39Scripts“ означает, что путь был добавлен в переменную PATH.
Если пункт не был добавлен, попробуйте добавить его одним из следующих двух способов:
Исправить 2. Добавьте пункт в переменную среды PATH
Выполните следующие действия, чтобы добавить вручную pip в среду пути с помощью графического интерфейса Windows или CMD. После добавления пути откройте новое окно CMD и попробуйте установить пакет pip, чтобы увидеть, решена ли проблема.
Добавьте pip в PATH с помощью графического интерфейса Windows:
- Откройте “Выполнить” диалоговое окно, нажав клавишу Windows + R.

- Введите “sysdm.cpl” и нажмите “Ввод” для доступа к “Свойствам системы”

- Выберите “ Расширенный” вкладку, затем “Переменные среды”

- Перейдите в “Системные переменные” и выберите “Путь”

- Нажмите “Изменить&rdquo ;

- Нажмите “Создать” чтобы добавить путь установки pip. Расположение по умолчанию: “C:users”ваше имя пользователя”AppDataProgramsPythonPython39” для Python 3.9.

Добавить пункт в PATH с помощью CMD:
- Откройте диалоговое окно Выполнить, нажав клавишу Windows + R.

- Чтобы открыть новое окно командной строки, введите “cmd” и нажмите Ввод.

- Введите команду “setx PATH “%PATH%; C:Python39Scripts” и нажмите Enter, чтобы запустить его.

Исправление 3. Открытие пакета Python без добавления переменной pip
Выполните следующие действия, чтобы открыть установочные пакеты Python в CMD без добавления переменной pip:
- Откройте диалоговое окно Выполнить.

- Введите “cmd” и нажмите Ввод, чтобы открыть командную строку.

- Введите команду “python -m pip install (имя пакета)” и запустите его.

Исправление 4. Убедитесь, что Pip включен в установку
Некоторые установщики Python опускают pip из установки по умолчанию. Это можно исправить, изменив установку Python, включив в нее pip. Вот как это сделать:
- Нажмите клавишу Windows + R, чтобы открыть Выполнить.

- Введите “appwiz.cpl” и Введите.

- В Программа и функции, щелкните правой кнопкой мыши Python и выберите Изменить.

- Выберите Изменить.
В разделе Дополнительные функции установите флажок pip и нажмите Далее.

Если вы все еще видите ошибку, перейдите к последнему раздел этой статьи, чтобы узнать, как удалить и переустановить Python 3.9.
Переустановите Python, чтобы исправить ‘Pip’ не распознается как внутренняя или внешняя команда
Эта ошибка обычно означает наличие проблемы с установкой Python или неправильную настройку системной переменной PATH. Попробуйте переустановить Python и все его компоненты, чтобы устранить проблему. Самый простой способ — через исполняемый установщик Python. Вот как это сделать:
- откройте диалоговое окно Выполнить.

- Запустите “appwiz.cpl“ чтобы перейти к разделу Программы и компоненты.

- Прокрутите список программ вниз, чтобы найти установку Python.

- Щелкните его правой кнопкой мыши и выберите Удалить, затем следуйте инструкциям.

- После удаления Python перезагрузите компьютер и загрузите последнюю версию установщика Python для вашего ОС.

- Запустите установочный файл и убедитесь, что Флажок Добавить Python 3.x в PATH установлен, где x означает любую версию Python 3, которая у вас есть. >
- Выберите Настроить установку.

- В разделе Дополнительные функции убедитесь, что установлен флажок pip, затем нажмите Далее.

- Расположение по умолчанию можно оставить как есть, нажмите Установить.

- После завершения установки вам будет предложено перезагрузить компьютер.
- После перезагрузки компьютера попробуйте снова установить пакет Python.
Pip теперь распознается
“&lsquo ;пип’ не распознается как внутренняя или внешняя команда“ сообщение об ошибке распространено. Причина обычно заключается в том, что путь установки pip недоступен или неправильно добавлен в путь системной переменной. Есть несколько способов решить эту проблему. Вы можете добавить его вручную через графический интерфейс Windows или CMD, изменить установку Python, включив в нее pip, или удалить и переустановить Python, чтобы убедиться, что “pip“ параметры проверены.
Удалось ли вам распознать pip? Что вы сделали, чтобы решить проблему? Расскажите нам в разделе комментариев ниже.
Источник
В 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
| Введение | |
| Решенные проблемы |
Введение
Многие сложности возникают у новичков из-за того, что им никто не объяснил про
виртуальное окружение
.
Вы можете избавить себя от головной боли прочитав статью
virtualenv
или
venv
Установлено несколько версий Python
Итак, Вы установили python, pipe, pipenv, requests и ещё много чего, но
вдруг выяснили, что на компьютере уже не одна, а несколько версий python.
Например, у Вас установлены версии 2.7 и 3.5.
Когда Вы запускаете python, то хотите, чтобы работала последняя версия, но,
почему-то работает версия 2.7.
Выясним, как разобраться в этой ситуации.
Python -V и which python
Узнаем версию python которая вызывается командой python с флаго -V
python -V
Python 2.7.18rcl
Полезная команда, которую можно выполнить, чтобы узнать где расположен ваш Python — which
which python
/usr/bin/python
Как видите, в моей
Ubuntu
Python находится в /usr/bin/python и имеет версию 2.7.18rcl
Третий Python тоже установлен, посмотреть версию и директорию также просто
python3 -V
Python 3.9.5
which python3
/usr/bin/python3
Резюмируем: второй Python вызывается командой python а третий Python командой python3.
Обычно Python установлен в директорию /usr/bin
Ещё один способ получить эту информацию — использование команды type
type python3
python3 is hashed (/usr/bin/python3)
type python
python3 is hashed (/usr/bin/python)
Следующий способ — через sys.executable
здесь я для разнообразия настроил alias в .bashrc и теперь команда python эквивалентна python3
python
Python 3.8.5 (default, Jul 28 2020, 12:59:40)
[GCC 9.3.0] on linux
Type «help», «copyright», «credits» or «license» for more information.
>>> import sys
>>> sys.executable
‘/usr/bin/python3’
Если у вас уже был третий Python, например 3.8.5, а вы самостоятельно скачали и
установили более позднюю версию, например 3.9.1 как в
инструкции
то у вас будет два разных третьих Python.
Убедиться в этом можно изучив директорию
/usr/local/bin/
ls -la /usr/local/bin/
total 21648
drwxr-xr-x 2 root root 4096 Feb 4 11:08 .
drwxr-xr-x 10 root root 4096 Jul 31 2020 ..
lrwxrwxrwx 1 root root 8 Feb 4 11:08 2to3 -> 2to3-3.9
-rwxr-xr-x 1 root root 101 Feb 4 11:08 2to3-3.9
-rwxr-xr-x 1 root root 238 Feb 4 11:08 easy_install-3.9
lrwxrwxrwx 1 root root 7 Feb 4 11:08 idle3 -> idle3.9
-rwxr-xr-x 1 root root 99 Feb 4 11:08 idle3.9
-rwxr-xr-x 1 root root 229 Feb 4 11:08 pip3
-rwxr-xr-x 1 root root 229 Feb 4 11:08 pip3.9
lrwxrwxrwx 1 root root 8 Feb 4 11:08 pydoc3 -> pydoc3.9
-rwxr-xr-x 1 root root 84 Feb 4 11:08 pydoc3.9
lrwxrwxrwx 1 root root 9 Feb 4 11:08 python3 -> python3.9
-rwxr-xr-x 1 root root 22127472 Feb 4 11:05 python3.9
-rwxr-xr-x 1 root root 3087 Feb 4 11:08 python3.9-config
lrwxrwxrwx 1 root root 16 Feb 4 11:08 python3-config -> python3.9-config
which python3
/usr/local/bin/python3
which python3.9
/usr/local/bin/python3.9
В такой ситуации вам нужно специально указывать полную версию python3.9 для
запуска программ, либо настроить
alias
PATH
Если ни одна из команд pyhon и python3 не работает, бывает полезно проверить переменную PATH
echo $PATH
/home/andrei/.local/bin:/home/andrei/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
Как вы можете убедиться моя директория /usr/bin прописана в PATH
Если вам нужно добавить директорию в PATH читайте статью
«PATH в Linux»
или статью
«PATH в Windows»
Важно понимать, что если в каждой из директорий, упомянутых в PATH, будет установлено по какому-то Python выполняться
будет тот, который в первой директории.
Если нужно использовать Python из какой-то определённой директории, нужно прописать её путь. В этом
случае не обязательно наличие этого пути в PATH
/usr/bin/python3
Python 3.8.5 (default, Jul 28 2020, 12:59:40)
[GCC 9.3.0] on linux
Type «help», «copyright», «credits» or «license» for more information.
>>>
>>> говорит о том, что Python в интерактивном режиме.
Pip
Выясним куда смотрит
pip
pip -V
/home/andrei/.local/lib/python2.7/site-packages (python 2.7)
Как видите, pip смотрит в директорию python2.7 поэтому всё, что мы до этого
устанавливали командой pip install попало к версии 2.7
а версия 3.5 не имеет ни pipenv ни requests и, например,
протестировать интерфейсы
с её помощью не получится
Если вы выполнили pip -V и получили в ответ
Command ‘pip’ not found, but there are 18 similar ones.
Посмотрите что выдаст
pip3 -V
В моей
Ubuntu
результат такой
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)
Посмотреть куда pip установил пакет можно командой pip show
Проверим, куда установлен модуль requests, который пригодится нам для работы с
REST API
pip show requests
Name: requests
Version: 2.22.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.org
License: Apache 2.0
Location: /usr/lib/python3/dist-packages
Requires:
Required-by: yandextank, netort, influxdb
alias
Если вы работаете в
Linux
можете прописать alias python=python3
Установить дополнительную версию Python
Если вы осознанно хотите установить определённую версию Python в добавок к уже существующей выполните
Куда устанавливаются различные версии Python
Просмотрите содержимое /usr/local/bin
ls -la /usr/local/bin
Результат на моём ПК показывает, что здесь находится версия 3.5
total 23620
drwxr-xr-x 0 root root 512 Mar 19 18:16 .
drwxr-xr-x 0 root root 512 Mar 30 2017 ..
lrwxrwxrwx 1 root root 8 Mar 19 18:16 2to3 -> 2to3-3.5
-rwxrwxrwx 1 root root 101 Mar 19 18:16 2to3-3.5
lrwxrwxrwx 1 root root 7 Mar 19 18:16 idle3 -> idle3.5
-rwxrwxrwx 1 root root 99 Mar 19 18:16 idle3.5
lrwxrwxrwx 1 root root 8 Mar 19 18:16 pydoc3 -> pydoc3.5
-rwxrwxrwx 1 root root 84 Mar 19 18:16 pydoc3.5
lrwxrwxrwx 1 root root 9 Mar 19 18:16 python3 -> python3.5
-rwxr-xr-x 2 root root 12090016 Mar 19 18:13 python3.5
lrwxrwxrwx 1 root root 17 Mar 19 18:16 python3.5-config -> python3.5m-config
-rwxr-xr-x 2 root root 12090016 Mar 19 18:13 python3.5m
-rwxr-xr-x 1 root root 3071 Mar 19 18:16 python3.5m-config
lrwxrwxrwx 1 root root 16 Mar 19 18:16 python3-config -> python3.5-config
lrwxrwxrwx 1 root root 10 Mar 19 18:16 pyvenv -> pyvenv-3.5
-rwxrwxrwx 1 root root 236 Mar 19 18:16 pyvenv-3.5
Версия 2.7 скорее всего здесь /home/andrei/.local/lib/
ls -la /home/andrei/.local/lib/python2.7/site-packages/
Результат на моём ПК
total 1304
drwx—— 0 andrei andrei 512 Mar 19 13:19 .
drwx—— 0 andrei andrei 512 Mar 19 13:19 ..
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 asn1crypto
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 asn1crypto-0.24.0.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 certifi
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 certifi-2018.1.18.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 cffi
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 cffi-1.11.5.dist-info
-rwxrwxrwx 1 andrei andrei 783672 Mar 19 13:19 _cffi_backend.so
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 chardet
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 chardet-3.0.4.dist-info
-rw-rw-rw- 1 andrei andrei 10826 Mar 19 13:19 clonevirtualenv.py
-rw-rw-rw- 1 andrei andrei 11094 Mar 19 13:19 clonevirtualenv.pyc
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 cryptography
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 cryptography-2.2.dist-info
-rw-rw-rw- 1 andrei andrei 126 Mar 19 13:19 easy_install.py
-rw-rw-rw- 1 andrei andrei 315 Mar 19 13:19 easy_install.pyc
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 enum
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 enum34-1.1.6.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 idna
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 idna-2.6.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 ipaddress-1.0.19.dist-info
-rw-rw-rw- 1 andrei andrei 79852 Mar 19 13:19 ipaddress.py
-rw-rw-rw- 1 andrei andrei 75765 Mar 19 13:19 ipaddress.pyc
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 .libs_cffi_backend
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 OpenSSL
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 ordereddict-1.1.dist-info
-rw-rw-rw- 1 andrei andrei 4221 Mar 19 13:19 ordereddict.py
-rw-rw-rw- 1 andrei andrei 4388 Mar 19 13:19 ordereddict.pyc
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pathlib-1.0.1.dist-info
-rw-rw-rw- 1 andrei andrei 41481 Mar 19 13:19 pathlib.py
-rw-rw-rw- 1 andrei andrei 43650 Mar 19 13:19 pathlib.pyc
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pip
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pip-9.0.2.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pipenv
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pipenv-11.8.2.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pkg_resources
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pycparser
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pycparser-2.18.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 pyOpenSSL-17.5.0.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 requests
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 requests-2.18.4.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 setuptools
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 setuptools-39.0.1.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 six-1.11.0.dist-info
-rw-rw-rw- 1 andrei andrei 30888 Mar 19 13:19 six.py
-rw-rw-rw- 1 andrei andrei 30210 Mar 19 13:19 six.pyc
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 urllib3
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 urllib3-1.22.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 virtualenv-15.1.0.dist-info
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 virtualenv_clone-0.3.0.dist-info
-rw-rw-rw- 1 andrei andrei 99021 Mar 19 13:19 virtualenv.py
-rw-rw-rw- 1 andrei andrei 86676 Mar 19 13:19 virtualenv.pyc
drwxrwxrwx 0 andrei andrei 512 Mar 19 13:19 virtualenv_support
Существует несколько способов обойти эту проблему. Сперва рассмотрим использование
команды python3.
python3 -V
Python 3.5.0
Как мы только что смогли убедиться команда python3 использует новую версию Python.
Установим pip3
sudo apt install python3-pip
Проверим, что он установился в нужную директорию
pip3 -V
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)
Теперь установим pipenv
pip3 install pipenv
Советую также прочитать статьи
pip
,
sys.path
Установить пакет для определённой версии Python
Если у вас несколько версий Python и нужно установить какой-то пакет только
для определённой версии, назовём её X.X, воспользуйтесь командой
pythonX.X -m pip install название_пакета —user —ignore-installed
Инструкция по установке Python на хостинге
ModuleNotFoundError: No module named ‘urllib2’
Модуль urllib2 был разделён на urllib.request и urllib.error
Поэтому строку
import urllib2
Нужно заменить на
import urllib.request
import urllib.error
TabError: inconsistent use of tabs and spaces in indentation
Эта ошибка обычно вызвана тем, что нажатие TAB не эквивалентно трём пробелам.
Можно попробовать заменить все отступы на пробелы строго соблюдая равенство
количества пробелов везде где нужно.
ModuleNotFoundError: No module named ‘requests’
Эта ошибка обычно вызвана тем, что модуль requests
не установлен, либо установлен, но не для того python, который Вы запустили.
Например, для python2.6 установлен, а для python3 не установлен.
Можно попробовать установить модуль requests. Подробнее про это
я писал в статье Тестирование с помощью Python.
Потому что столкнулся с этой проблемой впервые именно при
тестировании
API
Если эта проблема возникла при использовании PyCharm
установите requests для Вашего проекта по следующей
инструкции
Перейдите в настройки проекта нажав
CTRL + ALT + S

Выберите раздел Project Interpreter

Нажмите на плюс в правой части экрана
Введите в стоку поиска название нужного модуля. В моём случае это requests

Должно открыться окно Available Packages
Нажмите кнопку Install Package

Дождитесь окончания установки

SyntaxError: Missing parentheses in call to ‘print’
Эта ошибка обычно появляется когда Вы пробуете в python 3 использовать print без скобок,
так как это работало в python 2
print data
В python 3 нужно использовать скобки
print (data)
TypeError: getsockaddrarg: AF_INET address must be tuple, not str
Эта ошибка обычно появляется когда Вы неправильно ставите кавычку,
указывая куда нужно подключиться.
Правильный вариант — указать кортеж (tuple), который выглядит следующим образом:
(ip, port), ip обычно в кавычках, порт без
Пример (‘10.6.0.100’, 10000)
sock.connect(('10.6.0.130' ,9090))
Ошибка возникает если взять в кавычки и ip и порт,
тогда вместо кортежа передаётся строка, на что и жалуется
интерпретатор.
sock.connect(('10.6.0.130 ,9090'))
Traceback (most recent call last):
File «send.py», line 4, in <module>
sock.connect((‘10.6.0.130,9090’))
TypeError: getsockaddrarg: AF_INET address must be tuple, not str
Не выполняется команда virtualenv
Если Вы только что установили
virtualenv
, но при попытке выполнить
virtualenv new_env
или
venv new_env
Вы получаете что-то в духе:
virtualenv : The term ‘virtualenv’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ virtualenv juha_env
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Попробуйте
python -m virtualenv new_env
Не активируется виртуальное окружение
Сначала разберём случай в чистом virtualenv потом перейдём к virtualenvwrapper-win
1. virtualenv
Вы под
Windows
и пытаетесь активировать Ваше виртуальное окружение, которое называется, допустим, test_env командой
test_envScriptsactivate.bat
И ничего не происходит
Вы пробуете
test_envScriptsactivate.ps1
И получаете
.test_envScriptsactivate.ps1 : File C:UsersAndreivirtualenvstest_envScriptsactivate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see
about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .test_envScriptsactivate.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
Нужно зайти в PowerShell в режиме администратора и выполнить
Set-ExecutionPolicy Unrestricted -Force
И выполните ещё раз
test_envScriptsactivate.ps1
Set-ExecutionPolicy -Scope CurrentUser Unrestricted -Force
2. virtualenvwrapper-win
Вы установили
virtualenvwrapper-win
и создали новое окружение
mkvirtualenv testEnv
created virtual environment CPython3.8.2.final.0-32 in 955ms
creator CPython3Windows(dest=C:UsersAndreiEnvstestEnv, clear=False, global=False)
seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=C:UsersAndreiAppDataLocalpypavirtualenvseed-app-datav1.0.1)
activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
Его видно в списке окружений
lsvirtualenv
dir /b /ad «C:UsersAndreiEnvs»
==============================================================================
testEnv
И
workon
его видит
workon
Pass a name to activate one of the following virtualenvs:
==============================================================================
testEnv
Чтобы активировать его вводим
workon testEnv
NameError: name ‘psutil’ is not defined
NameError: name ‘psutil’ is not defined
Подобные ошибки возникают если ещё не установили какую-то
библиотеку, но уже попробовали ей воспользоваться
sudo apt install -y python-psutil
| Сложности при работе с Python | |
| Python | |
| Установлено несколько версий Python | |
| Установить дополнительную версию Python | |
| Проверка системного пути | |
| Куда устанавливаются различные версии Python | |
| Установить пакет для определённой версии Python | |
| AttributeError: partially initialized module ‘datetime’ has no attribute ‘date’ | |
| ModuleNotFoundError: No module named ‘requests‘ | |
| ModuleNotFoundError: No module named ‘urllib2‘ | |
| ModuleNotFoundError: No module named numpy | |
| SyntaxError: Missing parentheses in call to ‘print’ | |
| SyntaxError: Non-ASCII character | |
| TabError: inconsistent use of tabs and spaces in indentation | |
| TypeError: getsockaddrarg: AF_INET address must be tuple, not str | |
| TypeError: unsupported operand type(s) for +: | |
| TypeError: module object is not callable | |
| TypeError: ‘str’ object is not callable | |
| TypeError: __init__() got an unexpected keyword argument ‘capture_output’ | |
| TypeError: ‘generator’ object is not subscriptable | |
| virtualenv : The term ‘virtualenv’ is not recognized | |
| Не активируется виртуальное окружение | |
| SSL module is not available | |
| UnicodeDecodeError: ‘charmap’ codec can’t decode byte 0x90 in position |