为什么在函数中的exec中不导入?

问题描述 投票:25回答:3

我可以将导入语句放入字符串中,执行它,然后它可以工作(打印随机数字):

code = """
import random
def f():
    print random.randint(0,9)
"""

def f():
    pass

exec code
f()

现在,如果我将exec codef()放在自己的函数中并调用它,它将不起作用。

def test():
    exec code
    f()

test()

它说NameError: global name 'random' is not defined

python function import exec
3个回答
19
投票

怎么样:

def test():
    exec (code, globals())
    f()

19
投票

这里发生的事情是,在测试中将模块random作为局部变量导入。试试这个

def test():
    exec code
    print globals()
    print locals()
    f()

将打印

{'code': '\nimport random\ndef f():\n    print random.randint(0,9)\n', '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'test': <function test at 0x02958BF0>, '__name__': '__main__', '__doc__': None}
{'random': <module 'random' from 'C:\Python27\lib\random.pyc'>, 'f': <function f at 0x0295A070>}

f看不到random的原因是f不是test内的嵌套函数-如果您这样做的话:

def test():
    import random
    def f():
        print random.randint(0,9)
    f()

可以。但是,嵌套函数要求在编译外部函数时外部函数包含内部函数的定义-这是因为您需要设置单元变量来保存两个(外部和内部)函数之间共享的变量。

要随机进入全局名称空间,您只需执行以下操作

exec code in globals(),globals()

in关键字后exec的参数是在其中执行代码的全局和本地名称空间(因此,在exec的代码中定义名称的存储位置。)>]


3
投票

指定您要使用全局random模块

© www.soinside.com 2019 - 2024. All rights reserved.