簡體   English   中英

PLY lex yacc:錯誤處理

[英]PLY lex yacc: Errors handling

我正在使用PLY解析文件。 當我在一行上有錯誤時,我必須向用戶打印一條消息。

Error at the line 4顯示Error at the line 4消息。

def p_error(p):
    flag_for_error = 1
    print ("Erreur de syntaxe sur la ligne %d" % (p.lineno))
    yacc.errok()

但這是行不通的。 我有錯誤

print ("Erreur de syntaxe sur la ligne %d" % (p.lineno))
AttributeError: 'NoneType' object has no attribute 'lineno'

還有另一種更合適的方法嗎?

我前一段時間遇到了同樣的問題。 這是由於意外終止輸入引起的。

只需測試p (實際上是p_error的標記)是否為None

您的代碼如下所示:

def p_error(token):
    if token is not None:
        print ("Line %s, illegal token %s" % (token.lineno, token.value))
    else:
        print('Unexpected end of input')

希望這可以幫助。

我解決了這個問題。 我的問題是我總是重新初始化解析器。

def p_error(p):
    global flag_for_error
    flag_for_error = 1

    if p is not None:
        errors_list.append("Erreur de syntaxe à la ligne %s"%(p.lineno))
        yacc.errok()
    else:
        print("Unexpected end of input")
        yacc.errok()

好的功能是

def p_error(p):
    global flag_for_error
    flag_for_error = 1

    if p is not None:
        errors_list.append("Erreur de syntaxe à la ligne %s"%(p.lineno))
        yacc.errok()
    else:
        print("Unexpected end of input")

預期輸入結束時,請勿繼續解析。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM