临摹微笑
我们有类似的需求,为此我创建了asttokens库。它以文本和标记化形式维护源,并用标记信息标记AST节点,从中也可以轻松获得文本。它适用于Python 2和3(经过2.7和3.5测试)。例如:import ast, asttokensst='''def greet(a): say("hello") if a else say("bye")'''atok = asttokens.ASTTokens(st, parse=True)for node in ast.walk(atok.tree): if hasattr(node, 'lineno'): print atok.get_text_range(node), node.__class__.__name__, atok.get_text(node)印刷(1, 50) FunctionDef def greet(a): say("hello") if a else say("bye")(17, 50) Expr say("hello") if a else say("bye")(11, 12) Name a(17, 50) IfExp say("hello") if a else say("bye")(33, 34) Name a(17, 29) Call say("hello")(40, 50) Call say("bye")(17, 20) Name say(21, 28) Str "hello"(40, 43) Name say(44, 49) Str "bye"