我可以将导入语句放在一个字符串中,执行它,它可以工作(打印一个随机数字):
code = """
import random
def f():
print random.randint(0,9)
"""
def f():
pass
exec code
f()
现在,如果我把 exec code
和 f()
放在它们自己的函数中并调用它,它就不起作用了。
def test():
exec code
f()
test()
它说 NameError: global name 'random' is not defined
.
最佳答案
这个怎么样:
def test():
exec (code, globals())
f()
关于python - 为什么函数中的 exec 中的导入不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12505047/