2011-02-08 53 views
-2

我想写一个Python解析器,并在我的观点它可以解析一个“if语句”,但它不。它向我显示“语法错误”消息。解析python与PLY

有人能告诉我我做错了什么吗?

在此先感谢。

的代码是在这里:https://github.com/narke/py2neko


我修改了输入字符串是这样的:

s = '''if 5: 
    print 10 
else: 
    print 20 \n''' 
check_syntax(s) 

,输出是:

Syntax error at '5' 
atom: 10 
factor None 
None 
cmp: None None 
atom: 20 
factor None 
None 
cmp: None None 
simple_stmt: None 
+2

您可以提供“语法错误”消息。这可能对我们有帮助。 – 2011-02-08 16:55:28

回答

1

从代码:

s = "if 5:\n" 
check_syntax(s) 

if 5:\n是无效的语法,因为它不是一个完整的if语句。如果表达式为True,则需要提供套件(要执行的代码)。例如:

>>> if 5: 
... 
    File "<stdin>", line 2 

    ^
IndentationError: expected an indented block 

>>> compile('if 5:\n', '<string>', 'exec') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<string>", line 1 
    if 5: 
     ^
SyntaxError: unexpected EOF while parsing 

>>> compile('if 5:\n print 5', '<string>', 'exec') 
<code object <module> at 0xb7f60530, file "<string>", line 2>