[英]python package import from different directory
我有以下目錄結構:
\something\python\
extras\
__init__.py # empty file
decorators.py # contains a benchmark decorator (and other things)
20131029\ # not a package, this contains the scripts i use directly by doing "python somethingelse.py"
somethingelse.py
現在我希望能夠做類似的事情
from .extras import decorators
from decorators import benchmark
從somethingelse.py內部
為此,我需要在哪里放置__init__.py
文件(目前,“ \\ something \\ python \\”路徑已添加到我的.tchsrc中)
現在,我得到以下錯誤:
from .extras import decorators
ValueError: Attempted relative import in non-package
將其添加到我的pythonpath中是否有問題? 還是應該解決這個問題? 我當前的解決方法是僅將decorators.py復制粘貼到我創建的每個新目錄中(如果我創建代碼的新版本,例如“ 20131029”),但這只是一個愚蠢的解決方法,這意味着我必須復制粘貼每次我制作代碼的新版本時都會有很多東西,因此我想要一個帶有正確導入的更優雅的版本。
注意:我正在python 2.7中工作,是否有什么區別?
編輯:是的,我通過運行它
python somethingelse.py
更多編輯:不知道定義基准裝飾器的方式是否重要? (這不是一個類,所以接下來的事情完全來自decorators.py文件)
import time, functools
def benchmark(func):
"""
A decorator that prints the time a function takes
to execute.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
t = time.time()
res = func(*args, **kwargs)
print func.__name__, time.time()-t
return res
return wrapper
編輯:如果我把\\ something \\ python \\ extras \\放到我的pythonpath中,我得到
ImportError: No module named decorators
當我跑步時:
from decorators import benchmark
這是否意味着我需要在該Extras目錄中創建另一個子目錄,而不是將decorators.py放在其中?
編輯:.tchsrc中,我添加了以下行:
setenv PYTHONPATH /bla/blabla/something/python/extras/
並在somethingelse.py中,如果我運行以下命令:
import sys
s = sys.path
for k in s:
print k
我發現路徑/ bla / blabla / something / python / extras /在該列表中,所以我不明白為什么它不起作用?
您的20131029
目錄不是軟件包,因此您不能使用超出其的相對導入路徑。
您可以使用當前腳本中的相對路徑,將extras
目錄添加到Python模塊搜索路徑中:
import sys, os
here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.normpath(os.path.join(here, '../extras')))
現在,導入首先在extras
目錄中查找模塊,因此請使用:
import decorators
因為您的目錄名稱本身僅使用數字,所以無論如何您都不能將其打包。 軟件包名稱必須遵循Python標識符規則,該規則不能以數字開頭。 即使您重命名目錄並添加了__init__.py
文件,當您在目錄中以腳本方式運行文件時,仍然不能將其作為包使用。 腳本始終被視為位於程序包之外。 您必須有一個頂級“ shim”腳本,該腳本從包中導入真實代碼:
from package_20131029.somethingelse import main
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.