[英]Why does 'from file import function_name' fail in my interactive Python session but works in a script?
[英]Why does my python import statement fail when I import this function from outside the directory?
簡單的例子:
文件結構為:
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
。
現在,在test/lib/
加載f1.py
可以正常工作:
$ 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
中的f2.py
中f1.py
解決此問題,但是我不想這樣做。
為什么會出現此錯誤,如何避免該錯誤?
定義用於查找模塊的文件夾:
import sys
sys.path.append('test')
from lib.f1 import foo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.