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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With