[英]Can't get Python to import from a different folder
我似乎無法讓Python在子文件夾中導入模塊。 當我嘗試從導入的模塊創建類的實例時,我收到錯誤,但導入本身成功。 這是我的目錄結構:
Server
-server.py
-Models
--user.py
這是server.py的內容:
from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
和user.py:
class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
錯誤是:AttributeError:'module'對象沒有屬性'User'
我相信你需要在Models目錄中創建一個名為__init__.py
的文件,以便python將其視為一個模塊。
然后你可以這樣做:
from Models.user import User
您可以在__init__.py
包含代碼(例如,幾個不同類需要的初始化代碼)或將其留空。 但它一定存在。
導入用戶
u = user.User()#error在這一行
由於缺少上面提到的__init__,你會發現一個ImportError可以使問題更加清晰。
你沒有得到一個,因為'user'也是標准庫中的現有模塊。 你的import語句抓住那個並嘗試在其中找到User類; 那是不存在的,只有這樣才能得到錯誤。
通常一個絕對的導入是一個好主意:
import Server.Models.user
避免這種模棱兩可。 事實上,從Python 2.7'導入用戶'看起來根本不會與當前模塊相關。
如果你真的想要相對導入,你可以在Python 2.5中使用稍微丑陋的語法顯式地使用它們:
from .user import User
當您沒有標准包結構時,導入位於父文件夾的模塊的正確方法是:
import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
(您可以合並最后兩行,但這種方式更容易理解)。
該解決方案是跨平台的,並且通用性足以在其他情況下不需要修改。
你錯過了__init__.py。 從Python教程:
需要__init__.py文件才能使Python將目錄視為包含包; 這樣做是為了防止具有通用名稱的目錄(例如字符串)無意中隱藏稍后在模塊搜索路徑上發生的有效模塊。 在最簡單的情況下,__ init__.py可以只是一個空文件,但它也可以執行包的初始化代碼或設置__all__變量,稍后描述。
將名為__init__.py的空文件放在Models目錄中,所有文件都應該是黃金的。
你怎么寫出os.path.dirname
....命令的參數?
import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
我首選的方法是在包含其他模塊使用的模塊的每個目錄上都有__init__.py,並在入口點覆蓋sys.path,如下所示:
def get_path(ss):
return os.path.join(os.path.dirname(__file__), ss)
sys.path += [
get_path('Server'),
get_path('Models')
]
這使得指定目錄中的文件可供導入,我可以從Server.py導入用戶。
在完成上述貢獻者給出的答案后 - Zorglub29,Tom,Mark,Aaron McMillin,lucasamaral,JoeyZhao,Kjeld Flarup,Procyclinsur,martin.zaenker,tooty44以及調試我面臨的問題我發現了一個不同的用例到期我面對這個問題。 因此,在下面添加我的觀察結果供任何人參考。
在我的代碼中,我循環導入了類。 例如:
src
|-- utilities.py (has Utilities class that uses Event class)
|-- consume_utilities.py (has Event class that uses Utilities class)
|-- tests
|-- test_consume_utilities.py (executes test cases that involves Event class)
當我嘗試執行python -m pytest tests / test_utilities.py來執行用test_utilities.py編寫的UT時出現以下錯誤。
ImportError while importing test module '/Users/.../src/tests/test_utilities.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_utilities.py:1: in <module>
from utilities import Utilities
...
...
E ImportError: cannot import name 'Utilities'
我解決錯誤的方法是重新分解我的代碼以在循環導入類中移動功能,以便我可以刪除類的循環導入。
注意,我的' src '文件夾中有__init__.py
文件以及' tests '文件夾,只能通過重新分解代碼來擺脫' ImportError '。
stackoverflow鏈接之后提供了有關Python中循環依賴的更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.