2013-04-18 95 views
0

我想爲用戶提供一個python腳本,可以爲它們導入一些模塊,然後通過導入的模塊下載到python解釋器。我有一些代碼,我想可能會奏效,但它似乎並不:全局導入模塊

module_list = ['module_a','module_b'] 

# Import our common modules 
for module in module_list: 
try: 
    print "Importing: {0}".format(module) 
    exec("import {0}".format(module)) 
except: 
    print "FYI we failed importing {0}. It will not be available for you to use".format(module)    

所以當腳本完成,將下降到Python模塊,用戶可以做到:

>>> module_a.run() 
+3

你有沒有考慮過使用IPython的殼呢?它更加舒適,它確實支持嵌入。 – ThiefMaster 2013-04-18 06:18:23

回答

0

反對很多評論的建議我已經閱讀了觸摸__main__,我做到了。

所以這裏是最終爲我工作的代碼:

module_list = ['module_a','module_b'] 

# Import our modules 
for name in module_list: 
    try: 
     __import__(name) 
     if name in sys.modules: 
      setattr(__main__, name, sys.modules[name]) 
    except: 
     print "FYI we failed importing {0}. It will not be available for you to use".format(name) 
1

您可以使用code.InteractiveConsole()並傳遞一個locals字典,其中包含控制檯將運行的本地上下文。通過將模塊存儲在那裏,您可以輕鬆地將它們提供給交互式外殼。

0

我不會這麼做,如果我是你..但

import imp 

module_list = ['module_a','module_b'] 

for name in module_list: 
    try: 
     module_info = imp.find_module(name) 
     globals()[name] = imp.load_module(name, *module_info) 
    except: 
     "Import error: %s" %name 

保存上面的代碼文件,例如imptest.py-i開關加載它,因爲

python -i imptest.py 
+0

不需要'imp'。只需使用內建['__import__'](http://docs.python.org/2/library/functions.html#__import__)函數。 'globals()[name] = __import __(name)' – halex 2013-04-18 06:31:48

+0

問題是在python提示符下導入的模塊不可用這種方式。 – Plazgoth 2013-04-20 05:57:36