Python3-在函数内调用 exec(open().read()) 时出现问题
Python3-Issue with calling exec(open().read()) inside a function
我在 运行 在 python 脚本中设置 python 脚本时遇到问题,我根本不明白:
假设我们在同一目录中有 2 个文件:'init.py' 和 'text.py'
init.py:
X = 5
print("init.py was run")
test.py:
exec(open("./init.py").read())
print("X = %s" %X)
如果我 运行 test.py 现在,我得到
init.py was run
X = 5
但是,如果我将 test.py 更改为:
def func_call( filename):
exec(open(filename).read())
print("X = %s" %X)
func_call("./init.py")
我得到:
init.py was run
Traceback (most recent call last):
File "test.py", line 5, in
func_call("./init.py")
File "test.py", line 3, in func_call
print("X = %s" %X)
NameError: name 'X' is not defined
有人可以向我解释为什么这会导致不同的结果吗?
有解决方法吗?
我的目标是通过 运行ning 一个 python 脚本并访问在该 python 脚本中设置的变量来初始化我的大部分变量。
If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
内部方法 globals() 和 locals() 是不同的对象:
def method():
print(globals() == locals())
exec('X=10')
print('Method execution =', X)
method()
输出:
False
NameError: name 'X' is not defined
在全局级别,这个对象是相等的:
print(globals() == locals())
exec('X=99')
print('Global exec =', X)
输出:
True
Global exec = 99
所以如果你想通过方法来做,你需要将相同的对象传递给exec。对于您的代码,它看起来像这样:
def func_call(filename):
exec(open(filename).read(), globals(), globals())
print("X = %s" %X)
func_call("./init.py")
尽管如此,正如我在评论中提到的,使用常量创建文件并将其导入。尽量避免使用 exec/eval,除非您 100% 确定自己在做什么。
我在 运行 在 python 脚本中设置 python 脚本时遇到问题,我根本不明白:
假设我们在同一目录中有 2 个文件:'init.py' 和 'text.py'
init.py:
X = 5
print("init.py was run")
test.py:
exec(open("./init.py").read())
print("X = %s" %X)
如果我 运行 test.py 现在,我得到
init.py was run
X = 5
但是,如果我将 test.py 更改为:
def func_call( filename):
exec(open(filename).read())
print("X = %s" %X)
func_call("./init.py")
我得到:
init.py was run
Traceback (most recent call last):
File "test.py", line 5, in
func_call("./init.py")
File "test.py", line 3, in func_call
print("X = %s" %X)
NameError: name 'X' is not defined
有人可以向我解释为什么这会导致不同的结果吗? 有解决方法吗? 我的目标是通过 运行ning 一个 python 脚本并访问在该 python 脚本中设置的变量来初始化我的大部分变量。
If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
内部方法 globals() 和 locals() 是不同的对象:
def method():
print(globals() == locals())
exec('X=10')
print('Method execution =', X)
method()
输出:
False
NameError: name 'X' is not defined
在全局级别,这个对象是相等的:
print(globals() == locals())
exec('X=99')
print('Global exec =', X)
输出:
True
Global exec = 99
所以如果你想通过方法来做,你需要将相同的对象传递给exec。对于您的代码,它看起来像这样:
def func_call(filename):
exec(open(filename).read(), globals(), globals())
print("X = %s" %X)
func_call("./init.py")
尽管如此,正如我在评论中提到的,使用常量创建文件并将其导入。尽量避免使用 exec/eval,除非您 100% 确定自己在做什么。