Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - relative path not working even with __init__.py

I know that there are plenty of similar questions on stack overflow. But the common answer doesn't seem to be working for me.

I have a file structure like this

  proj/
       lib/
          __init__.py
          aa.py
          bb.py
          test/
               __init__.py
               aa_test.py

I figured that if I include the code in my test.py

import lib.aa

or

from lib import aa

I would be able to reference the modules in the lib/ directory. But that did not work.

So I tried to add to path, and it adds it correctly:

os.environ["PATH"] += ":%s" % os.path.abspath(os.path.join("..",""))
print os.environ["PATH"]

but even now when I try the import statements above... I keep getting the error

ImportError: No module named aa

or

ImportError: Importing from non-package <Something...>

Is there something obvious I am missing?

Is there a way to check if I have configured my __init__.py files correctly, or to see my package hierarchy?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to update your sys.path, which is where python looks for modules, as opposed to your system's path in the current environment, which is what os.environ["PATH"] is referring to.

Example:

import os, sys
sys.path.insert(0, os.path.abspath(".."))
import aa

After doing this, you can use your functions in aa like this: aa.myfunc()

There's some more information in the accepted answer for python: import a module from a directory


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...