使用时出现“SyntaxError:无效语法”

2024-06-25 23:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的有奇怪的语法错误。在第一次代码运行良好,但之后 它不起作用。在

MailName={}
string = ""
#pdb.set_trace()
fp=open("C:\\Users\\Dvir\\Dropbox\\chat\\cred.txt","a+")
#pdb.set_trace()

try:
    string=fp.read()

except:
    string=""

if (string !=""):
    MailName = eval(string)

有问题的代码是:

^{pr2}$

语法错误:

MailName = eval(string)   File "<string>", line 2
{'familyname': 'josh', 'pass': 'UGGlXJCpl', 'email': 'chat@gmail.com', 'n ame': 'justin'}
^ SyntaxError: invalid syntax

当我第一次使用这部分代码时,它运行得很好,但之后它显示出语法错误,这很奇怪,因为它是一个有效的字典。在


Tags: 代码stringevalchattraceopenuserspdb
1条回答
网友
1楼 · 发布于 2024-06-25 23:57:25

我会将数据存储在JSON中,并使用^{}来加载它—这比使用eval()更安全


引自this answer

eval() will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife.

There was recently a thread about how to do this kind of thing safely on the python-dev list, and the conclusions were:

It's really hard to do this properly.
It requires patches to the python interpreter to block many classes of attacks.
Don't do it unless you really want to.

您可以按如下方式格式化文本文件:(信用证.txt)在

{
    "familyname": "josh", 
    "email": "chat@gmail.com", 
    "name": "justin", 
    "pass": "UGGlXJCpl"
}

然后像这样加载:

^{pr2}$

相关问题 更多 >