python代码输出为抽象树

# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 12:17:32 2020

@author: leslielee

抽象树abstract syntax tree 或 parse tree, 是高级语言编译为汇编语言的第二步。
python有内置的模块ast,但是用print输出不好看
所以使用astpretty输出

https://www.dazhuanlan.com/2019/12/14/5df3f50c003f4/
https://www.cnblogs.com/yssjun/p/10069199.html
"""

import ast
import astpretty

source = \
"""
b=1
while b<20:
    print(b)
    b += 1
"""
# 编译为AST
parse = ast.parse(source)

# 对比一下print与pprint
print(ast.dump(parse))
print('='*10)
astpretty.pprint(parse, indent='    ') #indent为缩进

# 此处source的ast分为两个大类:一个是第一句的赋值  还有就是while循环  
# 用body[0] body[1]来选择性的输出
print(ast.dump(parse.body[0]))
print('='*10)
astpretty.pprint(parse.body[1], indent='    ') #indent为缩进

发布了53 篇原创文章 · 获赞 23 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37083038/article/details/104510193