我嘗試了一些不同的技術,試圖做一些對我來說似乎可行的,但我想我缺少一些關於python的疑難解答(使用2.7,但也希望這樣做也爲3。如果可能的話)。Python中模塊的相對路徑
我不確定像包或模塊這樣的術語,但對我來說,下面看起來相當「簡單」可行的場景。
這是目錄結構:
.
├── job
│ └── the_script.py
└── modules
├── __init__.py
└── print_module.py
的the_script.py
內容:
# this does not work
import importlib
print_module = importlib.import_module('.print_module', '..modules')
# this also does not work
from ..modules import print_module
print_module.do_stuff()
的print_module
內容:
def do_stuff():
print("This should be in stdout")
我想運行這些「相對路徑「的東西爲:
/job$ python2 the_script.py
但importlib.import_module
給出各種錯誤:
- 如果我只使用1個輸入參數
..modules.print_module
,然後我得到:TypeError("relative imports require the 'package' argument")
- 如果使用2個輸入參數(如在上面的例子中),然後我得到:
ValueError: Empty module name
在使用from ..modules
語法我得到的另一方面:ValueError: Attempted relative import in non-package
。
我認爲__init__.py
空文件應該足以將代碼限定爲「包」(或模塊?不確定術語),但似乎我缺少有關如何管理相對路徑的信息。
我看,在過去的人被盜號這個利用import os
和import sys
的path
等功能,但根據官方文檔(Python 2.7版和3 *)這不應該不再需要。
我在做什麼錯,我怎麼能達到打印內容的效果modules/print_module.do_stuff
從「相對目錄」中的腳本調用它job/
?
爲什麼你會在這裏使用importlib?爲什麼不直接導入? –
'__init __。py'只爲它所在的目錄創建一個包。你需要在顯示的樹中的所有目錄中添加__init __。py。您還需要確保包含頂級軟件包目錄的目錄位於'sys.path'上,並且如果您希望能夠將其中一個文件作爲腳本執行,則需要考慮這些問題描述[這裏](http://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-im-port-in-non-package-even-with-init-py)和[這裏](http: //stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time)。 – BrenBarn