![](/img/trans.png)
[英]Best way to import python module at the root of a package hierarchy from another module in the same package
[英]How to import a module from the root dir having another with same name in a descendent package?
我正在使用python 2.7.10。
我了解與此相關的問題很多。 我開始這個問題是因為在StackOverflow中找不到答案可以解決我的疑問。 我的目標是在社區的幫助下闡明我對Python導入機制的理解。
我有一個結構如下的項目:
./
./config.py
./modules
./modules/__init__.py
./modules/config.py
config.py
VALUE = 1
模塊/ config.py
import config
print(config.VALUE)
在此模塊中,我想從模塊的根目錄中獲取VALUE常量並進行打印。 當我在模塊包中運行配置時,出現以下錯誤:
$ python modules/config.py
Traceback (most recent call last):
File "modules/config.py", line 1, in <module>
import config
File "/test/modules/config.py", line 2, in <module>
print(config.VALUE)
AttributeError: 'module' object has no attribute 'VALUE'
我知道import config語句將模塊導入當前目錄中,而不是根目錄中。 因此,我需要添加一種技巧,以允許其將模塊導入根目錄:
模塊/ config.py
def import_from_root(name):
import os
import imp
root_path = os.path.dirname(os.path.abspath(__name__))
root_module = os.path.join(root_path, '{}.py'.format(name))
return imp.load_source('root_'.format(name), root_module)
print(import_from_root('config').VALUE)
現在可以正常工作:
$ python modules/config.py
1
但是我想知道這是否是最好的方法。 因此,我有以下問題:
請考慮我不想更改目錄結構或模塊名稱。
如果您想更改當前工作目錄而不是sys路徑,則此方法有效:
from os import chdir
chdir('/')
import config
如果您在根目錄中有其他資源,則可能會更好。 與當前解決方案相比,此解決方案和上述解決方案都更加簡約和Pythonic。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.