在Python中使用ast.parse错误解析python源代码

时间:2016-05-26 11:38:06

标签: python-3.x parsing abstract-syntax-tree

在Python中探索ast module。 我试试这个

import ast

py_src = r'C:\location\to\sourcefile'
c = open(py_src, 'r')
ast_out = ast.parse(content.read())

修改 按照塞巴斯蒂安的评论:

import ast
import tokenize

py_src = r'C:\location\to\sourcefile'
c = tokenize.open(py_src)
ast_out = ast.parse(content.read())

py_src文件

# Python source file
import os

class Test():
    """
    This class holds latitude, longitude, depth and magnitude data.
    """

    def __init__(self, latitude, longitude, depth, magnitude):
        self.latitude = latitude
        self.longitude = longitude
        self.depth = depth
        self.magnitude = magnitude

    def __str__(self):
        # -1 is for detection of missing data
        depth = self.depth
        if depth == -1:
            depth = 'unknown'

        magnitude = self.magnitude
        if magnitude == -1:
            depth = 'unknown'

        return "M{0}, {1} km, lat {2}\N{DEGREE SIGN} lon {3}\N{DEGREE SIGN}".format(magnitude, depth, self.latitude, self.longitude)

我得到一个缩进错误:

Traceback (most recent call last):
  File "C:/.../.py", line 31, in <module>
    t = ast.parse(content.read())
  File "C:\...\Python\Python35-32\lib\ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 2
    import os
    ^
IndentationError: unexpected indent

知道我做错了什么吗?

最终,我想获取该源文件的AST并提取其结构令牌详细信息(例如关键字,方法定义等)。你有一个建议的例子吗?

0 个答案:

没有答案