2011-02-08 94 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>