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

I’ve just installed python 3.6 which comes with pip

However, in Windows command prompt, when I do: ‘pip install bs4’ it returns ‘SyntaxError: invalid syntax’ under the install word.

Typing ‘python’ returns the version, which means it is installed correctly. What could be the problem?

Daniel Roseman's user avatar

asked Dec 4, 2017 at 11:59

zgg6a's user avatar

6

try this.

python -m  pip ...

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

Sometimes the OS can’t find pip so python or py -m may solve the problem because it is python itself searching for pip.

T.Todua's user avatar

T.Todua

52.5k19 gold badges233 silver badges236 bronze badges

answered Dec 4, 2017 at 12:17

Tiago_nes's user avatar

Tiago_nesTiago_nes

8437 silver badges30 bronze badges

1

You need to be in the specific folder where pip.exe exists, then do the following steps:

  1. open cmd.exe
  2. write the following command:
    cd "<Path to the python folder>"

or in my case, i wrote

    cd C:UsersusernameAppDataLocalProgramsPythonPython37-32Scripts
  1. then write the following command
    pip install *anypackage*

Oztaco's user avatar

Oztaco

3,34911 gold badges45 silver badges83 bronze badges

answered Apr 25, 2019 at 16:46

Dipak's user avatar

DipakDipak

1573 silver badges8 bronze badges

1

Don’t enter in the python shall, Install in the command directory.

Not inside the python pip cannot be installed inside the python.

Even in the version 3.+ you don’t have to write the python 3 instead just python.

which looks like

python -m pip install --upgrade pip

and then install others

python -m pip install jupyter

Intsab Haider's user avatar

answered Jul 2, 2019 at 5:43

vidyasagar mulge's user avatar

Try running cmd as administrator (in the menu that pops up after right-clicking) and/or
entering «pip» alone and then

answered Jul 5, 2018 at 14:41

David Ordman's user avatar

1

«D:Program FilesPyScriptspip.exe» install numpy -U

YOUR PATH to pip.exe in Python folder + install + YOUR LIB + -U

enter image description here

answered Aug 19, 2019 at 7:34

Roman Shubenko's user avatar

The OS is not recognizing ‘python’ command. So try ‘py’

Use ‘py -m pip’

answered Jun 22, 2020 at 4:20

Maxwel Jose's user avatar

The problem is the OS can’t find Pip. Pip helps you install packages
MODIFIED SOME GREAT ANSWERS TO BE BETTER

Method 1 Go to path of python, then search for pip

  1. open cmd.exe
  2. write the following command:

E.g

cd C:UsersUsernameAppDataLocalProgramsPythonPython37-32

In this directory, search pip with python -m pip then install package

E.g

python -m pip install ipywidgets

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

OR

GO TO scripts from CMD. This is where Pip stays :)

cd C:UsersUser nameAppDataLocalProgramsPythonPython37-32Scripts>

Then

pip install anypackage

answered Jun 29, 2020 at 16:31

VICTOR STEVE's user avatar

I had this error too!
I found the problem:
it had error cause i opened cmd then entered python then pip!!
you shouldn’t enter python!
just open cmd then write «pip install bs4»

answered Nov 7, 2021 at 18:56

zahra's user avatar

zahrazahra

111 bronze badge

0

  1. First go to python directory where it was installed on your windows machine by using

    cmd

  2. Then go ahead as i did in the picture

enter image description here

answered Dec 4, 2017 at 12:10

Land Owner's user avatar

Try:

pip3 install bs4

If you have python2 installed you typically have to make sure you are using the correct version of pip.

answered Dec 4, 2017 at 12:14

Dean Coakley's user avatar

Dean CoakleyDean Coakley

1,6432 gold badges10 silver badges25 bronze badges

I use Enthought Canopy for my python, at first I used «pip install —upgrade pip», it showed a syntax error like yours, then I added a «!» in front of the pip, then it finally worked.

answered Jun 8, 2018 at 2:17

owenhe's user avatar

You can also go into the directory where you have your pip.exe or pip3.exe located. For me it was on my D drive so here is what I did:

D:>cd python

D:python>cd Scripts

D:pythonScripts>pip3.exe install tweepy

Hope it helps

answered Oct 10, 2019 at 1:26

Kelly Le's user avatar

Chances are you are in the Python interpreter. Happens sometimes if you give
this (Python) command in cmd.exe just to check the version of Python and you so happen to forget to come out.

Try this command

exit()
pip install xyz

David Buck's user avatar

David Buck

3,72335 gold badges31 silver badges35 bronze badges

answered May 24, 2020 at 7:34

shubhamsarohi's user avatar

The resolution is pretty easy, altough it took me a while to figure it out.

Two ways to solve this:

1 — Short one

Open your CMD and write

pip install module 
or
python -m install module

2 — Longest one

Open your CMD and check your Python version:

python

After you confirm you are in the correct version, still in the prompt write:

exit()

After that write:

pip install module 
or
python -m install module

That will do the work.

answered Mar 20, 2021 at 4:21

Vinicius Raphael's user avatar

I found that you can download and install pip directly by running:

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

Then you can run

python3 get-pip.py

And check the version using:

pip3 --version

I was then able to install Django

pip install Django

answered Apr 18, 2021 at 11:58

Yuri.teacher.English's user avatar

When I use type pip install yfinance in terminal (cmd) on Mac, it shows

SyntaxError: invalid syntax pip -install yfinance File "<stdin>", line 1
    pip -install yfinance
                 ^
SyntaxError: invalid syntax

And, I finally open the Spyder, one of the development environments of python, in Anaconda Navigator.

Hadar's user avatar

Hadar

6404 silver badges16 bronze badges

answered Oct 7, 2022 at 21:58

Jamie's user avatar

In windows, you have to run pip install command from( python path)/ scripts path in cmd prompt

C:/python27/scripts

pip install pandas

Community's user avatar

answered Dec 4, 2017 at 14:42

Sridevi Amit B's user avatar

You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)

answered Dec 4, 2017 at 12:01

Elliot's user avatar

ElliotElliot

3081 silver badge8 bronze badges

5

I’m having trouble installing python modules using pip. Below is the output from the command window:

Note that I installed pip immediately before trying to install GDAL module.

I am on a w7 64bit machine running python 2.7

    Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:UsersjnunnDesktop>python get-pip.py
Downloading/unpacking pip
Downloading pip-1.2.1.tar.gz (102Kb): 102Kb downloaded
Running setup.py egg_info for package pip

warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.txt' found under directory
'docs_build'
no previously-included directories found matching 'docs_build_sources'
Installing collected packages: pip
Running setup.py install for pip

warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.txt' found under directory
'docs_build'
no previously-included directories found matching 'docs_build_sources'
Installing pip-script.py script to C:Python26ArcGIS10.1Scripts
Installing pip.exe script to C:Python26ArcGIS10.1Scripts
Installing pip.exe.manifest script to C:Python26ArcGIS10.1Scripts
Installing pip-2.7-script.py script to C:Python26ArcGIS10.1Scripts
Installing pip-2.7.exe script to C:Python26ArcGIS10.1Scripts
Installing pip-2.7.exe.manifest script to C:Python26ArcGIS10.1Scripts
Successfully installed pip
Cleaning up...

C:UsersjnunnDesktop>pip install gdal
Downloading/unpacking gdal
Downloading GDAL-1.9.1.tar.gz (420kB): 420kB downloaded
Running setup.py egg_info for package gdal

Installing collected packages: gdal
Running setup.py install for gdal
building 'osgeo._gdal' extension
c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.exe /c /nologo
/Ox /MD /W3 /GS- /DNDEBUG -I../../port -I../../gcore -I../../alg -I../../ogr/ -I
C:Python26ArcGIS10.1include -IC:Python26ArcGIS10.1PC -IC:Python26ArcGIS1
0.1libsite-packagesnumpycoreinclude /Tpextensions/gdal_wrap.cpp /Fobuildte
mp.win32-2.7Releaseextensions/gdal_wrap.obj
gdal_wrap.cpp
c:Program Files (x86)Microsoft Visual Studio 9.0VCINCLUDExlocale(342) :
warning C4530: C++ exception handler used, but unwind semantics are not enabled
. Specify /EHsc
extensions/gdal_wrap.cpp(2853) : fatal error C1083: Cannot open include file
: 'cpl_port.h': No such file or directory
error: command '"c:Program Files (x86)Microsoft Visual Studio 9.0VCBINc
l.exe"' failed with exit status 2
Complete output from command C:Python26ArcGIS10.1python.exe -c "import se
tuptools;__file__='c:\users\jnunn\appdata\local\temp\pip-build\gdal\setu
p.py';exec(compile(open(__file__).read().replace('rn', 'n'), __file__, 'exec'
))" install --record c:usersjnunnappdatalocaltemppip-f7tgze-recordinstall
-record.txt --single-version-externally-managed:
running install

running build

running build_py

creating build

creating buildlib.win32-2.7

copying gdal.py -> buildlib.win32-2.7

copying ogr.py -> buildlib.win32-2.7

copying osr.py -> buildlib.win32-2.7

copying gdalconst.py -> buildlib.win32-2.7

copying gdalnumeric.py -> buildlib.win32-2.7

creating buildlib.win32-2.7osgeo

copying osgeogdal.py -> buildlib.win32-2.7osgeo

copying osgeogdalconst.py -> buildlib.win32-2.7osgeo

copying osgeogdalnumeric.py -> buildlib.win32-2.7osgeo

copying osgeogdal_array.py -> buildlib.win32-2.7osgeo

copying osgeoogr.py -> buildlib.win32-2.7osgeo

copying osgeoosr.py -> buildlib.win32-2.7osgeo

copying osgeo__init__.py -> buildlib.win32-2.7osgeo

running build_ext

building 'osgeo._gdal' extension

creating buildtemp.win32-2.7

creating buildtemp.win32-2.7Release

creating buildtemp.win32-2.7Releaseextensions

c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.exe /c /nologo /Ox
/MD /W3 /GS- /DNDEBUG -I../../port -I../../gcore -I../../alg -I../../ogr/ -IC:P
ython26ArcGIS10.1include -IC:Python26ArcGIS10.1PC -IC:Python26ArcGIS10.1
libsite-packagesnumpycoreinclude /Tpextensions/gdal_wrap.cpp /Fobuildtemp.w
in32-2.7Releaseextensions/gdal_wrap.obj

gdal_wrap.cpp

c:Program Files (x86)Microsoft Visual Studio 9.0VCINCLUDExlocale(342) : war
ning C4530: C++ exception handler used, but unwind semantics are not enabled. Sp
ecify /EHsc

extensions/gdal_wrap.cpp(2853) : fatal error C1083: Cannot open include file: 'c
pl_port.h': No such file or directory

error: command '"c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.ex
e"' failed with exit status 2

----------------------------------------
Command C:Python26ArcGIS10.1python.exe -c "import setuptools;__file__='c:\us
ers\jnunn\appdata\local\temp\pip-build\gdal\setup.py';exec(compile(open(_
_file__).read().replace('rn', 'n'), __file__, 'exec'))" install --record c:u
sersjnunnappdatalocaltemppip-f7tgze-recordinstall-record.txt --single-vers
ion-externally-managed failed with error code 1 in c:usersjnunnappdatalocal
temppip-buildgdal
Storing complete log in C:Usersjnunnpippip.log

C:UsersjnunnDesktop>

I have tried to use easy_install before too, and it came back with a common error to this:

c:Program Files (x86)Microsoft Visual Studio 9.0VCINCLUDExlocale(342) : war
ning C4530: C++ exception handler used, but unwind semantics are not enabled. Sp
ecify /EHsc

extensions/gdal_wrap.cpp(2853) : fatal error C1083: Cannot open include file: 'c
pl_port.h': No such file or directory

error: command '"c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.ex
e"' failed with exit status 2

Plus the following additional pip.log:

    Exception information:
Traceback (most recent call last):
File "C:Python26ArcGIS10.1libsite-packagespipbasecommand.py", line 107, in main
status = self.run(options, args)
File "C:Python26ArcGIS10.1libsite-packagespipcommandsinstall.py", line 261, in run
requirement_set.install(install_options, global_options)
File "C:Python26ArcGIS10.1libsite-packagespipreq.py", line 1166, in install
requirement.install(install_options, global_options)
File "C:Python26ArcGIS10.1libsite-packagespipreq.py", line 589, in install
cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
File "C:Python26ArcGIS10.1libsite-packagespiputil.py", line 612, in call_subprocess
% (command_desc, proc.returncode, cwd))
InstallationError: Command C:Python26ArcGIS10.1python.exe -c "import setuptools;__file__='c:\users\jnunn\appdata\local\temp\pip-build\gdal\setup.py';exec(compile(open(__file__).read().replace('r    n', 'n'), __file__, 'exec'))" install --record c:usersjnunnappdatalocaltemppip-f7tgze-recordinstall-record.txt --single-version-externally-managed failed with error code 1 in c:usersjnunnappdata    localtemppip-buildgdal

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

Студворк — интернет-сервис помощи студентам

Ребят, всем привет. Такая беда. При установке пакетов вылезают такие ошибки.

Кликните здесь для просмотра всего текста

C:UsersНР>pip install python-docx
Collecting python-docx
Using cached python-docx-0.8.6.tar.gz
Requirement already satisfied: lxml>=2.3.2 in c:usersнрappdatalocalprograms
pythonpython36-32libsite-packages (from python-docx)
Installing collected packages: python-docx
Running setup.py install for python-docx … error
Exception:
Traceback (most recent call last):
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipcompat__init__.py», line 73, in console_to_str
return s.decode(sys.__stdout__.encoding)
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xed in position 48: invalid
continuation byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipbasecommand.py», line 215, in main
status = self.run(options, args)
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipcommandsinstall.py», line 342, in run
prefix=options.prefix_path,
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipreqreq_set.py», line 784, in install
**kwargs
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipreqreq_install.py», line 878, in install
spinner=spinner,
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
piputils__init__.py», line 676, in call_subprocess
line = console_to_str(proc.stdout.readline())
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipcompat__init__.py», line 75, in console_to_str
return s.decode(‘utf_8’)
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xed in position 48: invalid
continuation byte

в чём беда? стоит windows 8. Заранее спасибо.

I’ve just installed python 3.6 which comes with pip

However, in Windows command prompt, when I do: ‘pip install bs4’ it returns ‘SyntaxError: invalid syntax’ under the install word.

Typing ‘python’ returns the version, which means it is installed correctly. What could be the problem?

Daniel Roseman's user avatar

asked Dec 4, 2017 at 11:59

zgg6a's user avatar

6

try this.

python -m  pip ...

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

Sometimes the OS can’t find pip so python or py -m may solve the problem because it is python itself searching for pip.

T.Todua's user avatar

T.Todua

52.5k19 gold badges232 silver badges237 bronze badges

answered Dec 4, 2017 at 12:17

Tiago_nes's user avatar

Tiago_nesTiago_nes

8437 silver badges29 bronze badges

1

You need to be in the specific folder where pip.exe exists, then do the following steps:

  1. open cmd.exe
  2. write the following command:
    cd "<Path to the python folder>"

or in my case, i wrote

    cd C:UsersusernameAppDataLocalProgramsPythonPython37-32Scripts
  1. then write the following command
    pip install *anypackage*

Oztaco's user avatar

Oztaco

3,34911 gold badges45 silver badges83 bronze badges

answered Apr 25, 2019 at 16:46

Dipak's user avatar

DipakDipak

1573 silver badges8 bronze badges

1

Don’t enter in the python shall, Install in the command directory.

Not inside the python pip cannot be installed inside the python.

Even in the version 3.+ you don’t have to write the python 3 instead just python.

which looks like

python -m pip install --upgrade pip

and then install others

python -m pip install jupyter

Intsab Haider's user avatar

answered Jul 2, 2019 at 5:43

vidyasagar mulge's user avatar

Try running cmd as administrator (in the menu that pops up after right-clicking) and/or
entering «pip» alone and then

answered Jul 5, 2018 at 14:41

David Ordman's user avatar

1

«D:Program FilesPyScriptspip.exe» install numpy -U

YOUR PATH to pip.exe in Python folder + install + YOUR LIB + -U

enter image description here

answered Aug 19, 2019 at 7:34

Roman Shubenko's user avatar

The OS is not recognizing ‘python’ command. So try ‘py’

Use ‘py -m pip’

answered Jun 22, 2020 at 4:20

Maxwel Jose's user avatar

The problem is the OS can’t find Pip. Pip helps you install packages
MODIFIED SOME GREAT ANSWERS TO BE BETTER

Method 1 Go to path of python, then search for pip

  1. open cmd.exe
  2. write the following command:

E.g

cd C:UsersUsernameAppDataLocalProgramsPythonPython37-32

In this directory, search pip with python -m pip then install package

E.g

python -m pip install ipywidgets

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

OR

GO TO scripts from CMD. This is where Pip stays :)

cd C:UsersUser nameAppDataLocalProgramsPythonPython37-32Scripts>

Then

pip install anypackage

answered Jun 29, 2020 at 16:31

VICTOR STEVE's user avatar

I had this error too!
I found the problem:
it had error cause i opened cmd then entered python then pip!!
you shouldn’t enter python!
just open cmd then write «pip install bs4»

answered Nov 7, 2021 at 18:56

zahra's user avatar

zahrazahra

111 bronze badge

0

  1. First go to python directory where it was installed on your windows machine by using

    cmd

  2. Then go ahead as i did in the picture

enter image description here

answered Dec 4, 2017 at 12:10

Land Owner's user avatar

Try:

pip3 install bs4

If you have python2 installed you typically have to make sure you are using the correct version of pip.

answered Dec 4, 2017 at 12:14

Dean Coakley's user avatar

Dean CoakleyDean Coakley

1,6432 gold badges10 silver badges25 bronze badges

I use Enthought Canopy for my python, at first I used «pip install —upgrade pip», it showed a syntax error like yours, then I added a «!» in front of the pip, then it finally worked.

answered Jun 8, 2018 at 2:17

owenhe's user avatar

You can also go into the directory where you have your pip.exe or pip3.exe located. For me it was on my D drive so here is what I did:

D:>cd python

D:python>cd Scripts

D:pythonScripts>pip3.exe install tweepy

Hope it helps

answered Oct 10, 2019 at 1:26

Kelly Le's user avatar

Chances are you are in the Python interpreter. Happens sometimes if you give
this (Python) command in cmd.exe just to check the version of Python and you so happen to forget to come out.

Try this command

exit()
pip install xyz

David Buck's user avatar

David Buck

3,71235 gold badges31 silver badges35 bronze badges

answered May 24, 2020 at 7:34

shubhamsarohi's user avatar

The resolution is pretty easy, altough it took me a while to figure it out.

Two ways to solve this:

1 — Short one

Open your CMD and write

pip install module 
or
python -m install module

2 — Longest one

Open your CMD and check your Python version:

python

After you confirm you are in the correct version, still in the prompt write:

exit()

After that write:

pip install module 
or
python -m install module

That will do the work.

answered Mar 20, 2021 at 4:21

Vinicius Raphael's user avatar

I found that you can download and install pip directly by running:

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

Then you can run

python3 get-pip.py

And check the version using:

pip3 --version

I was then able to install Django

pip install Django

answered Apr 18, 2021 at 11:58

Yuri.teacher.English's user avatar

When I use type pip install yfinance in terminal (cmd) on Mac, it shows

SyntaxError: invalid syntax pip -install yfinance File "<stdin>", line 1
    pip -install yfinance
                 ^
SyntaxError: invalid syntax

And, I finally open the Spyder, one of the development environments of python, in Anaconda Navigator.

Hadar's user avatar

Hadar

6404 silver badges16 bronze badges

answered Oct 7, 2022 at 21:58

Jamie's user avatar

In windows, you have to run pip install command from( python path)/ scripts path in cmd prompt

C:/python27/scripts

pip install pandas

Community's user avatar

answered Dec 4, 2017 at 14:42

Sridevi Amit B's user avatar

You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)

answered Dec 4, 2017 at 12:01

Elliot's user avatar

ElliotElliot

3081 silver badge8 bronze badges

5

I’m having trouble installing python modules using pip. Below is the output from the command window:

Note that I installed pip immediately before trying to install GDAL module.

I am on a w7 64bit machine running python 2.7

    Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:UsersjnunnDesktop>python get-pip.py
Downloading/unpacking pip
Downloading pip-1.2.1.tar.gz (102Kb): 102Kb downloaded
Running setup.py egg_info for package pip

warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.txt' found under directory
'docs_build'
no previously-included directories found matching 'docs_build_sources'
Installing collected packages: pip
Running setup.py install for pip

warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.txt' found under directory
'docs_build'
no previously-included directories found matching 'docs_build_sources'
Installing pip-script.py script to C:Python26ArcGIS10.1Scripts
Installing pip.exe script to C:Python26ArcGIS10.1Scripts
Installing pip.exe.manifest script to C:Python26ArcGIS10.1Scripts
Installing pip-2.7-script.py script to C:Python26ArcGIS10.1Scripts
Installing pip-2.7.exe script to C:Python26ArcGIS10.1Scripts
Installing pip-2.7.exe.manifest script to C:Python26ArcGIS10.1Scripts
Successfully installed pip
Cleaning up...

C:UsersjnunnDesktop>pip install gdal
Downloading/unpacking gdal
Downloading GDAL-1.9.1.tar.gz (420kB): 420kB downloaded
Running setup.py egg_info for package gdal

Installing collected packages: gdal
Running setup.py install for gdal
building 'osgeo._gdal' extension
c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.exe /c /nologo
/Ox /MD /W3 /GS- /DNDEBUG -I../../port -I../../gcore -I../../alg -I../../ogr/ -I
C:Python26ArcGIS10.1include -IC:Python26ArcGIS10.1PC -IC:Python26ArcGIS1
0.1libsite-packagesnumpycoreinclude /Tpextensions/gdal_wrap.cpp /Fobuildte
mp.win32-2.7Releaseextensions/gdal_wrap.obj
gdal_wrap.cpp
c:Program Files (x86)Microsoft Visual Studio 9.0VCINCLUDExlocale(342) :
warning C4530: C++ exception handler used, but unwind semantics are not enabled
. Specify /EHsc
extensions/gdal_wrap.cpp(2853) : fatal error C1083: Cannot open include file
: 'cpl_port.h': No such file or directory
error: command '"c:Program Files (x86)Microsoft Visual Studio 9.0VCBINc
l.exe"' failed with exit status 2
Complete output from command C:Python26ArcGIS10.1python.exe -c "import se
tuptools;__file__='c:usersjnunnappdatalocaltemppip-buildgdalsetu
p.py';exec(compile(open(__file__).read().replace('rn', 'n'), __file__, 'exec'
))" install --record c:usersjnunnappdatalocaltemppip-f7tgze-recordinstall
-record.txt --single-version-externally-managed:
running install

running build

running build_py

creating build

creating buildlib.win32-2.7

copying gdal.py -> buildlib.win32-2.7

copying ogr.py -> buildlib.win32-2.7

copying osr.py -> buildlib.win32-2.7

copying gdalconst.py -> buildlib.win32-2.7

copying gdalnumeric.py -> buildlib.win32-2.7

creating buildlib.win32-2.7osgeo

copying osgeogdal.py -> buildlib.win32-2.7osgeo

copying osgeogdalconst.py -> buildlib.win32-2.7osgeo

copying osgeogdalnumeric.py -> buildlib.win32-2.7osgeo

copying osgeogdal_array.py -> buildlib.win32-2.7osgeo

copying osgeoogr.py -> buildlib.win32-2.7osgeo

copying osgeoosr.py -> buildlib.win32-2.7osgeo

copying osgeo__init__.py -> buildlib.win32-2.7osgeo

running build_ext

building 'osgeo._gdal' extension

creating buildtemp.win32-2.7

creating buildtemp.win32-2.7Release

creating buildtemp.win32-2.7Releaseextensions

c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.exe /c /nologo /Ox
/MD /W3 /GS- /DNDEBUG -I../../port -I../../gcore -I../../alg -I../../ogr/ -IC:P
ython26ArcGIS10.1include -IC:Python26ArcGIS10.1PC -IC:Python26ArcGIS10.1
libsite-packagesnumpycoreinclude /Tpextensions/gdal_wrap.cpp /Fobuildtemp.w
in32-2.7Releaseextensions/gdal_wrap.obj

gdal_wrap.cpp

c:Program Files (x86)Microsoft Visual Studio 9.0VCINCLUDExlocale(342) : war
ning C4530: C++ exception handler used, but unwind semantics are not enabled. Sp
ecify /EHsc

extensions/gdal_wrap.cpp(2853) : fatal error C1083: Cannot open include file: 'c
pl_port.h': No such file or directory

error: command '"c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.ex
e"' failed with exit status 2

----------------------------------------
Command C:Python26ArcGIS10.1python.exe -c "import setuptools;__file__='c:us
ersjnunnappdatalocaltemppip-buildgdalsetup.py';exec(compile(open(_
_file__).read().replace('rn', 'n'), __file__, 'exec'))" install --record c:u
sersjnunnappdatalocaltemppip-f7tgze-recordinstall-record.txt --single-vers
ion-externally-managed failed with error code 1 in c:usersjnunnappdatalocal
temppip-buildgdal
Storing complete log in C:Usersjnunnpippip.log

C:UsersjnunnDesktop>

I have tried to use easy_install before too, and it came back with a common error to this:

c:Program Files (x86)Microsoft Visual Studio 9.0VCINCLUDExlocale(342) : war
ning C4530: C++ exception handler used, but unwind semantics are not enabled. Sp
ecify /EHsc

extensions/gdal_wrap.cpp(2853) : fatal error C1083: Cannot open include file: 'c
pl_port.h': No such file or directory

error: command '"c:Program Files (x86)Microsoft Visual Studio 9.0VCBINcl.ex
e"' failed with exit status 2

Plus the following additional pip.log:

    Exception information:
Traceback (most recent call last):
File "C:Python26ArcGIS10.1libsite-packagespipbasecommand.py", line 107, in main
status = self.run(options, args)
File "C:Python26ArcGIS10.1libsite-packagespipcommandsinstall.py", line 261, in run
requirement_set.install(install_options, global_options)
File "C:Python26ArcGIS10.1libsite-packagespipreq.py", line 1166, in install
requirement.install(install_options, global_options)
File "C:Python26ArcGIS10.1libsite-packagespipreq.py", line 589, in install
cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
File "C:Python26ArcGIS10.1libsite-packagespiputil.py", line 612, in call_subprocess
% (command_desc, proc.returncode, cwd))
InstallationError: Command C:Python26ArcGIS10.1python.exe -c "import setuptools;__file__='c:usersjnunnappdatalocaltemppip-buildgdalsetup.py';exec(compile(open(__file__).read().replace('r    n', 'n'), __file__, 'exec'))" install --record c:usersjnunnappdatalocaltemppip-f7tgze-recordinstall-record.txt --single-version-externally-managed failed with error code 1 in c:usersjnunnappdata    localtemppip-buildgdal

Студворк — интернет-сервис помощи студентам

Ребят, всем привет. Такая беда. При установке пакетов вылезают такие ошибки.

Кликните здесь для просмотра всего текста

C:UsersНР>pip install python-docx
Collecting python-docx
Using cached python-docx-0.8.6.tar.gz
Requirement already satisfied: lxml>=2.3.2 in c:usersнрappdatalocalprograms
pythonpython36-32libsite-packages (from python-docx)
Installing collected packages: python-docx
Running setup.py install for python-docx … error
Exception:
Traceback (most recent call last):
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipcompat__init__.py», line 73, in console_to_str
return s.decode(sys.__stdout__.encoding)
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xed in position 48: invalid
continuation byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipbasecommand.py», line 215, in main
status = self.run(options, args)
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipcommandsinstall.py», line 342, in run
prefix=options.prefix_path,
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipreqreq_set.py», line 784, in install
**kwargs
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipreqreq_install.py», line 878, in install
spinner=spinner,
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
piputils__init__.py», line 676, in call_subprocess
line = console_to_str(proc.stdout.readline())
File «c:usersнрappdatalocalprogramspythonpython36-32libsite-packages
pipcompat__init__.py», line 75, in console_to_str
return s.decode(‘utf_8’)
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xed in position 48: invalid
continuation byte

в чём беда? стоит windows 8. Заранее спасибо.

При попытке установки практически любой библиотеки через 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 происходит аналогичная ситуация и та же ошибка

Ответ на:

комментарий
от t184256 21.10.19 23:21:23 MSK

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

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от cretin00 21.10.19 23:26:31 MSK

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

t184256 ★★★★★

(21.10.19 23:27:54 MSK)

  • Показать ответы
  • Ссылка

Ответ на:

комментарий
от t184256 21.10.19 23:27:54 MSK

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

  • Ссылка

Ответ на:

комментарий
от t184256 21.10.19 23:27:54 MSK

при установке программ 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
предупреждение: не удалось получить информацию о файле для

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от cretin00 21.10.19 23:43:21 MSK

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

AEP ★★★★★

(22.10.19 09:14:10 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от ei-grad 22.10.19 09:21:14 MSK

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

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

anonymous

(22.10.19 09:57:00 MSK)

  • Ссылка

Ответ на:

комментарий
от AEP 22.10.19 09:14:10 MSK

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

Radjah ★★★★★

(22.10.19 10:42:57 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от t184256 21.10.19 23:50:22 MSK

командой sudo pacman -Rsccdd namep?

  • Ссылка

Ответ на:

комментарий
от ei-grad 22.10.19 09:21:14 MSK

Пипка.

anonymous

(22.10.19 14:14:49 MSK)

  • Ссылка

Ответ на:

комментарий
от Radjah 22.10.19 10:42:57 MSK

С менеджером пакетов скорее всего нет, потому что pip кладёт в /usr/local даже при обновлении пакетов, которые через системный менеджер установлены

Это дистроспецифичный патч. В Debian и Ubuntu это так, в других дистрибутивах — нет.

AEP ★★★★★

(22.10.19 16:04:16 MSK)

  • Ссылка

Всегда используй virtualenv

  • Ссылка

Ответ на:

комментарий
от cretin00 22.10.19 16:12:05 MSK

Ответ на:

комментарий
от t184256 22.10.19 16:15:37 MSK

Ответ на:

комментарий
от cretin00 22.10.19 16:21:07 MSK

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

t184256 ★★★★★

(22.10.19 16:24:28 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от t184256 22.10.19 16:24:28 MSK

Ответ на:

комментарий
от cretin00 22.10.19 16:12:05 MSK

Но ведь ты не решил проблему с pacman, а до тех пор у тебя система сломана. Сделай pacman -Qkk python-setuptools.

Thetan ★★★

(22.10.19 16:27:29 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от Thetan 22.10.19 16:27:29 MSK

точно,вот выхлоп:
python-setuptools: всего 192 файла, 0 измененных файлов

  • Ссылка

Ответ на:

комментарий
от cretin00 22.10.19 16:26:23 MSK

Ответ на:

комментарий
от t184256 22.10.19 16:33:09 MSK

Ответ на:

комментарий
от t184256 22.10.19 16:15:37 MSK

Ответ на:

комментарий
от cretin00 22.10.19 16:33:47 MSK

https://wiki.archlinux.org/index.php/Python#Package_management

If you must use pip, use a virtual environment, or pip install --user to avoid conflicts with packages in /usr. It is always preferred to use pacman to install software.

https://wiki.archlinux.org/index.php/Python_(Русский)#Управление_пакетами

Если вы собираетесь использовать pip, используйте его в виртуальном окружении или с опцией --user (pip install --user), чтобы избежать конфликтов между пакетами в каталоге /usr. Во всех случаях предпочтительный способ установки программного обеспечения — это использование pacman.

Примечание: Существуют инструменты, автоматически генерирующие PKGBUILDы для пакетов pip и таким образом интегрирующие его в pacman: pipman-git, pip2arch-git

greenman ★★★★★

(22.10.19 17:11:37 MSK)

Последнее исправление: greenman 22.10.19 17:16:31 MSK
(всего

исправлений: 3)

  • Ссылка

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.

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

Collecting tmtoolkit
  Downloading tmtoolkit-0.1.6-py2.py3-none-any.whl (15.3MB)
Collecting pandas (from tmtoolkit)
  Downloading pandas-0.21.0.tar.gz (11.3MB)
    Complete output from command python setup.py egg_info:
    Running from numpy source directory.
    C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3setup.py:367: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
      run_build = parse_setuppy_commands()
    C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
        Atlas (http://math-atlas.sourceforge.net/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [atlas]) or by setting
        the ATLAS environment variable.
      self.calc_info()
    C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
        Blas (http://www.netlib.org/blas/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [blas]) or by setting
        the BLAS environment variable.
      self.calc_info()
    non-existing path in 'numpydistutils': 'site.cfg'
    C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      self.calc_info()
    C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilssystem_info.py:572: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      self.calc_info()
    C:Python34libdistutilsdist.py:260: UserWarning: Unknown distribution option: 'define_macros'
      warnings.warn(msg)
    Traceback (most recent call last):
      File "C:Python34libdistutilscore.py", line 148, in setup
        dist.run_commands()
      File "C:Python34libdistutilsdist.py", line 955, in run_commands
        self.run_command(cmd)
      File "C:Python34libdistutilsdist.py", line 974, in run_command
        cmd_obj.run()
      File "C:Python34libsite-packagessetuptoolscommandbdist_egg.py", line 161, in run
        self.run_command("egg_info")
      File "C:Python34libdistutilscmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "C:Python34libdistutilsdist.py", line 974, in run_command
        cmd_obj.run()
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandegg_info.py", line 26, in run
      File "C:Python34libdistutilscmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "C:Python34libdistutilsdist.py", line 974, in run_command
        cmd_obj.run()
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 148, in run
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 159, in build_sources
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 294, in build_library_sources
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandbuild_src.py", line 377, in generate_sources
      File "numpycoresetup.py", line 672, in get_mathlib_info
        'pandas.tests',
      File "C:Python34libdistutilscommandconfig.py", line 243, in try_link
        self._check_compiler()
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscommandconfig.py", line 51, in _check_compiler
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilsmsvccompiler.py", line 50, in initialize
      File "C:Python34libdistutilsmsvc9compiler.py", line 371, in initialize
        vc_env = query_vcvarsall(VERSION, plat_spec)
      File "C:Python34libsite-packagessetuptoolsmsvc.py", line 147, in msvc9_query_vcvarsall
        return EnvironmentInfo(arch, ver).return_env()
      File "C:Python34libsite-packagessetuptoolsmsvc.py", line 1228, in return_env
        [self.VCIncludes,
      File "C:Python34libsite-packagessetuptoolsmsvc.py", line 877, in VCIncludes
        return [os.path.join(self.si.VCInstallDir, 'Include'),
      File "C:Python34libsite-packagessetuptoolsmsvc.py", line 556, in VCInstallDir
        raise distutils.errors.DistutilsPlatformError(msg)
    distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 158, in save_modules
        yield saved
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 199, in setup_context
        yield
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 254, in run_setup
        _execfile(setup_script, ns)
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 49, in _execfile
        exec(code, globals, locals)
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3setup.py", line 392, in <module>
        def build_extension(self, ext):
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3setup.py", line 384, in setup_package
        self.check_cython_extensions(self.extensions)
      File "C:Users5A86~1AppDataLocalTempeasy_install-bz49tq70numpy-1.13.3numpydistutilscore.py", line 169, in setup
      File "C:Python34libsite-packagessetuptools__init__.py", line 129, in setup
        return distutils.core.setup(**attrs)
      File "C:Python34libdistutilscore.py", line 163, in setup
        raise SystemExit("error: " + str(msg))
    SystemExit: error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "C:Python34libsite-packagessetuptoolscommandeasy_install.py", line 1104, in run_setup
        run_setup(setup_script, args)
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 257, in run_setup
        raise
      File "C:Python34libcontextlib.py", line 77, in __exit__
        self.gen.throw(type, value, traceback)
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 199, in setup_context
        yield
      File "C:Python34libcontextlib.py", line 77, in __exit__
        self.gen.throw(type, value, traceback)
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 170, in save_modules
        saved_exc.resume()
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 145, in resume
        six.reraise(type, exc, self._tb)
      File "C:Python34libsite-packagespkg_resources_vendorsix.py", line 685, in reraise
        raise value.with_traceback(tb)
      File "C:Python34libsite-packagessetuptoolssandbox.py", line 158, in save_modules
        yield saved

      File "C:Python34libsite-packagessetuptools__init__.py", line 129, in setup
        return distutils.core.setup(**attrs)
      File "C:Python34libdistutilscore.py", line 163, in setup
        raise SystemExit("error: " + str(msg))
    SystemExit: error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
    
 
        ----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in C:UsersБлаблаблаAppDataLocalTemppycharm-packaging1pandas

Сделал это, запустил через терминал. Вот код

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import face-recognition #пробовал и face_recognition
import cv2
import numpy as np
import os
from datetime import datetime
 
path = 'KnownFaces'
images = []
classNames = []
myList = os.listdir(path)
print(myList)
 
for cls in myList:
    curImg = cv2.imread(f'{path}/{cls}')
    images.append(curImg)
    classNames.append(os.path.splitext(cls)[0])
 
print(classNames)
 
def findEncodings(images):
    encodeList = []
    for img in images:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[0]
        encodeList.append(encode)
    return encodeList
 
def markAttendance(name):
    with open("Attendance.csv", "r+") as f:
        myDataList = f.readlines()
        nameList = []
        for line in myDataList:
            entry = line.split(',')
            nameList.append(entry[0])
        if name not in nameList:
            now = datetime.now()
            dtString = now.strftime("%H:%M:%S")
            f.writelines(f'n{name}, {dtString}')
 
encodeListKnown = findEncodings(images)
print("Декодирование закончено")
 
cap = cv2.VideoCapture(0)
 
while True:
    success, img = cap.read()
    imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
    imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
 
    facesCurFrame = face_recognition.face_locations(imgS)
    encodeCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
 
    for encodeFace, faceLoc in zip(encodeCurFrame, facesCurFrame):
        matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
        faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
        #print(faceDis)
        matchIndex = np.argmin(faceDis)
 
        if matches[matchIndex]:
            name = classNames[matchIndex]
            #print(name)
            y1, x2, y2, x1 = faceLoc
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
            markAttendance(name)
 
    cv2.imshow("WebCam", img)
    cv2.waitKey(1)

Выводит следующее:

Код

import face-recognition
  File "<stdin>", line 1
    import face-recognition
               ^
SyntaxError: invalid syntax
>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import numpy as np
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
>>> import os
>>> from datetime import datetime
>>>
>>> path = 'KnownFaces'
>>> images = []
>>> classNames = []
>>> myList = os.listdir(path)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [WinError 3] Системе не удается найти указанный путь: 'KnownFaces'
>>> print(myList)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'myList' is not defined
>>>
>>> for cls in myList:
...     curImg = cv2.imread(f'{path}/{cls}')
...     images.append(curImg)
...     classNames.append(os.path.splitext(cls)[0])
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'myList' is not defined
>>> print(classNames)
[]
>>>
>>> def findEncodings(images):
...     encodeList = []
...     for img in images:
...         img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
...         encode = face_recognition.face_encodings(img)[0]
...         encodeList.append(encode)
...     return encodeList
...
>>> def markAttendance(name):
...     with open("Attendance.csv", "r+") as f:
...         myDataList = f.readlines()
...         nameList = []
...         for line in myDataList:
...             entry = line.split(',')
...             nameList.append(entry[0])
...         if name not in nameList:
...             now = datetime.now()
...             dtString = now.strftime("%H:%M:%S")
...             f.writelines(f'n{name}, {dtString}')
...
>>> encodeListKnown = findEncodings(images)
>>> print("Декодирование закончено")
Декодирование закончено
>>>
>>> cap = cv2.VideoCapture(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cv2' is not defined
>>>
>>> while True:
...     success, img = cap.read()
...     imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
...     imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'cap' is not defined
>>>     facesCurFrame = face_recognition.face_locations(imgS)
  File "<stdin>", line 1
    facesCurFrame = face_recognition.face_locations(imgS)
IndentationError: unexpected indent
>>>     encodeCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
  File "<stdin>", line 1
    encodeCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
IndentationError: unexpected indent
>>>
>>>     for encodeFace, faceLoc in zip(encodeCurFrame, facesCurFrame):
  File "<stdin>", line 1
    for encodeFace, faceLoc in zip(encodeCurFrame, facesCurFrame):
IndentationError: unexpected indent
>>>         matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
  File "<stdin>", line 1
    matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
IndentationError: unexpected indent
>>>         faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
  File "<stdin>", line 1
    faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
IndentationError: unexpected indent
>>>         #print(faceDis)
>>>         matchIndex = np.argmin(faceDis)
  File "<stdin>", line 1
    matchIndex = np.argmin(faceDis)
IndentationError: unexpected indent
>>>
>>>         if matches[matchIndex]:
  File "<stdin>", line 1
    if matches[matchIndex]:
IndentationError: unexpected indent
>>>             name = classNames[matchIndex]
  File "<stdin>", line 1
    name = classNames[matchIndex]
IndentationError: unexpected indent
>>>             #print(name)
>>>             y1, x2, y2, x1 = faceLoc
  File "<stdin>", line 1
    y1, x2, y2, x1 = faceLoc
IndentationError: unexpected indent
>>>             y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
  File "<stdin>", line 1
    y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
IndentationError: unexpected indent
>>>             cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
  File "<stdin>", line 1
    cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
IndentationError: unexpected indent
>>>             cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
  File "<stdin>", line 1
    cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
IndentationError: unexpected indent
>>>             cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
  File "<stdin>", line 1
    cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
IndentationError: unexpected indent
>>>             markAttendance(name)
  File "<stdin>", line 1
    markAttendance(name)
IndentationError: unexpected indent
>>>
>>>     cv2.imshow("WebCam", img)
  File "<stdin>", line 1
    cv2.imshow("WebCam", img)
IndentationError: unexpected indent
>>>     cv2.waitKey(1)

ОШИБКА ПОЧТИ В КАЖДОЙ СТРОЧКЕ! Но я так понимаю что это из-за неподключённых библиотек, ведь так? Можете пожалуйста скинуть рабочий код для распознавания лиц в google colab’e?

0

Collecting numpy
Using cached https://files.pythonhosted.org/pack…79828291f68aebfff1642be212ec/numpy-1.19.4.zip
Installing build dependencies: started
Installing build dependencies: finished with status ‘done’
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status ‘done’
Preparing wheel metadata: started
Preparing wheel metadata: finished with status ‘error’
Complete output from command D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvScriptspython.exe D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py prepare_metadata_for_build_wheel C:UsersVOLODI~1AppDataLocalTemptmpttixcb_z:
Error in sitecustomize; set PYTHONVERBOSE for traceback:
SyntaxError: (unicode error) ‘utf-8’ codec can’t decode byte 0xef in position 0: invalid continuation byte (sitecustomize.py, line 7)
Running from numpy source directory.
setup.py:480: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
run_build = parse_setuppy_commands()
Cythonizing sources
Error in sitecustomize; set PYTHONVERBOSE for traceback:
SyntaxError: (unicode error) ‘utf-8’ codec can’t decode byte 0xef in position 0: invalid continuation byte (sitecustomize.py, line 7)
Processing numpy/random_bounded_integers.pxd.in
Processing numpy/randombit_generator.pyx
Traceback (most recent call last):
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 59, in process_pyx
from Cython.Compiler.Version import version as cython_version
ModuleNotFoundError: No module named ‘Cython’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 235, in <module>
main()
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 231, in main
find_process_files(root_dir)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 222, in find_process_files
process(root_dir, fromfile, tofile, function, hash_db)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 188, in process
processor_function(fromfile, tofile)
File «C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpytoolscythonize.py», line 64, in process_pyx
raise OSError(‘Cython needs to be installed in Python as a module’)
OSError: Cython needs to be installed in Python as a module
Traceback (most recent call last):
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 207, in <module>
main()
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 197, in main
json_out[‘return_val’] = hook(**hook_input[‘kwargs’])
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py», line 69, in prepare_metadata_for_build_wheel
return hook(metadata_directory, config_settings)
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 140, in prepare_metadata_for_build_wheel
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 210, in run_setup
File «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagessetuptools-40.8.0-py3.8.eggsetuptoolsbuild_meta.py», line 126, in run_setup
File «setup.py», line 508, in <module>
setup_package()
File «setup.py», line 488, in setup_package
generate_cython()
File «setup.py», line 285, in generate_cython
raise RuntimeError(«Running cythonize failed!»)
RuntimeError: Running cythonize failed!

—————————————-

Command «D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvScriptspython.exe D:DOCUMENTSПРОГРАММИРОВАНИЕPYTHONPROJECTSPYCHARMme2safeautocrackervenvlibsite-packagespip-19.0.3-py3.8.eggpip_vendorpep517_in_process.py prepare_metadata_for_build_wheel C:UsersVOLODI~1AppDataLocalTemptmpttixcb_z» failed with error code 1 in C:UsersVolodinASAppDataLocalTemppycharm-packagingnumpy

О проблеме, из-за которой сторонние пакеты, установленные Python, не могут быть указаны в Pycharm

  • 0 Введение
    • Не удалось установить 1 пункт
      • 1.1 Установка не удалась из-за проблем с сетью
      • 1.2 Сбой установки в Анаконде
    • 2 Установка прошла успешно, но в интерпретаторе Pycharm нет нового установленного пакета
    • 3 Вновь установленный пакет появляется в интерпретаторе Pycharm, но на него нельзя ссылаться

0 Введение

Существует множество причин неудачной ссылки на сторонний пакет, установленный в Python, в Pycharm: следующие типичные проблемы: 1. Сбой установки pip, 2. Установка прошла успешно, но нет нового установленного интерпретатора Pycharm. Пакет, 3. Недавно установленный пакет появляется в интерпретаторе Pycharm, но на него нельзя ссылаться.

Не удалось установить 1 пункт

Существует также много ситуаций, когда установка pip завершается неудачно: 1. Сбой установки из-за проблем с сетью 2. Если установлена ​​среда Anaconda, может возникнуть проблема при установке с помощью команды conda. :

1.1 Установка не удалась из-за проблем с сетью

  1. Перейдите на соответствующий веб-сайт и загрузите соответствующий файл whl. Соответствующий номер cp + в имени пакета представляет поддерживаемый формат. Соответствующий номер cp + в имени пакета представляет поддерживаемый формат.
  2. Затем переместите загруженный whl-файл в каталог сценариев локального python. В это время вам нужно выбрать каталог, в котором расположен ваш проект. Если это виртуальный каталог, вам нужно ввести каталог сценариев виртуального каталога. (Сеть виртуальных каталогов для этого компьютера: D: Anaconda3 envs network Scripts)
  3. pip intall «путь к файлу»

1.2 Сбой установки в Анаконде

Если он установлен вместе с conda install -n network dnspython3 (обратите внимание: последние два параметра основаны на вас самих, network — это виртуальный каталог, в котором находится мой проект, а dnspython3 — это имя устанавливаемого пакета), если на веб-сайте, связанном с Anaconda, этот пакет отсутствует, Затем он сообщит об ошибке, которая не может быть найдена.
выглядит следующим образом:

F: Информация Классы Сетевое программирование Программные средства memcached_en32or64 x64> conda install -n network d
nspython3 Solving environment: failed

PackagesNotFoundError: The following packages are not available from
current cha nnels:

  • dnspython3

Current channels:

  • https://repo.anaconda.com/pkgs/main/win-64
  • https://repo.anaconda.com/pkgs/main/noarch
  • https://repo.anaconda.com/pkgs/free/win-64
  • https://repo.anaconda.com/pkgs/free/noarch
  • https://repo.anaconda.com/pkgs/r/win-64
  • https://repo.anaconda.com/pkgs/r/noarch
  • https://repo.anaconda.com/pkgs/pro/win-64
  • https://repo.anaconda.com/pkgs/pro/noarch
  • https://repo.anaconda.com/pkgs/msys2/win-64
  • https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package
you’re looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.

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

F: Data Classes Network Programming Software Tools> активировать сеть

(сеть) F: материалы классы сетевое программирование программные инструменты> pip install dnspython3

После успешной установки отобразятся:

Successfully built dnspython3 Installing collected packages:
dnspython, dnspython3 Successfully installed dnspython-1.15.0
dnspython3-1.15.0

Как определить, успешно ли установлен пакет?
Сторонние пакеты обычно устанавливаются в каталог ** Lib site-packages. Если вы можете найти имя пакета, которое вы только что установили в этом каталоге, это означает, что пакет был установлен Установка прошла успешно.

Если определено, что пакет был успешно установлен, и запрашивается при использовании в Pycharm:

AttributeError: module ‘dns’ has no attribute ‘resolver’

или

ModuleNotFoundError: No module named ‘dns.resolver’

Подобная ошибка указывает на то, что у Pycharm нет этого пакета в интерпретаторе, в котором находится текущий проект, поэтому вам необходимо проверить, правильно ли интерпретатор вашего проекта. Если вы используете виртуальный каталог и ваш pip установлен в среде вашей системы по умолчанию, это вызовет эту проблему.
Если pip установлен в системной среде по умолчанию, которая является так называемой общедоступной средой, нажмите «Файл» -> «Настройка», затем действуйте, как показано на рисунке ниже, щелкните значок «плюс» в правой части рисунка, Просто добавьте и найдите только что установленный пакет.

Здесь из-за версии пакета, от которого зависит проект Python, все авторы настоятельно рекомендуют использовать для проекта виртуальный каталог, и все установки выполняются только в текущем виртуальном каталоге, предпочтительно не в среде по умолчанию.

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

3 Вновь установленный пакет появляется в интерпретаторе Pycharm, но на него нельзя ссылаться

Если в интерпретаторе, где находится текущий проект Pycharm, только что установленный пакет появился, но на него все еще нельзя ссылаться, проблема может быть в следующем:
В вашем текущем проекте уже есть модуль или каталог,Совпадает с именем модуля установочного пакетаВызвано конфликтом.
Например, автору необходимо установить пакет dnspython3, и он был успешно установлен следующим образом:

Кроме того, убедитесь, что он появился в интерпретаторе проекта (указывая, что Pycharm загрузил этот пакет), следующим образом:

В настоящее время импорт dns по-прежнему будет запрашивать отсутствие такого модуля, поскольку в моем проекте уже есть каталог dns, поэтому при импорте он будет иметь приоритет при импорте dns в ваш проект следующим образом. :

В настоящее время измените имя своего собственного каталога DNS, чтобы разрешить конфликт. Как показано ниже:

На этом этапе рекомендуется, чтобы при разработке проекта лучше всего было добавить префикс проекта к собственному имени каталога, например, от dns к net_dns, что может эффективно избежать проблемы конфликтов имен, вызванных импортом сторонних пакетов.


  1. https://blog.csdn.net/kouyi5627/article/details/80531442
    end。 ↩︎

Понравилась статья? Поделить с друзьями:
  • Ошибка при установке параметров безопасности на machine software
  • Ошибка при установке пакета macroscop код ошибки 11
  • Ошибка при установке параметра модуля криптографии как исправить ошибку
  • Ошибка при установке офиса не удалось зарегистрировать шрифт
  • Ошибка при установке офиса 365