Python导入相对模块

0 投票
3 回答
745 浏览
提问于 2025-04-15 12:21

我在同一个文件夹里有两个Python文件,分别是a.py和b.py。现在我想从a.py中引入b.py,但a.py可能是从其他文件夹导入的,或者直接运行的。因为这个模块会被分发出去,所以我不能写死一个固定的路径。

我试着用了一些方法,比如__file__、sys.path和os.chdir,但感觉有点乱。而且__file__并不是总能用。

3 个回答

1

使用 inspect 模块可以让内置模块变得更加明显:

>>> import os
>>> import sys
>>> inspect.getfile(os)
'/usr/local/lib/python2.6/os.pyc'
>>> inspect.getfile(sys)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/inspect.py", line 407, in getfile
    raise TypeError('arg is a built-in module')
TypeError: arg is a built-in module
6

其实,__file__这个东西在导入的模块中是可以用的,但前提是这个模块是从一个 .py 或 .pyc 文件导入的。如果这个模块是内置的,那就用不了。比如说:

>>> import sys, os
>>> hasattr(os, '__file__')
True
>>> hasattr(sys, '__file__')
False
-1

把包含这两个文件的文件夹放到你的Python路径里……或者反过来也可以。

撰写回答