Ошибка установки модуля python

Для указания прокси:

pip install --proxy https://username:pwd@proxy:port package_name

Или:

set http_proxy=http://username:pwd@proxy:port
set https_proxy=https://username:pwd@proxy:port
pip install package_name

Или:

cd "%APPDATA%/pip"
notepad pip.ini
# add:
[global]
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org
proxy = http://[domain name]%5C[username]:[password]@[proxy address]:[proxy port]
# Сохранить и закрыть pip.ini

pip install package_name

Или:

Установить Cntlm Authentication Proxy, используя инструкции, например, здесь. Для установки и использования права администратора — не нужны

После этого использовать прокси 127.0.0.1:3128

Лучше всего скачать zip-версию программы. На данный момент это версия 0.92.3

После этого распаковать её, настроить .ini файл и запускать из Git Bash окружения (программа использует Cygwin):

/c/tools/cntlm/cntlm.exe -c /c/tools/cntlm/cntlm.ini -I -f

-I запускает приложение в интерактивном режиме. При этом не нужно прописывать пароль в .ini — строку с паролем следует закомментировать. Программа спросит пароль при запуске

-f оставляет приложение на переднем плане, позволяя закрыть его по Ctrl-Break

Этот подход наиболее правилен с точки зрения безопасности хранения и передачи пароля по сети в открытом виде.

P.S. На моей Windows 10 программа вполне себе запустилась из командной строки безо всяких Git Bash и Cygwin…


Для первых трёх вариантов:

Если в имени или пароле есть спецсимволы, то их можно escape при помощи или записывая в 16-ричной нотации, например, %5C

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

ModuleNotFoundError: no module named Python Error [Fixed]

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

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

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

import numpys as np

Here’s what the error looks like:

image-341

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

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

How to fix the ModuleNotFoundError in Python

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

1. Make sure imported modules are installed

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

import numpy as np

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

print(arr)

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

ModuleNotFoundError: No module named "numpy"

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

python -m pip install numpy

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

[1, 2, 3]

2. Make sure modules are spelled correctly

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

import nompy as np

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

print(arr)

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

ModuleNotFoundError: No module named "nompy"

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

3. Make sure modules are in the right casing

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

import Numpy as np

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

print(arr)

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

ModuleNotFoundError: No module named 'Numpy'

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

4. Make sure you use the right paths

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

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

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

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

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

Here’s the structure:

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

Here are the contents of test1.py:

def hello():
  print("hello")

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

import demoA.test as test1

test1.hello()

This code will throw the following error:

ModuleNotFoundError: No module named 'demoA.test'

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

import demoA.test1 as test1

test1.hello()
# hello

Wrapping up

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

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

I hope you learned from it :)



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

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

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

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

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

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

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

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

❌ModuleNotFoundError: No module named numpy

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

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

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

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

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

pip install numpy

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

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

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

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

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

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

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

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

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

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

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

pip install numpy
# или
pip3 install numpy

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

conda install numpy

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

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

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

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

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


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

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

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

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

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

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

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

  • Ошибка установки обновления gta 5 rockstar launcher
  • Ошибка установки метро исход
  • Ошибка установки обновления 80073701
  • Ошибка установки маркировка эвотор
  • Ошибка установки обновления 80070570