Python 3.x 如何从代码中检测EOF解析器错误?
该代码用于GUI计算器。如何从代码中检测EOF解析错误 代码: 在文本框中单击带3*的“=”时输出Python 3.x 如何从代码中检测EOF解析器错误?,python-3.x,tkinter,eof,Python 3.x,Tkinter,Eof,该代码用于GUI计算器。如何从代码中检测EOF解析错误 代码: 在文本框中单击带3*的“=”时输出 sumup = str(eval(operator)) File "<string>", line 1 3* ^ SyntaxError: unexpected EOF while parsing summup=str(eval(运算符)) 文件“”,第1行 3* ^ SyntaxError:分析时出现意外的EOF 每当用户在文本框中的错误语法上按Eq
sumup = str(eval(operator))
File "<string>", line 1
3*
^
SyntaxError: unexpected EOF while parsing
summup=str(eval(运算符))
文件“”,第1行
3*
^
SyntaxError:分析时出现意外的EOF
每当用户在文本框中的错误语法上按Equals时,我希望在计算器显示中显示“Error!”。您希望捕获解析器异常:
try:
sumup = str(eval(operator))
except SyntaxError as e:
print('Error!', e)
def btnEqualsInput():
global operator
if operator!='':
try:
sumup = str(eval(operator))
text_Input.set(sumup)
operator =""
except SyntaxError as e:
print("Error!",str(e)) #e contains the type of message, for example unexpected EOF while parsing
只需捕捉异常:
try:
sumup = str(eval(operator))
except SyntaxError as e:
print('Error!', e)
def btnEqualsInput():
global operator
if operator!='':
try:
sumup = str(eval(operator))
text_Input.set(sumup)
operator =""
except SyntaxError as e:
print("Error!",str(e)) #e contains the type of message, for example unexpected EOF while parsing
如果你想做一些特定的事情,你也可以解析错误字符串(例如,对于EOF,str(e)中的“EOF”将为真)由于安全问题,我建议你使用第三方评估工具代替
eval
<代码>simpleeval很好。@Jean-Françoisfare我刚开始学习python,所以现在还可以。我一定会查阅simpleeval,了解更多有关安全问题的信息。谢谢你的建议。