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

How do I detect the EOF parser error from within the code?

该代码用于 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

每当用户在文本框中的错误语法上按等于时,我想在计算器显示中显示 "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

如果您想做一些特定的事情,您也可以解析错误字符串(例如,对于 EOF,"EOF" in str(e) 将为真)