Why doesn't an import in an exec in a function work?

前端 未结 3 934

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)
         


        
3条回答
  •  一个人的身影
    2020-12-03 03:15

    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.

提交回复
热议问题