Решение проблем с модулями и пакетами Python
Я с завидной регулярностью сталкиваюсь со всевозможными ошибками, так или иначе связанными с модулями Python. Существует огромное количество разнообразных модулей Python, которые разработчики активно используют, но далеко не всегда заботятся об установке зависимостей. Некоторые даже не удосуживаются их документировать. Параллельно существует две мажорные версии Python: 2 и 3. В разных дистрибутивах отдано предпочтение одной или другой версии, по этой причине самостоятельно установленную программу в зависимости от дистрибутива нужно при запуске предварять python или python2/python3. Например:
Причём обычно не происходит никаких проверок и угадали ли вы с выбором версии или нет вы узнаете только при появлении первых ошибок, вызванных неправильным синтаксисом программного кода для данной версии.
Также прибавляет путаницу то, что модули можно установить как из стандартного репозитория дистрибутивов, так и с помощью pip (инструмент для установки пакетов Python).
Цель этой заметки — рассмотреть некоторые характерные проблемы модулей Python. Все возможные ошибки вряд ли удастся охватить, но описанное здесь должно помочь понять, в каком примерно направлении двигаться.
Отсутствие модуля Python
Большинство ошибок модулей Python начинаются со строк:
В них трудно разобраться, поэтому поищите фразы вида:
- ModuleNotFoundError: No module named
- No module named
- ImportError: No module named
За ними следует название модуля.
Поищите по указанному имени в системном репозитории, или попробуйте установить командой вида:
Пакет Python установлен, но программа его не видит
Причина может быть в том, что вы установили модуль для другой версии. Например, программа написана на Python3, а вы установили модуль с этим же названием, но написанный на Python2. В этом случае он не будет существовать для программы. Поэтому нужно правильно указывать номер версии.
Команда pip также имеет свои две версии: pip2 и pip3. Если версия не указана, то это означает, что используется какая-то из двух указанных (2 или 3) версий, которая является основной в системе. Например, сейчас в Debian и производных по умолчанию основной версией Python является вторая. Поэтому в репозитории есть два пакета: python-pip (вторая версия) и python3-pip (третья).
В Arch Linux и производных по умолчанию основной версией является третья, поэтому в репозиториях присутствует пакет python-pip (третья версия) и python2-pip (вторая).
Это же самое относится к пакетам Python и самому Python: если версия не указана, значит имеется ввиду основная для вашего дистрибутива версия. По этой причине многие пакеты в репозитории присутствуют с двумя очень похожими названиями.
Установлена новая версия модуля, но программа видит старую версию
Я несколько раз сталкивался с подобными необъяснимыми ошибками.
Иногда помогает удаление модуля командой вида:
Также попробуйте удалить его используя системный менеджер пакетов.
Если модуль вам нужен, попробуйте вновь установить его и проверьте, решило ли это проблему.
Если проблема не решена, то удалите все файлы модуля, обычно они расположены в папках вида:
- /usr/lib/python2.7/site-packages/модуль
- /usr/lib/python3.7/site-packages/модуль
Ошибки с фразой «AttributeError: 'NoneType' object has no attribute»
Ошибки, в которых присутствует слово AttributeError, NoneType, object has no attribute обычно вызваны не отсутствием модуля, а тем, что модуль не получил ожидаемого аргумента, либо получил неправильное число аргументов. Было бы правильнее сказать, что ошибка вызвана недостаточной проверкой данных и отсутствием перехвата исключений (то есть программа плохо написана).
В этих случаях обычно ничего не требуется дополнительно устанавливать. В моей практике частыми случаями таких ошибок является обращение программы к определённому сайту, но сайт может быть недоступен, либо API ключ больше недействителен, либо программа не получила ожидаемые данные по другим причинам. Также программа может обращаться к другой программе, но из-за ошибки в ней получит не тот результат, который ожидала, и уже это вызывает приведённые выше ошибки, которые мы видим.
Опять же, хорошо написанная программа в этом случае должна вернуть что-то вроде «информация не загружена», «работа программы N завершилась ошибкой» и так далее. Как правило, нужно разбираться с причиной самой первой проблемы или обращаться к разработчику.
Модуль установлен, но при обновлении или обращении к нему появляется ошибки
Это самая экзотическая ошибка, которая вызвана, видимо, повреждением файлов пакета. К примеру, при попытке обновления я получал ошибку:
При этом сам модуль установлен как следует из самой первой строки.
Проблема может решиться удалением всех файлов пакета (с помощью rm) и затем повторной установки.
К примеру в рассматриваемом случае, удаление:
После этого проблема с модулем исчезла.
Заключение
Пожалуй, это далеко не полный «справочник ошибок Python», но если вы можете сориентироваться, какого рода ошибка у вас возникла:
- отсутствует модуль
- модуль неправильной версии
- модуль повреждён
- внешняя причина — программа не получила ожидаемые данные
Так вот, если вы хотя бы примерно поняли главную причину, то вам будет проще понять, в каком направлении двигаться для её решения.
ModuleNotFoundError: no module named Python Error [Fixed]

Dillion Megida
![ModuleNotFoundError: no module named Python Error [Fixed]](https://www.freecodecamp.org/news/content/images/size/w2000/2022/09/module-not-found-error.png)
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:
Here’s what the error looks like:

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:
If you try to run this code with python test.py and you get this error:
Then it’s most likely possible that the numpy module is not installed on your device. You can install the module like this:
When installed, the previous code will work correctly and you get the result printed in your terminal:
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:
Here, you have installed numpy but running the above code throws this error:
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:
For this code, you have numpy installed but running the above code will throw this error:
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:
Here are the contents of test1.py :
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:
This code will throw the following error:
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:
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.
Почему интерпретатор Python не видит модуль?
Начал изучать Python по учебнику Лутц.М — изучаем Python. У меня установлен python 3.4.1.
Создал модуль с текстом:
import sys
print(sys.platform)
print(2 ** 100)
x = ‘Spam!’
print(x * 8)
Обозвал его script1 и дал расширение .Py.
Данный модуль закинул в корневую папку где установлен питон
По учебнику сказано — «Сохранив этот текстовый файл, вы сможете предложить интерпретатору Python выполнить его, указав полное имя файла в качестве первого аргументакоманды python, введя следующую строку в системной командной строке:
% python script1.py»
Следуя инструкции я получаю ошибку
Среда Path у меня объявлена
Так почему же когда я ввожу python script1.py (как сказано в учебники) я не получаю нужного результата ?
- Вопрос задан более трёх лет назад
- 20509 просмотров
- Вконтакте

script1.py должен быть в текущей директории
или текущая директория должна быть там где script1.py (:
Why Can't Python Find My Modules?

It’s not uncommon for new Pythonistas to have trouble installing packages and using their modules. Frustrating errors like this often arise, even if you think you’ve installed a package properly:
This is caused by the fact that the version of Python you’re running your script with is not configured to search for modules where you’ve installed them. This happens when you use the wrong installation of pip to install packages.
In general, each Python installation comes bundled with its own pip executable, used for installing packages. By default, that pip executable will install packages in a location where that specific Python installation can find them.
The problem is that it’s very common to have multiple Python interpreters installed (and by extension, multiple pip executables.) Depending on your shell’s PATH, running pip may invoke the pip executable linked to the version of Python you’re using, or to a different one. If the wrong pip is invoked, then the packages it installs will likely not be visible to the Python interpreter you’re using, causing the ImportError .
To use the version of pip specific to your desired Python version, you can use python -m pip . Here, python is the path to the desired Python interpreter, so something like /usr/local/bin/python3.7 -m pip will use the pip executable for /usr/local/bin/python3.7 . However, this still has its limitations.
There are also other ways to get around this issue. You can modify your shell’s PATH so it uses the correct pip executable, or change the PYTHONPATH so that your desired version of Python can find the packages located in a different directory. But these can all get messy fast.
Instead, virtual environments are often used to isolate Python installations from one another. A virtual environment contains, among other things, a Python interpreter, a pip executable, and a site-packages directory, which is the standard location for most packages downloaded with pip .
By activating a virtual environment within your shell, you expose it to only the pip and Python executables installed within your virtual environments, ensuring that the right versions of both applications are invoked and that packages are always installed to the correct location. Virtual environments also allow you to run different versions of the same package with different projects, something not possible if you are using a global Python installation.
There are many different virtual environments to choose from. This course uses Conda, bundled with Anaconda. You can learn more about virtual environments in Working With Python Virtual Environments.