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
62.3k11 gold badges102 silver badges153 bronze badges
asked Jan 12, 2013 at 17:07
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
15.4k32 gold badges113 silver badges197 bronze badges
answered May 4, 2013 at 17:55
Paul WangPaul Wang
1,7111 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
28.5k9 gold badges62 silver badges82 bronze badges
answered Jan 14, 2016 at 19:12
Dan HDan H
14.1k6 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_MJ_
5541 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.
-
Open up Terminal
-
Type open .bash_profile
-
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/
-
Save the file, restart the Terminal, and you’re done
desertnaut
57.7k27 gold badges140 silver badges167 bronze badges
answered Apr 22, 2014 at 17:45
user1552891user1552891
5275 silver badges4 bronze badges
3
The Python import mechanism works, really, so, either:
- Your PYTHONPATH is wrong,
- Your library is not installed where you think it is
- You have another library with the same name masking this one
answered Jan 12, 2013 at 17:19
Ali AfsharAli Afshar
41k12 gold badges95 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
LocaneLocane
2,8962 gold badges24 silver badges35 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:
- Uninstalled keyring:
sudo pip uninstall keyring
- I used sudo’s
-H
option and reinstalled keyring:
sudo -H pip install keyring
bad_coder
11.3k20 gold badges44 silver badges72 bronze badges
answered Sep 4, 2018 at 5:56
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
42k16 gold badges111 silver badges154 bronze badges
answered Feb 27, 2019 at 18:40
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
2,0117 gold badges29 silver badges40 bronze badges
answered Dec 6, 2016 at 16:32
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
62.3k11 gold badges102 silver badges153 bronze badges
answered Nov 24, 2020 at 5:34
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
IShaanIShaan
931 gold badge1 silver badge6 bronze badges
0
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.
answered Jan 13 at 14:06
AnnAnn
7821 gold badge9 silver badges17 bronze badges
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
ChrisChris
5,8074 gold badges29 silver badges40 bronze badges
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
DimiDakDimiDak
4,8302 gold badges26 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
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.
wjandrea
28.5k9 gold badges62 silver badges82 bronze badges
answered Apr 26, 2019 at 9:26
jens_lauferjens_laufer
1903 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 <yourfile>.py
Make sure you’re installing the package on the right Python version.
wjandrea
28.5k9 gold badges62 silver badges82 bronze badges
answered Nov 21, 2019 at 20:39
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
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
sbrksbrk
1,3381 gold badge17 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
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
11.3k20 gold badges44 silver badges72 bronze badges
answered May 7, 2018 at 6:42
Dima GDima G
1,95518 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 :
-
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».
-
Then, when jupyter was running I’ve opened a .ipynb file to give commands.
-
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. -
Last with the command !pip3 install sympy (inside jupyter notebook
session) I’ve solved the problem, here the screen-shot :
-
Now, with !pip list the package «sympy» is present, and working :
answered Jan 9, 2022 at 11:43
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 KlinkeAddison Klinke
1,0342 gold badges14 silver badges23 bronze badges
Not sure if this will help anyone, but I had a similar issue on Mac M1 with zsh. Turns out I had set an alias command in my .zshrc file with the same name as my python command (python3).
To solve the issue, I just had to unalias the command. I ran:
unalias python3
both from my home terminal and from the terminal in Visual Studio.
answered Feb 8 at 11:00
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/orecho $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
, orwhich 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 ArteconaRyan Artecona
5,9733 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
ivanlanivanlan
9896 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.Patrick B.
11.8k8 gold badges58 silver badges101 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
6,50512 gold badges50 silver badges54 bronze badges
answered May 9, 2019 at 17:41
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
PedramPedram
2,4215 gold badges31 silver badges49 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
mkstmkst
5656 silver badges16 bronze badges
4
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 RobinsonDavid Robinson
77.4k16 gold badges167 silver badges187 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
1,8542 gold badges21 silver badges33 bronze badges
answered Feb 21, 2012 at 18:31
ZenonZenon
1,48112 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
jmontrossjmontross
3,5331 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
阿东刘阿东刘
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
KrysaleadKrysalead
1011 silver badge3 bronze badges
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
sixsixsixsixsixsix
1,76821 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
sziraquisziraqui
5,7733 gold badges28 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
YilmazYilmaz
35.9k11 gold badges157 silver badges206 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 AnandDeekshith Anand
2,2231 gold badge21 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
astrowalkerastrowalker
3,1413 gold badges21 silver badges40 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
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
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 BoukhechbaMehdi Boukhechba
2,4812 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.
answered Dec 25, 2022 at 13:57
AMKAMK
6746 silver badges16 bronze badges
I added my custom modules path to python3*._pth file.It will be located in the python installed directory.
This resolved the issue
answered Jul 27 at 7:25
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:
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
asnumpys
during import - you use an incorrect casing for a module (which still links back to the first point)…for example, spelling
numpy
asNumPy
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
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
62.3k11 gold badges102 silver badges153 bronze badges
asked Jan 12, 2013 at 17:07
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
15.4k32 gold badges113 silver badges197 bronze badges
answered May 4, 2013 at 17:55
Paul WangPaul Wang
1,7111 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
28.5k9 gold badges62 silver badges82 bronze badges
answered Jan 14, 2016 at 19:12
Dan HDan H
14.1k6 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_MJ_
5541 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.
-
Open up Terminal
-
Type open .bash_profile
-
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/
-
Save the file, restart the Terminal, and you’re done
desertnaut
57.7k27 gold badges140 silver badges167 bronze badges
answered Apr 22, 2014 at 17:45
user1552891user1552891
5275 silver badges4 bronze badges
3
The Python import mechanism works, really, so, either:
- Your PYTHONPATH is wrong,
- Your library is not installed where you think it is
- You have another library with the same name masking this one
answered Jan 12, 2013 at 17:19
Ali AfsharAli Afshar
41k12 gold badges95 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
LocaneLocane
2,8962 gold badges24 silver badges35 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:
- Uninstalled keyring:
sudo pip uninstall keyring
- I used sudo’s
-H
option and reinstalled keyring:
sudo -H pip install keyring
bad_coder
11.3k20 gold badges44 silver badges72 bronze badges
answered Sep 4, 2018 at 5:56
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
42k16 gold badges111 silver badges154 bronze badges
answered Feb 27, 2019 at 18:40
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
2,0117 gold badges29 silver badges40 bronze badges
answered Dec 6, 2016 at 16:32
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
62.3k11 gold badges102 silver badges153 bronze badges
answered Nov 24, 2020 at 5:34
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
IShaanIShaan
931 gold badge1 silver badge6 bronze badges
0
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.
answered Jan 13 at 14:06
AnnAnn
7821 gold badge9 silver badges17 bronze badges
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
ChrisChris
5,8074 gold badges29 silver badges40 bronze badges
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
DimiDakDimiDak
4,8302 gold badges26 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
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.
wjandrea
28.5k9 gold badges62 silver badges82 bronze badges
answered Apr 26, 2019 at 9:26
jens_lauferjens_laufer
1903 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 <yourfile>.py
Make sure you’re installing the package on the right Python version.
wjandrea
28.5k9 gold badges62 silver badges82 bronze badges
answered Nov 21, 2019 at 20:39
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
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
sbrksbrk
1,3381 gold badge17 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
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
11.3k20 gold badges44 silver badges72 bronze badges
answered May 7, 2018 at 6:42
Dima GDima G
1,95518 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 :
-
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».
-
Then, when jupyter was running I’ve opened a .ipynb file to give commands.
-
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. -
Last with the command !pip3 install sympy (inside jupyter notebook
session) I’ve solved the problem, here the screen-shot :
-
Now, with !pip list the package «sympy» is present, and working :
answered Jan 9, 2022 at 11:43
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 KlinkeAddison Klinke
1,0342 gold badges14 silver badges23 bronze badges
Not sure if this will help anyone, but I had a similar issue on Mac M1 with zsh. Turns out I had set an alias command in my .zshrc file with the same name as my python command (python3).
To solve the issue, I just had to unalias the command. I ran:
unalias python3
both from my home terminal and from the terminal in Visual Studio.
answered Feb 8 at 11:00
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/orecho $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
, orwhich 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 ArteconaRyan Artecona
5,9733 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
ivanlanivanlan
9896 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.Patrick B.
11.8k8 gold badges58 silver badges101 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
6,50512 gold badges50 silver badges54 bronze badges
answered May 9, 2019 at 17:41
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
PedramPedram
2,4215 gold badges31 silver badges49 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
mkstmkst
5656 silver badges16 bronze badges
4
Ошибка «ImportError: No module named» в Python — это типичная проблема, с которой сталкиваются новички. Она возникает, когда Python не может найти модуль, который
Ошибка «ImportError: No module named» в Python — это типичная проблема, с которой сталкиваются новички. Она возникает, когда Python не может найти модуль, который указан для импорта в коде.
Рассмотрим пример. Предположим, есть следующая структура директорий:
(local directory)/site-packages/toolkit/interface.py
И код находится здесь:
(local directory)/site-packages/toolkit/examples/mountain.py
Чтобы запустить пример, используется команда python mountain.py
, и в коде есть строка:
from toolkit.interface import interface
Но при запуске кода возникает ошибка:
Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
Это означает, что Python не может найти указанный модуль или пакет. Возможные причины могут быть следующими:
-
Неправильный путь к модулю. Python ищет модули и пакеты в определенных местах. Если модуль или пакет находится в директории, которая не входит в
sys.path
, Python не сможет его найти. В этом случае, необходимо убедиться, что путь к модулю или пакету правильный. -
Отсутствует файл
__init__.py
. В каждом пакете Python должен быть файл__init__.py
(может быть пустым), чтобы Python мог распознать пакет. Если этого файла нет, Python не сможет импортировать модули из этого пакета. -
Проблемы с правами доступа. Если у Python нет прав на чтение файла модуля или пакета, он не сможет его импортировать. В этом случае, необходимо проверить права доступа к файлам и директориям.
-
Неправильное имя модуля или пакета. Имя модуля или пакета в команде import должно быть точно таким же, как и имя файла (без расширения
.py
). Если имена не совпадают, Python не сможет найти и импортировать модуль или пакет.
Решение этой проблемы — это процесс исключения. Нужно проверить каждую из возможных причин, пока не будет найдена та, которая вызвала ошибку. Затем можно приступить к исправлению этой проблемы.