Python no module named options

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

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

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

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

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

Читайте также:  Css block under block

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

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

Exception: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/………. ……………… ………………

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

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

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

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

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

sudo pip2 uninstall модуль

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

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

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

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

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

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

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

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

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

Requirement already satisfied: networkx in /usr/lib/python2.7/site-packages (2.1) Exception: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/_internal/basecommand.py", line 141, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/_internal/commands/install.py", line 299, in run resolver.resolve(requirement_set) File "/usr/lib/python2.7/site-packages/pip/_internal/resolve.py", line 102, in resolve self._resolve_one(requirement_set, req) File "/usr/lib/python2.7/site-packages/pip/_internal/resolve.py", line 261, in _resolve_one check_dist_requires_python(dist) File "/usr/lib/python2.7/site-packages/pip/_internal/utils/packaging.py", line 46, in check_dist_requires_python feed_parser.feed(metadata) File "/usr/lib/python2.7/email/feedparser.py", line 177, in feed self._input.push(data) File "/usr/lib/python2.7/email/feedparser.py", line 99, in push parts = data.splitlines(True) AttributeError: 'NoneType' object has no attribute 'splitlines'

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

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

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

rm -rf /usr/lib/python2.7/site-packages/networkx-2.1-py2.7.egg-info/
pip2 install networkx Collecting networkx Downloading https://files.pythonhosted.org/packages/11/42/f951cc6838a4dff6ce57211c4d7f8444809ccbe2134179950301e5c4c83c/networkx-2.1.zip (1.6MB) 100% |████████████████████████████████| 1.6MB 2.9MB/s Requirement already satisfied: decorator>=4.1.0 in /usr/lib/python2.7/site-packages (from networkx) (4.3.0) Installing collected packages: networkx Running setup.py install for networkx . done Successfully installed networkx-2.1

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

Заключение

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

  • отсутствует модуль
  • модуль неправильной версии
  • модуль повреждён
  • внешняя причина — программа не получила ожидаемые данные

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

Источник

ModuleNotFoundError: no module named Python Error [Fixed]

Dillion Megida

Dillion Megida

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:

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:

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.

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

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:

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 🙂

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, tweet to the author to show them you care. Tweet a thanks

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

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Оцените статью