我想使用Python函数将变量实例化为my_var
默认值。接下来,我要使用以下input.txt
文本文件来修改的值my_var
:
my_var = 0.15 # Change the value
print(f"In the text file, my_var={my_var}")
my_var = 0.15; print(f"In the same line, my_var={my_var}")
这是Python脚本,用于读取文本文件中的行并逐行执行:
def run_exec():
my_var = 1.0 # Default value
f = open("input.txt")
lines = f.readlines()
for l in lines:
exec(l)
print(f"Within the function, my_var={my_var}")
return my_var
my_var = run_exec()
print(f"Outside the function, my_var={my_var}")
在终端中运行此脚本时,我得到:
At the beginning, my_var=1.0
In the text file, my_var=1.0
In the same line, my_var=0.15
Within the function, my_var=1.0
Outside the function, my_var=1.0
看起来每个执行的文本行都有其自己的作用域...我如何才能my_var=0.15
超出函数范围?
是的,每次调用代码exec()
都会在其自己的范围内运行。不可能直接影响中的函数的局部变量exec()
,但是您可以传递字典以exec()
用作在函数中创建的新局部变量的容器:
def run_exec():
local_dict = {} # container for local variables in exec()
my_var = 1.0 # Default value
with open("input.txt") as f:
for line in f:
exec(line, globals(), local_dict)
# local variable unchanged
print(f"Within the function, {my_var=}")
my_var = local_dict.get('my_var', my_var) # defaults to my_var
print(f"Within the function {my_var=} after explicit assignment")
return my_var
my_var = run_exec()
print(f"Outside the function, my_var={my_var}")
输出
In the text file, my_var=0.15
In the same line, my_var=0.15
Within the function, my_var=1.0
Within the function my_var=0.15 after explicit assignment
Outside the function, my_var=0.15
当然,您永远不要这样做,因为执行不受信任的代码极其危险,例如,如果文件包含以下内容:
exec('import os; os.remove("some_important_file")')
除此之外,还有更好的方法来执行此操作,例如配置文件,使用所需变量导入模块,JSON文件等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句