为什么python的解析器会在这个简单的输入上抛出错误?

Mat*_*ime 1 python parsing abstract-syntax-tree

我有以下代码 -

from sys import version

class ExampleClass(object):
        def get_sys_version(self):
                return version

x = ExampleClass()
print x.get_sys_version()
Run Code Online (Sandbox Code Playgroud)

它被这段代码解析 -

import ast

source = open("input.py")
code = source.read()
node = ast.parse(code, mode='eval')
Run Code Online (Sandbox Code Playgroud)

并导致此错误 -

Traceback (most recent call last):
  File "parse.py", line 5, in <module>
    node = ast.parse(code, mode='eval')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    from sys import version
Run Code Online (Sandbox Code Playgroud)

这似乎是一个非常简单的解析文件 - 它肯定会运行 - 为什么解析器抛出这个错误?

Ale*_*amo 11

这是因为你正在使用mode='eval',它只适用于单个表达式.您的代码有多个语句,因此请mode='exec'改用.(这是默认值)

有关参数的解释,请参阅文档compile()mode,因为这是ast.parse()使用的内容.