In Python, why doesn't an import in an exec in

2019-01-18 03:00发布

问题:

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

回答1:

How about this:

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


回答2:

What's going on here is that the module random is being imported as a local variable in test. Try this

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

will print

{'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>}

The reason f can't see random is that f is not a nested function inside of test--if you did this:

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

it would work. However, nested functions require that the outer function contains the definition of the inner function when the outer function is compiled--this is because you need to set up cell variables to hold variables that are shared between the two (outer and inner) functions.

To get random into the global namespace, you would just do something like this

exec code in globals(),globals()

The arguments to exec after the in keyword are the global and local namespaces in which the code is executed (and thus, where name's defined in the exec'd code are stored).



回答3:

Specify that you want the global random module

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

The problem here is that you're importing the random module into your function scope, not the global scope.