2017-05-15 101 views
0

我遇到了一個很奇怪的問題:進口蟒蛇文件失敗

我的文件結構是這樣的:(核心和測試是目錄)

core 
    ----file1.py 

    ----__init__.py 

test 

    ----file2.py 

file2中,我寫道:

from core import file1 

結果是:

ImportError: cannot import name file1 
+0

你有沒有嘗試過從'..core import file1'這樣的相對導入? –

回答

2

必須在測試目錄中創建__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

+0

對不起。試過,但失敗了。仍然是ImportError – wjxiz

+0

更新了問題的詳細信息。 –

0

當我想你的情況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__),'../')是將路徑狀況來​​。

1

這不是一個奇怪的問題,進口根本就不行。

從官方文檔: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一樣添加corePYTHONPATH。 L說。

+0

嘿,謝謝你。我在「core」裏面有一個名爲「core-2」的目錄,core-2裏的python文件可以成功導入file1(file1在'core'中)。根據tuto,它不應該能夠做到這一點。我誤解了某個地方? – wjxiz

+0

這聽起來像它會工作是的......真相被告知,我也不確定。也許我發佈的第二個鏈接可能有幫助,我認爲它解決了這個問題。 – Oersted