全局导入模块

时间:2013-04-18 06:10:55

标签: python import

我想为用户提供一个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 个答案:

答案 0 :(得分:1)

您可以使用code.InteractiveConsole()并传递包含控制台将运行的本地上下文的locals字典。通过将模块存储在那里,您可以轻松地将它们提供给交互式shell。

答案 1 :(得分: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

答案 2 :(得分: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)