首页 > 解决方案 > 当我从目录外导入此函数时,为什么我的 python 导入语句会失败?

问题描述

简单的例子:

文件结构为:

test/lib/f1.py
test/lib/f2.py

文件内容:

$ cat lib/f1.py 
from f2 import bar

def foo(a):
  print(1+bar(a))

$ cat lib/f2.py                                                                                                   
def bar(a):
  return a

所以f1.py定义foo,它依赖于bar,定义在f2.py.

f1.py现在,在里面加载就可以了test/lib/

$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from f1 import foo
>>> foo(1)
2

但是,当从外部加载时test/lib/(比如 from test/),这会失败并出现导入错误:

$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib.f1 import foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/pymod/lib/f1.py", line 1, in <module>
    from f2 import bar
ImportError: No module named 'f2'
>>> Quit (core dumped)

f2.py从in移动代码可以f1.py解决问题,但我不想这样做。

为什么我会收到此错误,我该如何避免?

标签: pythonpython-3.xpython-import

解决方案


定义应在其中查找模块的文件夹:

import sys
sys.path.append('test')

from lib.f1 import foo

推荐阅读