2009-06-29 15 views

回答

14

添加全局的說法對我來說就足夠了:

__import__('messages_en', globals=globals()) 

事實上,只有__name__是需要在這裏:

__import__('messages_en', globals={"__name__": __name__}) 
14

__import__是的只是另一種方式由import語句調用的內部函數。在日常的編碼,你並不需要(或希望)從Python文檔調用__import__

例如,聲明import spam結果字節碼類似下面的代碼:

spam = __import__('spam', globals(), locals(), [], -1) 

在另一方面,聲明from spam.ham import eggs, sausage as saus結果

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) 
eggs = _temp.eggs 
saus = _temp.sausage 

更多信息: http://docs.python.org/library/functions.html

+1

+1和感謝的解釋,但你可以描述究竟爲什麼OP的例子不起作用?他似乎試圖將messages_en別名爲消息,這似乎(對我來說天真)是合理的。 – 2009-06-29 11:54:02

+0

由於'wr'解釋它是由於級別造成的,我知道__import__不應該經常使用,但在這種情況下,我必須從配置文件動態讀取語言附加到消息並導入該文件 – 2009-06-29 12:55:07

+0

此示例非常有用,特別是如果你想從子目錄加載模塊。它幫助我修復了「找不到屬性」錯誤。 – Carlos 2012-10-18 15:46:05

19

如果這是一個路徑問題,您應該使用level參數(從docs):

__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module 

Level is used to determine whether to perform 
absolute or relative imports. -1 is the original strategy of attempting 
both absolute and relative imports, 0 is absolute, a positive number 
is the number of parent directories to search relative to the current module. 
0

你可以試試這個:

messages == __import__('Foo.messages_en', fromlist=['messages_en']) 
3

一定要追加modules目錄到你的Python路徑。

您的路徑(Python通過搜索模塊和文件的目錄列表)存儲在sys模塊的路徑屬性中。由於路徑是一個列表,所以可以使用append方法將新目錄添加到路徑中。

例如,在目錄/ home/ME/mypy添加到路徑:

import sys 
sys.path.append("/home/me/mypy") 
0

您需要手動導入動態包路徑的頂部包。

例如,在文件的開頭我寫:

import sites 

後來在這個代碼工作對我來說:

target = 'some.dynamic.path' 
my_module = __import__ ('sites.%s.fabfile' % target, fromlist=["sites.%s" % target]) 
相關問題