Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm trying to run a script that launches, amongst other things, a python script. I get a ImportError: No module named ... , however, if I launch ipython and import the same module in the same way through the interpreter, the module is accepted.

What's going on, and how can I fix it? I've tried to understand how python uses PYTHONPATH but I'm thoroughly confused. Any help would greatly appreciated.

You need to give more information. When you say "run a script", do you mean a shell script? What module is it that you cannot import? Where is that module located? Where is your script located? BrenBarn Mar 20, 2013 at 3:11 If you want a definitive answer to "what's going on", start python with the -v option and you will see where python is (or is not) finding the modules you import. FatalError Mar 20, 2013 at 3:13 Please give us the code you are running, the full text of the stack trace, and the exact steps you are taking to produce the error. It's rather difficult to assist when we don't know what the exact problem is. MattDMo supports the strike Mar 20, 2013 at 4:49 I guess it's a problem lots of users experience, even 4 years after the question was first asked. CodeOcelot Jun 15, 2017 at 20:10

This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you're operating in is the same one you started ipython in. If you run

import os
os.getcwd() 

you'll see this is true.

However, let's say you're using an ipython notebook, run os.getcwd() and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir setting).

The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:

import sys
sys.path.append('my/path/to/module/folder')
import module_of_interest

If that doesn't work, you've got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.

The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.

PSA: if you've come to this SO question because you're getting this error in jupyter-notebook, then see below, stackoverflow.com/a/27944947/127971 Unfortunately, the question is not specific enough for a single answer. – michael Jul 15, 2017 at 19:45 @michael that answer is about importing Python modules in the general case; the dunder init.py file is needed when the interpreter searches directories for modules to import, notebook or not. The above answer about the notebook interpreter working directory and setting PYTHONPATH is correct. – BoltzmannBrain Jul 15, 2017 at 19:58 I did say there were going to be multiple correct answers, due to the wording of the question. I'm not implying this answer isn't correct. But if using jupyter-notebook, you're just going to touch the file __init_.py, right? ...and, not going to want to modify PYTHONPATH nor call sys.path.append, even if they are also correct (correct?). I mean, I have dozens of directories w/ code in them, and I'm not going to add them all to the path -- or expect other users to their jupyter config file, even if it's one directory. – michael Jul 15, 2017 at 22:52 This was helpful for me. Especially because the init.py was in the correct folders and that had worked locally but not in jupyter... – Joseph Oct 28, 2021 at 13:51 By 'init.py' you mean '_init_.py', right? I created the _init_.py as an empty file and it worked for me. Thanks a lot. But why is this needed? Before I had a python script in the same directory as my ipython notebook and the import was working fine. – Eduardo Reis Nov 18, 2015 at 12:49 actually init.py is used to indicate python to indicate there is some package containing in that corresponding location. then only it will found sub modules whatever you created under it. if you doesn't create 'init.py' means python don't know there is some package in it. Eg: from "Myfolder.Mypackage import Mymodules" for this eg, you should initiate init.py to indicate python to tell there is some package here. else it don't know. – Mohideen bin Mohammed Nov 19, 2015 at 6:48

Make sure they are both using the same interpreter. This happened to me on Ubuntu:

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]
$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

And sys.path was different between the two interpreters. To fix it, I removed Python 3.3.

having used miniconda to install a bunch of python related stuff I also got exactly this problem. The bundled ubuntu python 2.7 being different to the miniconda python 2.7. This answer allowed me to fix the issue – bph Feb 24, 2016 at 21:51 This was my problem. I had upgraded to python 2.7.11 but my iPython interactive shell was still using 2.7.5. I just needed to run pip install --upgrade ipython to get the latest version and then it automatically used 2.7.11 by default. – Abundnce10 May 3, 2016 at 17:46

The main reason is the sys.paths of Python and IPython are different.

Please refer to lucypark link, the solution works in my case. It happen when install opencv by

conda install opencv

And got import error in iPython, There are three steps to solve this issue:

import cv2
ImportError: ...

1. Check path in Python and iPython with following command

import sys
sys.path

You will find different result from Python and Jupyter. Second step, just use sys.path.append to fix the missed path by try-and-error.

2. Temporary solution

In iPython:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

the ImportError:.. issue solved

3. Permanent solution

Create an iPython profile and set initial append:

In bash shell:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

In vi, append to the file:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
                'ipython profile create' .... Yes! This is the only (permanent) solution that addresses jupyter notebook not reading from environment PATH and PYTHONPATH ... without resorting to messy sys.path statements at the start of every file (yuk). thank you @jesse.
– JohnL_10
                Mar 26, 2020 at 22:29
                I'd have thought it better to set the PYTHONPATH on a per project basis instead of in every shell, e.g. with dotenv etc.
– RobinGower
                May 25 at 11:45
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

I have found that the solution to this problem was extensively documented here:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

Basically, you must install the packages within the Jupyter environment, issuing shell commands like:

!{sys.executable} -m pip install numpy

Please check the above link for an authoritative full answer.

Before installing ipython, I installed modules through easy_install; say sudo easy_install mechanize.

After installing ipython, I had to re-run easy_install for ipython to recognize the modules.

If you are running it from command line, sometimes python interpreter is not aware of the path where to look for modules.

Below is the directory structure of my project:

/project/apps/..
/project/tests/..

I was running below command:

>> cd project
>> python tests/my_test.py

After running above command i got below error

no module named lib

lib was imported in my_test.py

i printed sys.path and figured out that path of project i am working on is not available in sys.path list

i added below code at the start of my script my_test.py .

import sys
import os
module_path = os.path.abspath(os.getcwd())    
if module_path not in sys.path:       
    sys.path.append(module_path)

I am not sure if it is a good way of solving it but yeah it did work for me.

This will work if you always run the script from the same location. Otherwise, you'll run into problems since os.getcwd() gets the directory where the script was run, not the directory where the script file lives. – Nathan Arthur Jun 24, 2019 at 10:37

This kind of errors occurs most probably due to python version conflicts. For example, if your application runs only on python 3 and you got python 2 as well, then it's better to specify which version to use. For example use

python3 .....

instead of

python

This problem occurs due to the different versioning - e.g. if the Python installed on your machine is installed in a folder called path_to_lib/python3.6 but your notebook is running in Python 3 - the spacing in the naming matters!

How to solve it?

When creating a new jupyter notebook, just choose the Python with the same versioning as yours (watch out for spaces!). See the attached image.

I found yet another source of this discrepancy:

I have ipython installed both locally and in commonly in virtualenvs. My problem was that, inside a newly made virtualenv with ipython, the system ipython was picked up, which was a different version than the python and ipython in the virtualenv (a 2.7.x vs. a 3.5.x), and hilarity ensued.

I think the smart thing to do whenever installing something that will have a binary in yourvirtualenv/bin is to immediately run rehash or similar for whatever shell you are using so that the correct python/ipython gets picked up. (Gotta check if there are suitable pip post-install hooks...)

  • Open Spyder -> Tools -> PYTHONPATH manager
  • Add Python paths by clicking "Add Path". E.g: 'C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages'
  • Click "Synchronize..." to allow other programs (e.g. Jupyter Notebook) use the pythonpaths set in step 2.
  • Restart Jupyter if it is open
  • This is probably caused by different python versions installed on your system, i.e. python2 or python3.

    Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x. E.g. you should see version information like below:

    pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)
    

    Then run the example.py script with below command

    $ python3 example.py
    

    Happened to me with the directory utils. I was trying to import this directory as:

    from utils import somefile
    

    utils is already a package in python. Just change your directory name to something different and it should work just fine.

    If anyone comes across this issue using conda with Jupyter Notebook in MSVS Code, the solution is to make sure you're using the correct kernel. The kernel is in a box in the top right corner of the interface and looks like this:

    I pointed mine to the version of Python that also matched my application path -- problem solved!

    This is what worked for me: I just changed my working directory inside my notebook

    import os
    os.chdir("my/path/to/module")
    os.getcwd() 
    

    I have a similar issued with my Jupyter Lab setup which I resolved by checking the Jupyter Lab log on opening. This informed me that the virtual environment (pipenv) couldn't locate the Jupyter Lab so it used a shared version (from an earlier installation of Python).

    I created a requirements.txt and discovered I hadn't installed Jupyter Lab in this new environment. Installing it resolved the import error.

    Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

    pip install pathlib
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.