且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

即使使用__init__.py,相对路径也不起作用

更新时间:2023-02-09 23:26:57

您需要更新 sys.path ,这是python查找模块的地方,而不是当前环境中系统的路径,这是 os.environ [PATH] 指的是。



示例:

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

执行此操作后,您可以在 aa 中使用您的函数,如下所示: aa.myfunc()



的版权问题解决方案:helpoverflow.com/a/6098238/775982 python:从目录导入模块


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?

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