当我从目录外部导入此函数时,为什么我的python import语句失败?

时间:2019-07-15 10:35:18

标签: python python-3.x python-import

简单的例子:

文件结构为:

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/(例如从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中的f1.py中移出代码可以解决此问题,但我不想这样做。

为什么会出现此错误,如何避免该错误?

1 个答案:

答案 0 :(得分:0)

定义用于查找模块的文件夹:

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

from lib.f1 import foo