在模块中运行的 Python 可执行文件可以工作,但在函数中不起作用



这有效:

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

有人可以告诉我为什么以及如何修复它吗?

我又一次阅读 - 习惯 - python的文档,尤其是这个文档:

请记住,在模块级别,全球和当地人是相同的字典

尝试一下:

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

现在有效!

我仍然不知道为什么,但是现在至少有效。

最新更新