Python如何即时更改变量的值
现在,我正在处理具有以下信息的.txt文件:
Right now i am working with a file .txt with this information:
["corrector", "Enabled"]
["Inteligencia", "Enabled"]
然后在我的python程序中,它以这种方式从一开始就加载该数据:
Then in my python program it loads that data at the very beggining, this way:
for line in open("menu.txt", 'r'):
retrieved = json.loads(line)
if retrieved[0] == "corrector":
corrector = retrieved[1]
if retrieved[0] == "Inteligencia":
Inteligencia = retrieved[1]
到目前为止,它的工作原理是完美的,但是因为它是针对聊天机器人的,所以我希望可以直接从聊天中更改该变量的值,并且当我从聊天室中调用!启用校正器"时,我尝试了此代码聊天.
So far it works perfect, however as this is for a chat bot, i want to make possible to change the value of that variables directly from the chat, and i tried this code when i call "!Enable corrector" from the chat.
if corrector == "Enabled":
room.message("ERROR: Already Enabled")
else:
data = []
with open('menu.txt', 'r+') as f:
for line in f:
data_line = json.loads(line)
if data_line[0] == "corrector":
data_line[1] = "Enabled"
data.append(data_line)
f.seek(0)
f.writelines(["%s\n" % json.dumps(i) for i in data])
f.truncate()
room.message("corrector enabled")
这也有效,如果我打开.txt文件,我可以看到它已经更改的值.真正的问题是python似乎并未接受我更改了变量,并且它仍然认为它已启用",而仍被禁用".直到我重新启动程序,它才会将变量读取为已启用".
That also works, and if i open the .txt file i can see the value it's already changed. The real problem is that python didn't seem to accept that i changed a variable, and it still thinks it's "disabled" while it's already "enabled". It won't read the variable as "enabled" until i restart the program.
我想知道是否有用于变量的刷新选项或一种变通方法,可以随时更改变量的值并保持效果而无需重新启动.
I was wondering if there is a refresh option for variables or a workaround to change the value of a variables on the fly and make the effect lasts without a restart.
随时更改变量的值
change the value of a variables on the fly
此代码可随时更改变量的值:
This code changes the value of a variable on the fly:
a = 1
a = 2
您的问题建议您希望能够通过计算出的名称查找值.解决方法是使用dict
:
Your question suggests that you want to be able to look up a value by a calculated name. The solution is to use a dict
:
mydict = {'corrector':0}
mydict['corrector'] = 1
如果要更改文件中的值,则需要根据所拥有的数据写出新文件.看来您正在加载json,所以json
模块将帮助您解决这一问题.
If you want to change the values in the file, you'll need to write out a new file based on the data you have. It looks like you're loading json, so the json
module will help you out with that.