Перейти к содержимому

No module named python как исправить

  • автор:

How To Solve ModuleNotFoundError: No module named in Python

In this article, We’ll discuss the reasons and the solutions for the ModuleNotFoundError error.

1. The name of the module is incorrect

The first reason for ModuleNotFoundError: No module named is the module name is incorrect. For example, let’s try to import the os module with double «s» and see what will happen:

As you can see, we got ModuleNotFoundError: No module named ‘oss.’ To solve the error, make sure that you use the correct module name.

Let’s import the module with the correct name.

As you can see, the error is solved.

2. The path of the module is incorrect

The Second reason is the path of the local module you want to import is incorrect. for example, let’s see a directory structure

  • core.py: is the file that will execute
  • folder_1: folder contains my_module.py

Now in core.py, let’s try to import my_module.py

As you can see, we got the error because my_module.py is not in the path that we’ve executed core.py. We need to define the module’s path in the following example to solve the error.

Now we’ve imported m_module successfully.

3. The library is not installed

Also, you can get the ModuleNotFoundError: No module named issue if you are trying to import a library module that is not installed in your virtual environment or computer.

So before importing a library’s module, you need to install it with any package-management system.

Note: pip is recommended.

For example, let’s try to import the Beautifulsoup4 library that’s not installed in my virtual environment.

Now, let’s install the library and try to re-import it:

As you can see, after installing the package, the program is working.

4. The module is unsupported

When a library releases a new update, new modules are added, and others are dropped to support it.

If you try to import a module that is n unsupported by the library, you will get ModuleNotFoundError: No module named.

To ensure the module is supported, go to the package documentation and check if the module is available or not.

5. Python 2 instead of Python 3

As you know, Some Python libraries no longer support Python 2. For that reason, you’ll get the ModuleNotFoundError error if you execute a module that does not support Python 2 with Python 2.

To solve the error:

First, let’s check our python version using these two commands:

In my case, Python 3 is on the python3 command, So I will execute the program using python3. If Python3 is not found on your device, Install Python on Windows, Mac, and Linux.

Python “No Module Named” Import Error

As someone who owns a Coding website and blog, I tend to keep an eye out on the Programming community and their troubles. If I notice enough demand for a certain topic or question, I’ll create a tutorial or make a post about it.

One day while going through a list of popular googles searches, I happened to notice an unusually large number of people making searches like “no module name xxx“. For some Python libraries, there would be over 10k monthly searches like this. If one were to add them all up, they would probably number well over 100k per month.

At any rate, I was quite surprised, and have decided to make this article as a guide, explaining this error, how to fix it and how to avoid running into this in the future.

What does this Error mean?

As the name implies, this error occurs when Python is unable to locate a module that you have tried importing. And as expected of the Python interpreter, it immediately returns an exception, ModuleNotFoundError and shuts the program down.

So why was Python unable to find this module? Let’s assume you were trying to import this library called fly. You used the import fly statement, but of course, since no module called fly exists, the following error was thrown.

We’ll now proceed to examine every possible scenario in which this error can occur and how to fix it.

Library not installed

This is by far the most common reason. You’ve tried to import a library that you saw someone use in a YouTube tutorial, but the problem here is that Python does not come with all these libraries pre-installed and downloaded. Only a certain number of libraries, known as the Standard library can be imported directly. Popular examples of such libraries are DateTime and Tkinter.

So what do you do now? Well, you head over to the command prompt, navigate to your Python installation and use the Python package installer pip to download the library of your choice. It’s a very simple command, pip install <insert library here> .

Since I have the path to my Python.exe added to the list of default paths, I don’t have to manually navigate to it. If you were confused about any step in this process, head over to the Python setup guide where it’s discussed in detail.

Making sure you’re in the correct directory is of utmost importance. Most people make this mistake and simply try to call the pip install from the default location on the command prompt. You must first navigate to the folder with your Python.exe and then call the command. If you don’t know how to navigate the command prompt, you’ll have to look it up.

Multiple Python Installations

One issue that can complicate things is if you have multiple Python installations on your computer. And this is easily possible. As I’m writing this, I currently have two Python installations myself (accidentally of course). The first I happened to download when I was setting up Visual Studio, which would serve as my IDE for Python for a good while. My Python.exe file path looks something like this.

C://Program Files/Microsoft Visual Studio/Python37

Now, every time I download a library, it’s installed in the above folder. As a result only the python.exe in this folder can access those libraries. The second Python installation of mine was done through the regular method, and is stored elsewhere. As a result, it cannot access the libraries installed with the first Python installation.

Now how is this relevant to this article? Well, if you have multiple python installations, there’s a good chance you’ve gotten confused between the two and are importing the library from the wrong place. If this is the case, before rushing over to google this error, make sure that the library is installed at the Python installation you’re currently using.

Incorrect Library name

While extremely unlikely, there is a chance you messed up the library names. I know for fact that sometimes the actual name of a library and the name used to install the library can be a bit different.

For instance the popular web scrapper library BeautifulSoup is installed and imported with the name bs4 . Some people may try to download or import it using the name BeautifulSoup, and that would return an error.

There’s a simple to find the name through which a library is imported. Do a google search like Python numpy and click on the first tutorial for it. 9 times out of 10 there will be a small section at the top where they mention how to install the library.

Importing a file

Unbeknownst to many python programmers, you can actually import another python file into your python program. Why we do this is a story for another article, where it’s explained in greater detail. But for now, we’ll just cover the import problems that may be caused while doing this.

Let’s assume you’re trying to import a file called data.py . To import this correctly, you must use import data . Note the lack of an extension. Secondly, it must be in the same directory as the file you’re importing it into. If the Python files are not in the same directory, a no module named data error will pop up.

You can still import a file even if it’s in another directory, but the process is a bit shaky, so its best to avoid it.

One final tip. Be careful while naming your files. Do not use the names of any libraries, like numpy.py or csv.py . If you do so, and simultaneously import that same library, Python will get confused between the two and try importing the file instead of the library.

I think that just about covers every scenario in which you could possibly face this error. Hopefully you’ve learnt something from this article and won’t have to worry about this error in the future.

BONUS: If you are interested in learning more about importing modules in Python, check out this tutorial which teaches you how to import a module using a user-input string.

This marks the end of the Python “no module named” error Article. Any suggestions or contributions for CodersLegacy are more than welcome. Relevant questions regarding the article can be asking in the comments section below.

Решение проблем с модулями и пакетами 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», но если вы можете сориентироваться, какого рода ошибка у вас возникла:

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

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

How to Fix ModuleNotFoundError and ImportError

Giorgos Myrianthous

Module imports can certainly frustrate people and especially those who are fairly new to Python. Since I keep seeing relevant questions on StackOverflow on a daily basis, I decided to write an article here on Medium to try and describe how import works behind the scenes and what approach you need to follow in order to do your life easier.

Terminology

First, let’s start by defining some useful terms that will help you understand the concepts described in this article.

  • A pythonmodule is a single file with a .py extension.
  • A pythonpackage is a folder that contains at least one python module. For python2, a package requires a __init__.py file
  • A python package can contain any number of nested sub-packages, i.e. packages that contain other packages down the hierarchy of the project structure.
  • imports are useful when a module needs to use some piece of functionality (e.g. a function or a class) written in another module (of the same or a different package or sub-package)

For example, consider the following project structure:

Project myproject contains two packages, mypackage and anotherpackage each of which contains a number of python modules, while the latter also contains a sub-package called mysubpackage which in turn contains an additional python module.

How does module import work behind the scenes?

Now let’s assume that in your current module, you wish to import another module as shown below:

Python will execute the above statement in two steps:

  • Locate, load and initialise (if required) the requested module
  • Define necessary names in the local namespace and corresponding scope

Now Python interpreter is going to follow the next steps in an attempt to resolve a .

Step 1: sys.modules lookup

Initially, Python will try to search for the module’s name in sys.modules , which is a dictionary that maps module names to modules which have already been loaded. If the name is resolved successfully (which means that another module has already loaded it) will be then be made available to the local namespace otherwise, jump into step 2.

Step 2: Python Standard Library lookup

Python Standard Library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs.

If the name couldn’t be found in sys.modules then Python is going to search for it in Python Standard Library. Again, if the name is resolved then it will be defined in the local namespace otherwise step 3 needs to be followed.

Step 3: sys.path lookup

Now if the module’s name was not found either in sys.modules nor in standard library, Python will finally attempt to resolve it under sys.path . And this is the point where things can certainly go wrong. I believe most Python programmes are quite familiar with ModuleNotFoundError

or ImportError :

Absolute vs Relative imports

In absolute imports, we specify the explicit path starting from the project’s root directory. In our example

this means that if we would like to import module a in module b we would have to specify

Other valid examples are the following imports:

Now on the other hand, in relative imports we specify the path to the module relatively to the location of the current module. A few examples in our example could be:

I’d personally discourage the use of relative imports as they are not as readable as absolute imports and PEP-8 suggests the same as well. In some rare cases, you might have to use relative imports in order to avoid unnecessarily long paths. For instance,

How to fix ModuleNotFoundError and ImportError?

Now we’re up to speed with how the basic import statement is executed and what is the difference between absolute and relative imports we can now go ahead and discuss what to do when your Python application fails with either ModuleNotFoundError or ImportError .

In most of the cases, either of the errors occur due to the fact that Python is unable to resolve the module’s name in sys.path . Recall that when you call import a if the module’s name was found neither in sys.modules nor in standard library, Python will try to resolve it in sys.path . Likewise, when you use from syntax (e.g. from mypackage import a ), Python will first attempt to find and load the module. When it fails to do so, Python will throw ModuleNotFoundError for the first case or ImportError for the second case.

If that’s the case and recalling our example below,

  • first make sure you are using absolute imports
  • export the project’s root directory toPYTHONPATH

Most modern Python IDEs will do the trick automatically but if this is not the case, I am pretty sure there will be such option where you’ll be able to define the PYTHONPATH for your Python application (at least PyCharm).

If you are running your Python application in any other environment such as Docker, Vagrant or inside your virutal environment you can run the below command in your bash:

and now since your project’s root directory has been appended to PYTHONPATH your absolute imports should work like a charm.

sys.path.append(/path/to/your/project/ can possibly do the trick as well, but it’s definitely not a good practise.

Conclusion

If you are new to Python, import modules can become a nightmare especially if you need to deal with a complex project structure. If you follow the two-step rule — i.e use absolute imports and append your project’s root directory to PYTHONPATH — then you shouldn’t really worry about module imports in the future.

If you are new to Python, I would highly recommended getting a copy of Learning Python book on Amazon.

Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *