如何通过在 Python3 函数中执行文本文件行来实例化全局变量?

How to instantiate global variables by executing a text file lines within a Python3 function?

我想使用 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 文件等