实现解析python文件,生成AST,然后修改python文件内的内容并输出。

RedBaron

使用RedBaron库可以实现这个功能,官网是https://redbaron.readthedocs.io/en/latest/。 安装:pip install redbaron

Demo

样例文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = 1


def hello():
    return "world"


b = 2
c = 3
d = [1, 2, 3]

修改样例文件

1
2
3
4
5
6
7
8
9
def lab001():
    # 读取sample.py文件
    red = RedBaron(open("sample.py").read())

    # find ,直接查找node的type
    node = red.find("assignment", lambda x: x.name.value == 'a')
    node.value = '9'

    print(red.dumps())  # get code back

image.png|150