Ошибка при импорте модуля python

I’m having a hard time understanding how module importing works in Python (I’ve never done it in any other language before either).

Let’s say I have:

myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py

Now I’m trying to get something like this:

myapp.py
===================
from myapp import SomeObject
# stuff ...

TestCase.py
===================
from myapp import SomeObject
# some tests on SomeObject

However, I’m definitely doing something wrong as Python can’t see that myapp is a module:

ImportError: No module named myapp

asked Feb 21, 2012 at 18:27

1

In your particular case it looks like you’re trying to import SomeObject from the myapp.py and TestCase.py scripts. From myapp.py, do

import SomeObject

since it is in the same folder. For TestCase.py, do

from ..myapp import SomeObject

However, this will work only if you are importing TestCase from the package. If you want to directly run python TestCase.py, you would have to mess with your path. This can be done within Python:

import sys
sys.path.append("..")
from myapp import SomeObject

though that is generally not recommended.

In general, if you want other people to use your Python package, you should use distutils to create a setup script. That way, anyone can install your package easily using a command like python setup.py install and it will be available everywhere on their machine. If you’re serious about the package, you could even add it to the Python Package Index, PyPI.

answered Feb 21, 2012 at 18:46

David Robinson's user avatar

David RobinsonDavid Robinson

77k16 gold badges165 silver badges184 bronze badges

6

The function import looks for files into your PYTHONPATH env. variable and your local directory. So you can either put all your files in the same directory, or export the path typing into a terminal::

export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"

Michael's user avatar

Michael

1,7742 gold badges19 silver badges31 bronze badges

answered Feb 21, 2012 at 18:31

Zenon's user avatar

ZenonZenon

1,47112 silver badges21 bronze badges

4

exporting path is a good way. Another way is to add a .pth to your site-packages location.
On my mac my python keeps site-packages in /Library/Python shown below

/Library/Python/2.7/site-packages

I created a file called awesome.pth at /Library/Python/2.7/site-packages/awesome.pth and in the file put the following path that references my awesome modules

/opt/awesome/custom_python_modules

answered May 20, 2013 at 23:36

jmontross's user avatar

jmontrossjmontross

3,5231 gold badge21 silver badges17 bronze badges

4

You can try

from myapp.myapp import SomeObject

because your project name is the same as the myapp.py which makes it search the project document first

answered Mar 6, 2017 at 13:54

阿东刘's user avatar

阿东刘阿东刘

1491 silver badge2 bronze badges

You need to have

__init__.py

in all the folders that have code you need to interact with.
You also need to specify the top folder name of your project in every import even if the file you tried to import is at the same level.

answered Jun 5, 2020 at 15:42

Krysalead's user avatar

KrysaleadKrysalead

911 silver badge1 bronze badge

0

In your first myapp directory ,u can add a setup.py file and add two python code in setup.py

from setuptools import setup
setup(name='myapp')

in your first myapp directory in commandline , use pip install -e . to install the package

answered Oct 28, 2017 at 11:30

未来陆家嘴顶尖的投资人's user avatar

未来陆家嘴顶尖的投资人未来陆家嘴顶尖的投资人

1,74821 silver badges19 bronze badges

pip install on Windows 10 defaults to installing in ‘Program Files/PythonXX/Lib/site-packages’ which is a directory that requires administrative privileges. So I fixed my issue by running pip install as Administrator (you have to open command prompt as administrator even if you are logged in with an admin account). Also, it is safer to call pip from python.
e.g.
python -m pip install <package-name>
instead of
pip install <package-name>

answered Aug 21, 2018 at 9:12

sziraqui's user avatar

sziraquisziraqui

5,7333 gold badges27 silver badges37 bronze badges

1

let’s say i write a module

import os
my_home_dir=os.environ['HOME'] // in windows 'HOMEPATH'
file_abs_path=os.path.join(my_home_dir,"my_module.py")

with open(file_abs_path,"w") as f:
   f.write("print('I am loaded successfully')")

import importlib
importlib.util.find_spec('my_module') ==> cannot find

we have to tell python where to look for the module. we have to add our path to the sys.path

 import sys
 sys.path.append(file_abs_path)

now importlib.util.find_spec('my_module') returns:

  ModuleSpec(name='my_module', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa40143e8e0>, origin='/Users/name/my_module.py')

we created our module, we informed python its path, now we should be able to import it

 import my_module

//I am loaded successfully

answered Sep 14, 2020 at 2:09

Yilmaz's user avatar

YilmazYilmaz

31.7k10 gold badges149 silver badges183 bronze badges

0

Short Answer:

python -m ParentPackage.Submodule

Executing the required file via module flag worked for me. Lets say we got a typical directory structure as below:

my_project:
 | Core
    ->myScript.py
 | Utils
   ->helpers.py
 configs.py

Now if you want to run a file inside a directory, that has imports from other modules, all you need to do is like below:

python -m Core.myscript

PS: You gotta use dot notation to refer the submodules(Files/scripts you want to execute). Also I used python3.9+. So I didnt require neither any init.py nor any sys path append statements.

Hope that helps! Happy Coding!

answered Aug 29, 2021 at 13:23

Deekshith Anand's user avatar

Deekshith AnandDeekshith Anand

2,0751 gold badge19 silver badges24 bronze badges

In my case it was Windows vs Python surprise, despite Windows filenames are not case sensitive, Python import is. So if you have Stuff.py file you need to import this name as-is.

answered May 17, 2018 at 9:31

astrowalker's user avatar

astrowalkerastrowalker

3,0733 gold badges18 silver badges39 bronze badges

This worked for me:

from .myapp import SomeObject

The . signifies that it will search any local modules from the parent module.

answered May 30, 2022 at 3:58

Evan Schwartzentruber's user avatar

If you use Anaconda you can do:

conda develop /Path/To/Your/Modules

from the Shell and it will write your path into a conda.pth file into the standard directory for 3rd party modules (site-packages in my case).

answered Aug 5, 2022 at 21:39

Alexander Audet's user avatar

If you are using the IPython Console, make sure your IDE (e.g., spyder) is pointing to the right working directory (i.e., your project folder)

answered Nov 18, 2022 at 15:16

Mehdi Boukhechba's user avatar

Mehdi BoukhechbaMehdi Boukhechba

2,4512 gold badges19 silver badges24 bronze badges

Besides the suggested solutions like the accepted answer, I had the same problem in Pycharm, and I didn’t want to modify imports like the relative addressing suggested above.

I finally found out that if I mark my src/ (root directory of my python codes) as the source in Interpreter settings, the issue will be resolved.

In the settings

enter image description here

answered Dec 25, 2022 at 13:57

AMK's user avatar

AMKAMK

4925 silver badges15 bronze badges

В 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 

After installing mechanize, I don’t seem to be able to import it.

I have tried installing from pip, easy_install, and via python setup.py install from this repo: https://github.com/abielr/mechanize. All of this to no avail, as each time I enter my Python interactive I get:

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mechanize
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named mechanize
>>> 

The installations I ran previously reported that they had completed successfully, so I expect the import to work. What could be causing this error?

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

asked Jan 12, 2013 at 17:07

roy's user avatar

8

In my case, it is permission problem. The package was somehow installed with root rw permission only, other user just cannot rw to it!

nbro's user avatar

nbro

15.2k32 gold badges110 silver badges196 bronze badges

answered May 4, 2013 at 17:55

Paul Wang's user avatar

Paul WangPaul Wang

1,6361 gold badge12 silver badges19 bronze badges

7

I had the same problem: script with import colorama was throwing an ImportError, but sudo pip install colorama was telling me «package already installed».

My fix: run pip without sudo: pip install colorama. Then pip agreed it needed to be installed, installed it, and my script ran. Or even better, use python -m pip install <package>. The benefit of this is, since you are executing the specific version of python that you want the package in, pip will unequivocally install the package into the «right» python. Again, don’t use sudo in this case… then you get the package in the right place, but possibly with (unwanted) root permissions.

My environment is Ubuntu 14.04 32-bit; I think I saw this before and after I activated my virtualenv.

wjandrea's user avatar

wjandrea

27.2k9 gold badges59 silver badges80 bronze badges

answered Jan 14, 2016 at 19:12

Dan H's user avatar

Dan HDan H

14k6 gold badges39 silver badges32 bronze badges

3

I was able to correct this issue with a combined approach. First, I followed Chris’ advice, opened a command line and typed ‘pip show packagename’
This provided the location of the installed package.

Next, I opened python and typed ‘import sys’, then ‘sys.path’ to show where my python searches for any packages I import. Alas, the location shown in the first step was NOT in the list.

Final step, I typed ‘sys.path.append(‘package_location_seen_in_step_1’). You optionally can repeat step two to see the location is now in the list.

Test step, try to import the package again… it works.

The downside? It is temporary, and you need to add it to the list each time.

answered Apr 1, 2018 at 20:19

MJ_'s user avatar

MJ_MJ_

5441 gold badge6 silver badges10 bronze badges

It’s the python path problem.

In my case, I have python installed in:

/Library/Frameworks/Python.framework/Versions/2.6/bin/python,

and there is no site-packages directory within the python2.6.

The package(SOAPpy) I installed by pip is located

/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/

And site-package is not in the python path, all I did is add site-packages to PYTHONPATH permanently.

  1. Open up Terminal

  2. Type open .bash_profile

  3. In the text file that pops up, add this line at the end:

    export PYTHONPATH=$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/
    
  4. Save the file, restart the Terminal, and you’re done

desertnaut's user avatar

desertnaut

57k23 gold badges137 silver badges165 bronze badges

answered Apr 22, 2014 at 17:45

user1552891's user avatar

user1552891user1552891

5175 silver badges4 bronze badges

3

The Python import mechanism works, really, so, either:

  1. Your PYTHONPATH is wrong,
  2. Your library is not installed where you think it is
  3. You have another library with the same name masking this one

answered Jan 12, 2013 at 17:19

Ali Afshar's user avatar

Ali AfsharAli Afshar

40.8k12 gold badges94 silver badges109 bronze badges

8

I have been banging my head against my monitor on this until a young-hip intern told me the secret is to «python setup.py install» inside the module directory.

For some reason, running the setup from there makes it just work.

To be clear, if your module’s name is «foo»:

[burnc7 (2016-06-21 15:28:49) git]# ls -l
total 1
drwxr-xr-x 7 root root  118 Jun 21 15:22 foo
[burnc7 (2016-06-21 15:28:51) git]# cd foo
[burnc7 (2016-06-21 15:28:53) foo]# ls -l
total 2
drwxr-xr-x 2 root root   93 Jun 21 15:23 foo
-rw-r--r-- 1 root root  416 May 31 12:26 setup.py
[burnc7 (2016-06-21 15:28:54) foo]# python setup.py install
<--snip-->

If you try to run setup.py from any other directory by calling out its path, you end up with a borked install.

DOES NOT WORK:

python /root/foo/setup.py install

DOES WORK:

cd /root/foo
python setup.py install

answered Jun 21, 2016 at 22:32

Locane's user avatar

LocaneLocane

2,8562 gold badges24 silver badges33 bronze badges

1

I encountered this while trying to use keyring which I installed via sudo pip install keyring. As mentioned in the other answers, it’s a permissions issue in my case.

What worked for me:

  1. Uninstalled keyring:
  • sudo pip uninstall keyring
  1. I used sudo’s -H option and reinstalled keyring:
  • sudo -H pip install keyring

bad_coder - on strike's user avatar

answered Sep 4, 2018 at 5:56

blackleg's user avatar

blacklegblackleg

3513 silver badges3 bronze badges

In PyCharm, I fixed this issue by changing the project interpreter path.

File -> Settings -> Project -> Project Interpreter

File -> Invalidate Caches… may be required afterwards.

miken32's user avatar

miken32

41.5k16 gold badges108 silver badges153 bronze badges

answered Feb 27, 2019 at 18:40

Amit D's user avatar

Amit DAmit D

611 silver badge2 bronze badges

1

I couldn’t get my PYTHONPATH to work properly. I realized adding export fixed the issue:

(did work)

export PYTHONPATH=$PYTHONPATH:~/test/site-packages

vs.

(did not work)

PYTHONPATH=$PYTHONPATH:~/test/site-packages

buczek's user avatar

buczek

2,0117 gold badges29 silver badges40 bronze badges

answered Dec 6, 2016 at 16:32

George Weber's user avatar

This problem can also occur with a relocated virtual environment (venv).

I had a project with a venv set up inside the root directory. Later I created a new user and decided to move the project to this user. Instead of moving only the source files and installing the dependencies freshly, I moved the entire project along with the venv folder to the new user.

After that, the dependencies that I installed were getting added to the global site-packages folder instead of the one inside the venv, so the code running inside this env was not able to access those dependencies.

To solve this problem, just remove the venv folder and recreate it again, like so:

$ deactivate
$ rm -rf venv
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install -r requirements.txt

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

answered Nov 24, 2020 at 5:34

Jaikishan's user avatar

1

Something that worked for me was:

python -m pip install -user {package name}

The command does not require sudo. This was tested on OSX Mojave.

answered Aug 19, 2019 at 21:35

IShaan's user avatar

IShaanIShaan

931 gold badge1 silver badge6 bronze badges

0

In my case I had run pip install Django==1.11 and it would not import from the python interpreter.

Browsing through pip’s commands I found pip show which looked like this:

> pip show Django
Name: Django
Version: 1.11
...
Location: /usr/lib/python3.4/site-packages
...

Notice the location says ‘3.4’. I found that the python-command was linked to python2.7

/usr/bin> ls -l python
lrwxrwxrwx 1 root root 9 Mar 14 15:48 python -> python2.7

Right next to that I found a link called python3 so I used that. You could also change the link to python3.4. That would fix it, too.

answered Apr 6, 2017 at 14:05

Chris's user avatar

ChrisChris

5,6484 gold badges29 silver badges39 bronze badges

In my case it was a problem with a missing init.py file in the module, that I wanted to import in a Python 2.7 environment.

Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an init.py file.

answered Apr 26, 2019 at 9:26

jens_laufer's user avatar

jens_lauferjens_laufer

1582 silver badges13 bronze badges

Had this problem too.. the package was installed on Python 3.8.0 but VS Code was running my script using an older version (3.4)

fix in terminal:

py .py

Make sure you’re installing the package on the right Python Version

answered Nov 21, 2019 at 20:39

Aramich100's user avatar

I had colorama installed via pip and I was getting «ImportError: No module named colorama»

So I searched with «find», found the absolute path and added it in the script like this:

import sys
sys.path.append("/usr/local/lib/python3.8/dist-packages/")
import colorama 

And it worked.

answered Aug 25, 2020 at 13:01

DimiDak's user avatar

DimiDakDimiDak

4,7202 gold badges24 silver badges32 bronze badges

I had just the same problem, and updating setuptools helped:

python3 -m pip install --upgrade pip setuptools wheel

After that, reinstall the package, and it should work fine :)

The thing is, the package is built incorrectly if setuptools is old.

answered Jul 28, 2022 at 8:00

Ivan Konovalov's user avatar

Check that you are using the same python version in the interpreter of your IDE or code editor and on your system.
For example, check your python version in the terminal with python3 --version
And check python version for interpreter in VSCode by cmd+shift+p-> Python: Select interpreter -> select the same version as you see in your terminal.enter image description here

answered Jan 13 at 14:06

Anna Logacheva's user avatar

Anna LogachevaAnna Logacheva

7021 gold badge9 silver badges16 bronze badges

If the other answers mentioned do not work for you, try deleting your pip cache and reinstalling the package. My machine runs Ubuntu14.04 and it was located under ~/.cache/pip. Deleting this folder did the trick for me.

answered Aug 7, 2019 at 1:29

sbrk's user avatar

sbrksbrk

1,3081 gold badge16 silver badges25 bronze badges

Also, make sure that you do not confuse pip3 with pip. What I found was that package installed with pip was not working with python3 and vice-versa.

answered Nov 14, 2019 at 14:14

Devansh Maurya's user avatar

I had similar problem (on Windows) and the root cause in my case was ANTIVIRUS software! It has «Auto-Containment» feature, that wraps running process with some kind of a virtual machine.
Symptoms are: pip install somemodule works fine in one cmd-line window and import somemodule fails when executed from another process with the error

ModuleNotFoundError: No module named 'somemodule'

bad_coder - on strike's user avatar

answered May 7, 2018 at 6:42

Dima G's user avatar

Dima GDima G

1,89518 silver badges22 bronze badges

In my case (an Ubuntu 20.04 VM on WIN10 Host), I have a disordered situation with many version of Python installed and variuos point of Shared Library (installed with pip in many points of the File System). I’m referring to 3.8.10 Python version.
After many tests, I’ve found a suggestion searching with google (but’ I’m sorry, I haven’t the link). This is what I’ve done to resolve the problem :

  1. From shell session on Ubuntu 20.04 VM, (inside the Home, in my case /home/hduser), I’ve started a Jupyter Notebook session with the command «jupyter notebook».

  2. Then, when jupyter was running I’ve opened a .ipynb file to give commands.

  3. First : pip list —> give me the list of packages installed, and, sympy
    wasn’t present (although I had installed it with «sudo pip install sympy»
    command.

  4. Last with the command !pip3 install sympy (inside jupyter notebook
    session) I’ve solved the problem, here the screen-shot :
    enter image description here

  5. Now, with !pip list the package «sympy» is present, and working :
    enter image description here

answered Jan 9, 2022 at 11:43

Colonna Maurizio's user avatar

In my case, I assumed a package was installed because it showed up in the output of pip freeze. However, just the site-packages/*.dist-info folder is enough for pip to list it as installed despite missing the actual package contents (perhaps from an accidental deletion). This happens even when all the path settings are correct, and if you try pip install <pkg> it will say «requirement already satisfied».

The solution is to manually remove the dist-info folder so that pip realizes the package contents are missing. Then, doing a fresh install should re-populate anything that was accidentally removed

answered Oct 4, 2022 at 17:59

Addison Klinke's user avatar

Addison KlinkeAddison Klinke

9852 gold badges13 silver badges23 bronze badges

When you install via easy_install or pip, is it completing successfully? What is the full output? Which python installation are you using? You may need to use sudo before your installation command, if you are installing modules to a system directory (if you are using the system python installation, perhaps). There’s not a lot of useful information in your question to go off of, but some tools that will probably help include:

  • echo $PYTHONPATH and/or echo $PATH: when importing modules, Python searches one of these environment variables (lists of directories, : delimited) for the module you want. Importing problems are often due to the right directory being absent from these lists

  • which python, which pip, or which easy_install: these will tell you the location of each executable. It may help to know.

  • Use virtualenv, like @JesseBriggs suggests. It works very well with pip to help you isolate and manage the modules and environment for separate Python projects.

answered Jan 12, 2013 at 17:26

Ryan Artecona's user avatar

Ryan ArteconaRyan Artecona

5,9233 gold badges19 silver badges18 bronze badges

0

I had this exact problem, but none of the answers above worked. It drove me crazy until I noticed that sys.path was different after I had imported from the parent project. It turned out that I had used importlib to write a little function in order to import a file not in the project hierarchy. Bad idea: I forgot that I had done this. Even worse, the import process mucked with the sys.path—and left it that way. Very bad idea.

The solution was to stop that, and simply put the file I needed to import into the project. Another approach would have been to put the file into its own project, as it needs to be rebuilt from time to time, and the rebuild may or may not coincide with the rebuild of the main project.

answered Apr 17, 2016 at 19:08

ivanlan's user avatar

ivanlanivanlan

9596 silver badges8 bronze badges

I had this problem with 2.7 and 3.5 installed on my system trying to test a telegram bot with Python-Telegram-Bot.

I couldn’t get it to work after installing with pip and pip3, with sudo or without. I always got:

Traceback (most recent call last):
  File "telegram.py", line 2, in <module>
    from telegram.ext import Updater
  File "$USER/telegram.py", line 2, in <module>
    from telegram.ext import Updater
ImportError: No module named 'telegram.ext'; 'telegram' is not a package

Reading the error message correctly tells me that python is looking in the current directory for a telegram.py. And right, I had a script lying there called telegram.py and this was loaded by python when I called import.

Conclusion, make sure you don’t have any package.py in your current working dir when trying to import. (And read error message thoroughly).

answered Jan 10, 2017 at 7:09

Patrick B.'s user avatar

Patrick B.Patrick B.

11.7k8 gold badges57 silver badges100 bronze badges

I had a similar problem using Django. In my case, I could import the module from the Django shell, but not from a .py which imported the module.
The problem was that I was running the Django server (therefore, executing the .py) from a different virtualenv from which the module had been installed.

Instead, the shell instance was being run in the correct virtualenv. Hence, why it worked.

mx0's user avatar

mx0

6,35812 gold badges49 silver badges54 bronze badges

answered May 9, 2019 at 17:41

aleclara95's user avatar

This Works!!!

This often happens when module is installed to an older version of python or another directory, no worries as solution is simple.
— import module from directory in which module is installed.
You can do this by first importing the python sys module then importing from the path in which the module is installed

import sys
sys.path.append("directory in which module is installed")

import <module_name>

answered Jul 4, 2019 at 1:56

Terrence_Freeman's user avatar

Most of the possible cases have been already covered in solutions, just sharing my case, it happened to me that I installed a package in one environment (e.g. X) and I was importing the package in another environment (e.g. Y). So, always make sure that you’re importing the package from the environment in which you installed the package.

answered Aug 2, 2019 at 16:45

Pedram's user avatar

PedramPedram

2,3892 gold badges31 silver badges48 bronze badges

For me it was ensuring the version of the module aligned with the version of Python I was using.. I built the image on a box with Python 3.6 and then injected into a Docker image that happened to have 3.7 installed, and then banging my head when Python was telling me the module wasn’t installed…

36m for Python 3.6
bsonnumpy.cpython-36m-x86_64-linux-gnu.so

37m for Python 3.7 bsonnumpy.cpython-37m-x86_64-linux-gnu.so

answered Sep 18, 2019 at 15:43

mkst's user avatar

mkstmkst

5556 silver badges16 bronze badges

4

I know this is a super old post but for me, I had an issue with a 32 bit python and 64 bit python installed. Once I uninstalled the 32 bit python, everything worked as it should.

answered Sep 24, 2019 at 13:18

Moultrie's user avatar

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

>>> Насколько я знаю, это импортирует все функции? А если нужно импортировать весь код?
Для модулей только функции и классы нужны. Или вы хотите вызвать и исполнение кода, что не в функциях?
Если так, то при импорте происходит исполнение кода модуля, т.е. что не в функциях сразу же исполняется. Обычно, это как раз, не требуется и соответственно этого пытаются избежать таким способом:

def main():
    pass # код который исполняется при запуске, а не при импорте

if __name__ == '__main__':
    main()

__name__ будет равен __main__ при прямом запуске этого модуля, и имени файла без расширения (.py) при импорте. Для кругозора прочитайте про пространство имен в Python-е. Спойлер: модули(файлы *.py) в 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
from tkinter import *
import numpy as np
import random
 
canvas_width = 700
canvas_height = 500
brush_size = 3
color = "black"
 
def create_point():
    chislo = message.get()
    n = int(chislo) - 1
    x1 = random.randrange(start=1, stop=700)
    y1 = random.randrange(start=1, stop=500)
    for i in range(n):
        x2 = random.randrange(start=1, stop=700)
        y2 = random.randrange(start=1, stop=500)
        w.create_line(x1, y1, x2, y2, fill=color)
        x1 = x2
        y1 = y2
 
root = Tk()
root.title("Точки-ломаная-сгладить")
 
message = StringVar()
 
message_entry = Entry(textvariable=message)
 
w = Canvas(root, width=canvas_width, height=canvas_height, bg="white")
w.bind("<B1-Motion>")
 
create_btn = Button(text="Соединить точки", width=14, command=lambda: create_point())
b_btn = Button(text="Сгладить ломаную", width=15, command=lambda: color_change("yellow"))
clear_btn = Button(text="Очистить", width=10, command=lambda: w.delete("all"))
 
w.grid(row=2, column=0, columnspan=7, padx=5, pady=5, sticky=E+W+S+N)
w.columnconfigure(6, weight=1)
w.rowconfigure(2, weight=1)
 
message_entry.grid(row=0, column=2)
create_btn.grid(row=0, column=3)
b_btn.grid(row=0, column=4)
clear_btn.grid(row=0, column=5, sticky=W)
 
root.mainloop()

Что означает ошибка 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

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

Вёрстка:

Кирилл Климентьев

Время чтения 1 мин.

Если вы работаете с Visual Studio Code и импортируете любую библиотеку, вы столкнетесь с этой ошибкой: «неразрешенный импорт». Чтобы исправить ошибку неразрешенного импорта, укажите путь к Python в настройках рабочей области.

{

   «python.pythonPath»: «/path/to/your/venv/bin/python»,

}

Затем перезагрузите VSCode, и он исправит эту ошибку.

Для импорта, специфичного для Python, этот способ исправляет данную проблему импорта, но не решает ваши модули. При импорте модулей будет возвращена та же ошибка, и для ее устранения используйте следующий параметр в настройках рабочей области .vscode/settings.json.

«python.autoComplete.extraPaths»: [«./path-to-your-code»],

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

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

Введите Cmd / Ctrl + Shift + P → Python: Select Interpreter → выберите тот, который содержит нужные вам пакеты, и все.

Использование файла .env

Вы также можете создать файл .env в корневой папке проекта. Затем добавьте к нему PYTHONPATH, как показано в следующем коде.

PYTHONPATH = path/to/your/code

И в файле settings.json добавьте следующий код.

Затем перезагрузите VSCode, и он исправит эту ошибку.

Понравилась статья? Поделить с друзьями:
  • Ошибка при инициализации гта 5 что делать
  • Ошибка при импорте audacity
  • Ошибка при инициализации гта 5 рп при сворачивании
  • Ошибка при иммобилизации всей нижней конечности лестничными шинами
  • Ошибка при измерении сканворд