如何修复 Python 中的动态变量赋值冲突

How to fix dynamic variable assignment conflict in Python

如何修复此 Python 代码中的变量赋值?所以,我有这个 python 代码:

with open('save.data') as fp:
    save_data = [line.split(' = ') for line in fp.read().splitlines()]
with open('brute.txt') as fp:
    brute = fp.read().splitlines()
for username, password in save_data:
    if username in brute:
        break
else:
    print("didn't find the username")

好的,一个快速的解释; save.data 是一个包含批处理文件游戏变量(例如用户名、hp 等...)的文件,brute.txt 是一个包含 "random" 字符串的文件(如在用于暴力破解的词表)。

save.data:

username1 = PlayerName
password1 = PlayerPass
hp = 100

正如我之前所说,这是一个批处理文件游戏,所以不需要引用字符串。

brute.txt:

username
username1
password
password1
health
hp

因此,当执行 Python 代码时,它会加载两个文件的内容并将它们保存到列表中,然后遍历 "brute" 它们的用户名和密码,直到它们与上面的内容匹配brute.txt,它们会自动分配给自己。但是,问题出在赋值上,当我尝试 print 它们(变量)时,会发生这种情况:

## We did all the previous code
...
>>> print(save_data)

[['username', 'PlayerName'], ['password', 'PlayerPass'], ['health', '100']]
>>> print("Your username is: " + username)

username
>> print("Your password is: " + password)

PlayerName
>> print("Your health is: " + hp)

NameError: name 'hp' is not defined

那么,关于如何解决分配冲突有什么想法吗?如果有不明白的地方,欢迎评论,我会一一解答。

and they assign themselves automatically

这不是一回事。我想您是在想象 save.data 中的 pseudo-variables pseudo-defined 将成为程序中的 Python 变量。他们不会。

相反,将它们解析为数据结构并从数据结构中检索值。

例如,

with open('save.data') as fp:
    save_data = dict([line.split(' = ') for line in fp.read().splitlines()])

...

print(save_data["hp"])