Skip to main content
 首页 » 编程设计

python之导入驻留在不相关路径中的文件

2025年05月04日8lonelyxmas

假设我有一个名为 root 的目录,它有两个目录:x 和 y。我有一个驻留在 x 中的模块文件,让我们称之为 test.py。现在在 y 中,我有一个模块需要调用 test.py

我正在做一个简单的:

从 x 导入测试

而且它有效。我想知道,这是如何工作的?

编辑:它是如何工作的,因为 x 中没有 __init__.py 文件,但是从 y 我能够从那里调用一个模块。

请您参考如下方法:

事实并非如此。您,或者您的操作系统,或者您的 Python 站点启动脚本,已经修改了 PYTHONPATH。

14:59 jsmith@upsidedown pwd 
/Users/jsmith/Test/Test2/root 
 
14:59 jsmith@upsidedown cat x/test.py 
def hello(): 
  print "hello" 
 
14:59 jsmith@upsidedown cat y/real.py 
#!/usr/bin/python 
from x import test 
test.hello() 
 
14:59 jsmith@upsidedown y/real.py 
Traceback (most recent call last): 
  File "y/real.py", line 3, in <module> 
    from x import test 
ImportError: No module named x