-2

我正在尝试编写一个python解析器,在我看来它可以解析一个“if语句”,但它没有。它向我显示了“语法错误”消息。

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

提前致谢。

代码在这里: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
4

1 回答 1

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>
于 2011-02-08T17:07:40.767 回答