2015-03-03 27 views
2

我該怎麼辦from some.module import *其中模塊的名稱是在字符串變量中定義的?從Python模塊動態加載所有名稱

+0

你在做什麼最有可能是錯誤的...定義運行時模塊級變量。遲早你會遇到這種方法的麻煩。相反,將這些對象存儲到一個數據結構中,例如字典並對其進行處理。 – bgusach 2015-03-03 08:10:27

+0

我這樣做是爲了根據環境變量加載開發,生產和測試設置 – 2015-03-03 08:14:56

+0

這很好,但在這種情況下,您更可能想模擬'import some.module'而不是'from some.module import *'。 – 2015-03-03 08:37:35

回答

2

此代碼出口所有符號從os

import importlib 
# Load the module as `module' 
module = importlib.import_module("os") 
# Now extract the attributes into the locals() namespace, as `from .. 
# import *' would do 
if hasattr(module, "__all__"): 
    # A module can define __all__ to explicitly define which names 
    # are imported by the `.. import *' statement 
    attrs = { key: getattr(module, key) for key in module.__all__ } 
else: 
    # Otherwise, the statement imports all names that do not start with 
    # an underscore 
    attrs = { key: value for key, value in module.__dict__.items() if 
       key[0] != "_" } 
# Copy the attibutes into the locals() namespace 
locals().update(attrs) 

參見例如this question瞭解更多關於from ... import *操作背後邏輯的信息。

現在,雖然這個工程,你應該而不是使用此代碼。從命名模塊導入所有符號已經被認爲是不好的做法,但用戶給定的名稱做到這一點更糟糕。搜索PHP的register_globals如果您需要提示可能出錯的提示。

+0

這不是用戶給定的名稱,我需要根據環境變量 – 2015-03-03 08:17:29

+0

中的值加載dev,測試或prod設置文件。 ; '「os」'是一個可以是任何東西的字符串。 – 2015-03-03 09:02:59

0

在Python中,內置的導入函數完成了與使用import語句相同的目標,但它是一個實際函數,它將一個字符串作爲參數。

sys = __import__('sys') 

變量sys現在是sys模塊,就像你說過import sys一樣。

Reference