2010-06-23 31 views

回答

6
>>> m = __import__('xml.sax') 
>>> m.__name__ 
'xml' 
>>> m = __import__('xml.sax', fromlist=['']) 
>>> m.__name__ 
'xml.sax' 
3

您可以使用內置的__import__函數。例如:

import sys 

myconfigfile = sys.argv[1] 

try: 
    config = __import__(myconfigfile) 
    for i in config.__dict__: 
     print i    
except ImportError: 
    print "Unable to import configuration file %s" % (myconfigfile,) 

欲瞭解更多信息,請參見:

+0

使用'fromlist'參數,否則你得到'a'而不是'abmodule' http://stackoverflow.com/questions/3102252/python-how-to-import-a-module-if-i-have-其路徑爲字符串/ 3102318#3102318 – jfs 2010-06-23 14:05:26

0
x = __import__('a.b.module', fromlist=['']) 

Reference

+0

>>> n = __ import __('mobius.api') >>> n >>> >>>爲我在正.__ dict__: ...打印我 ... 設置 __builtins__ 文檔 __file__ 投票 __PACKAGE__ __path__ api video __name__ __doc__ ccb >>> 爲什麼mobius獲取導入而不是mobius.api? – Nullpoet 2010-06-23 14:12:47

+0

請參閱下面的註釋以獲取答案。現在更新我的答案。 – huntaub 2010-06-23 14:15:33

相關問題