Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python';s exec在模块中运行正常,但功能不正常_Python 3.x_Function_Module_Exec - Fatal编程技术网

Python 3.x Python';s exec在模块中运行正常,但功能不正常

Python 3.x Python';s exec在模块中运行正常,但功能不正常,python-3.x,function,module,exec,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_cont

这项工作:

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
回溯(最近一次呼叫最后一次):
文件“tmp.py”,第8行,在
运行()
运行中的第6行文件“tmp.py”
执行官(脚本内容)
文件“”,第15行,在
文件“”,第16行,放置在Spitter中
名称错误:未定义名称“地点”

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

我又读了一遍,特别是这篇:

请记住,在模块级别,全局变量和局部变量是同一个字典

试试这个:

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

run()
现在可以了

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