Python的exec在模块中运行但不起作用

时间:2017-12-01 11:07:45

标签: python-3.x function module exec

这有效:

import os
import sys
with open('tests.py') as fptr:
    script_content = fptr.read()
exec(script_content)

而这不是:

def run():
    import os
    import sys
    with open('tests.py') as fptr:
        script_content = fptr.read()
    exec(script_content)

run()

结果:

Traceback (most recent call last):
  File "tmp.py", line 8, in <module>
    run()
  File "tmp.py", line 6, in run
    exec(script_content)
  File "<string>", line 15, in <module>
  File "<string>", line 16, in PlaceSpitter
NameError: name 'Place' is not defined

有谁可以告诉我为什么以及如何解决它?

1 个答案:

答案 0 :(得分:1)

我再次阅读 - carrefully - python's docs尤其是这个:

  

请记住,在模块级别,全局变量和本地变量是相同的字典

试试这个:

def run():
    import os
    import sys
    with open('tests.py') as fptr:
        script_content = fptr.read()
    exec(script_content, globals())

run()

现在有效!

我仍然不知道为什么,但现在至少它起作用了。