Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: No module named - Python

Tags:

python

import

I have a python application with the following directory structure:

src  |  +---- main  |  +---- util  |  +---- gen_py          |          +---- lib 

In the package main, I have a python module named MyServer.py which has an import statement like:

from gen_py.lib import MyService 

In order for this statement to work, I placed the following line at the beginning of MyServer.py:

import sys sys.path.append('../gen_py/lib') 

When I run MyServer.py in the terminal, I get the following error:

ImportError: No module named gen_py.lib

What I am missing here?

like image 589
F. Aydemir Avatar asked Sep 28 '11 17:09

F. Aydemir


People also ask

How do I fix the ImportError No module named error in Python?

To get rid of this error “ImportError: No module named”, you just need to create __init__.py in the appropriate directory and everything will work fine.

What is ImportError in Python?

ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised. If a module does not exist.


1 Answers

Your modification of sys.path assumes the current working directory is always in main/. This is not the case. Instead, just add the parent directory to sys.path:

import sys import os.path  sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import gen_py.lib 

Don't forget to include a file __init__.py in gen_py and lib - otherwise, they won't be recognized as Python modules.

like image 150
phihag Avatar answered Sep 28 '22 10:09

phihag