如何从代码中检测到EOF分析器错误?

时间:2019-04-08 05:14:52

标签: python-3.x tkinter eof

该代码用于GUI计算器。如何从代码中检测到EOF分析错误?

代码:

def btnEqualsInput():
    global operator
    if operator!='':
        sumup = str(eval(operator))
        text_Input.set(sumup)
        operator =""

当我在文本框中单击带有3 *的'='时输出

    sumup = str(eval(operator))
  File "<string>", line 1
    3*
     ^
SyntaxError: unexpected EOF while parsing

我要显示“错误!”每当用户在文本框中输入错误语法等于“ Equals”时,计算器显示在屏幕上。

2 个答案:

答案 0 :(得分:1)

只需捕获异常:

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,"EOF" in str(e)为true)

答案 1 :(得分:0)

您想捕获解析器异常:

try:
    sumup = str(eval(operator))
except SyntaxError as e:
    print('Error!', e)