我遇到了一個很奇怪的問題:進口蟒蛇文件失敗
我的文件結構是這樣的:(核心和測試是目錄)
core
----file1.py
----__init__.py
test
----file2.py
file2中,我寫道:
from core import file1
結果是:
ImportError: cannot import name file1
我遇到了一個很奇怪的問題:進口蟒蛇文件失敗
我的文件結構是這樣的:(核心和測試是目錄)
core
----file1.py
----__init__.py
test
----file2.py
file2中,我寫道:
from core import file1
結果是:
ImportError: cannot import name file1
必須在測試目錄中創建__init__.py
文件:
因爲需要使用__init__.py
文件來使Python將目錄視爲包含包。
parent/
child1/
__init__.py
file1.py
child2/
__init__.py
file2.py
從錯誤:
如果直接運行child2/file2.py
文件。您無法從child2/file2.py
訪問child1/file1.py
因爲只有來自父目錄才能訪問子項。
如果有一個文件夾結構,如:
parent/
child1/
__init__.py
file1.py
child2/
__init__.py
file2.py
file3.py
如果我們運行file3.py
文件。能夠訪問child1/file1.py
,child2/file2.py
中的file3.py
因爲它從父目錄運行。
如果我們需要從child2/file2.py
訪問child1/file1
,我們需要設置父目錄:
通過運行此命令之下,我們可以實現它...
PYTHONPATH=. python child2/file2.py
PYTHONPATH=.
它是指父路徑。然後運行從shell
對不起。試過,但失敗了。仍然是ImportError – wjxiz
更新了問題的詳細信息。 –
當我想你的情況child2/file2.py
文件,我得到了
Traceback (most recent call last):
File "file2.py", line 3, in <module>
from core import file1
ImportError: No module named core
的原因是,Python
沒有找到core
。在這種情況下,你需要添加core
到系統路徑,如下圖所示(以一開始添加的話):
import sys,os
sys.path.append(path_to_core.py)
或者,如果你使用命令行運行它,你可以簡單地把在
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__),'../'))
這裏開始下面,os.path.join(os.path.dirname(__file__),'../')
是將路徑狀況來。
這不是一個奇怪的問題,進口根本就不行。
從官方文檔:https://docs.python.org/3/tutorial/modules.html
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
你可以看看相對導入,這裏有一個很好的來源:https://stackoverflow.com/a/16985066/4886716
從該職位相關的信息是,有做到這一點,除非沒有什麼好辦法你像Shawn一樣添加core
到PYTHONPATH
。 L說。
你有沒有嘗試過從'..core import file1'這樣的相對導入? –