在Python中,为什么函数中的exec不会导入? [英] In Python, why doesn't an import in an exec in a function work?

查看:132
本文介绍了在Python中,为什么函数中的exec不会导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 我可以在一个字符串中放入一个import语句,exec它,并且它可以工作(打印一个随机数字) code =
import random
def f():
print random.randint(0,9)


def f ():
传递

执行代码
f()

现在,如果我将执行代码 f()放在它们自己的函数中并调用它,它就不会()

  def test():
执行代码
f()

test()

它表示 NameError:全局名称'random'未定义
任何想法发生了什么?
Thanks $ / $>

解决方案

如何操作:

<$ p $ (),
f()


I can put an import statement in a string, exec it, and it works (prints a random digit):

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

def f():
    pass

exec code
f()

Now, if I put exec code and f() in their own function and call it, it doesn't work.

def test():
    exec code
    f()

test()

It says NameError: global name 'random' is not defined. Any idea what's going on? Thanks

解决方案

How about this:

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

这篇关于在Python中,为什么函数中的exec不会导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆