Warm tip: This article is reproduced from serverfault.com, please click

其他-更新变量Python文件中的变量值

(其他 - Update variable value in variables Python file)

发布于 2020-12-23 06:31:08

我有一个variables.py带钥匙文件TOKEN= 123456我需要在需要时动态更新该值。

文件Constants.py读为:

#!/usr/bin/env python
# encoding: utf-8
"""
variables.py
"""

TOKEN= 50

refresh_tok.py

#!/usr/bin/env python
# encoding: utf-8
"""
refresh_tok.py
"""
import variables

def refresh_token():
    print(variables.TOKEN) // previous value 50
    change_constant(variables.TOKEN, 100)
    print(variables.TOKEN) // value I am expecting is 100 but it says 50


def change_constant(match_string, replace_string):
    read_file = open("variables.py", "rt")
    read_data = read_file.read()
    read_data = read_data.replace(match_string, replace_string)
    read_file.close()
    
    write_file = open("variables.py", "wt")
    write_file.write(read_data)
    write_file.close()

我在refresh_tok.py的第二个打印语句中期望的值是100,但它仍在以前的值上,先打印50,然后再打印100。

Questioner
Zain ul Ebad
Viewed
0
juanpa.arrivillaga 2020-12-23 14:39:19

你似乎对计算机程序的本质有基本的误解。

你的change_constant函数从文件中以字符串形式读取源代码,创建一个更改该源代码的新字符串,然后将该新字符串写入同一文件。这将永远不会影响你已加载的模块。了解这一点非常重要。

相反,你需要做的是:

variables.TOKEN = new_value

当然,这只会影响运行过程。如果需要保留这些更改,则需要选择某种持久性策略,例如写入文件。为此,通常不建议使用python源代码,而应使用一些合适的序列化格式,例如JSON,pickle,类似于INI的配置文件,YAML等(或即使是非常简单的文本文件) )。