![](/img/trans.png)
[英]Python accessing modules from package that is distributed over different directories
[英]Accessing files and modules in different directories in Python
我正在使用Python 2.7。 我有以下目錄結構:
alogos
- resources
- __init__.py
- test.py
- lib
- __init__.py
- utils.py
- common
- config
- config.json
我的utils.py是以下內容:
def read_json_data(filename):
with open(filename) as data:
json_data=json.load(data)
return json_data
我的test.py
具有以下內容:
from lib.utils import read_json_data
running_data = read_json_data('common/config/config.json')
print running_data
當我嘗試從resources
目錄運行python test.py
,出現以下錯誤:
ImportError: No module named lib.utils
什么是訪問文件和模塊的正確方法
您的lib.utils
模塊不在當前目錄中(並且顯然不在其他任何位置的import
檢查),因此import
失敗。
Python文檔詳細介紹了模塊搜索路徑:
導入名為spam的模塊時,解釋器首先搜索具有該名稱的內置模塊。 如果找不到,它將在變量sys.path給出的目錄列表中搜索名為spam.py的文件。 sys.path從以下位置初始化:
* the directory containing the input script (or the current directory). * PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). * the installation-dependent default.
初始化后,Python程序可以修改sys.path。 包含正在運行的腳本的目錄位於搜索路徑的開始,在標准庫路徑之前。 這意味着將加載該目錄中的腳本,而不是庫目錄中相同名稱的模塊。 除非打算進行更換,否則這是一個錯誤。 有關更多信息,請參見標准模塊部分。
雖然這當然不是唯一的方法,但我要做的是將lib.utils
模塊作為一個單獨的模塊存儲在本地Pypi服務器中( Artifactory是一個示例,但還有其他示例,例如devpi ),可以像其他任何模塊一樣安裝它,只需從常規Pypi使用不同的索引URL。 這樣,您的任何腳本都可以像使用其他模塊一樣使用它,並且消除了玩各種與路徑相關的游戲的需要,這些游戲可能會增加不必要的復雜性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.