1

我正在尝试在 python 中构建一种脚本系统,允许在运行时在 python 中选择和执行小片段代码。

本质上我希望能够加载一个小的python文件,比如

for i in Foo: #not in a function.
    print i

我在程序的其他地方指定 Foo 将是什么。好像 Foo 充当整个加载的 python 文件的函数参数,而不是单个函数

所以在别的地方

FooToPass = GetAFoo ()
TempModule = __import__ ("TheSnippit",<Somehow put {'Foo' : FooToPass} in the locals>)
4

1 回答 1

2

It is considered bad style to have code with side effects at module level. If you want your module to do something, put that code in a function, make Foo a parameter of this function and call it with the desired value.

Python's import mechanism does not allow to preinitialise a module namespace. If you want to do this anyway (which is, in my opinion, confusing and unnecessary), you have to fiddle around with details of the import mechanism. Example implementation (untested):

import imp
import sys

def my_import(module_name, globals):
    if module_name in sys.modules:
        return sys.modules[module_name]
    module = imp.new_module(module_name)
    vars(module).update(globals)
    f, module.__file__, options = imp.find_module(module_name)
    exec f.read() in vars(module)
    f.close()
    sys.modules[module_name] = module
    return module
于 2012-07-03T15:24:19.927 回答