[英]PLY lex yacc: Errors handling
I am using PLY to parse a file. 我正在使用PLY解析文件。 I have to print a message to the user when I have an error on a line. 当我在一行上有错误时,我必须向用户打印一条消息。
A message like Error at the line 4
. 第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()
But it is not working. 但这是行不通的。 I have the error 我有错误
print ("Erreur de syntaxe sur la ligne %d" % (p.lineno))
AttributeError: 'NoneType' object has no attribute 'lineno'
Is there another is more suitable way to do that? 还有另一种更合适的方法吗?
I encountered the same problem a while ago. 我前一段时间遇到了同样的问题。 It is caused by unexpected end of input . 这是由于意外终止输入引起的。
Just test if p
(which is actually a token in p_error
) is None
. 只需测试p
(实际上是p_error
的标记)是否为None
。
Your code would look something like this: 您的代码如下所示:
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')
Hope this helps. 希望这可以帮助。
I resolved the problem. 我解决了这个问题。 My problem was that I always reinitialise the parser. 我的问题是我总是重新初始化解析器。
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()
The good function is 好的功能是
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")
When I have an expected end of input, I must not continue parsing. 预期输入结束时,请勿继续解析。
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.