Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

import - ImportError: No module named - Python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...