解析一个.py文件,读取AST,修改它,然后回写修改后的源代码 [英] Parse a .py file, read the AST, modify it, then write back the modified source code

查看:750
本文介绍了解析一个.py文件,读取AST,修改它,然后回写修改后的源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式编辑python源代码。基本上我想读一个 .py 文件,生成 AST ,然后写回修改后的python源代码(即另一个 .py 文件)。

I want to programmatically edit python source code. Basically I want to read a .py file, generate the AST, and then write back the modified python source code (i.e. another .py file).

有一些方法可以使用标准的python模块解析/编译python源代码,例如 ast 编译器 。但是,我不认为任何人都支持修改源代码的方法(例如删除此函数声明),然后回写修改的python源代码。

There are ways to parse/compile python source code using standard python modules, such as ast or compiler. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.

UPDATE :我想这样做的原因是我想写一个突变测试库

UPDATE: The reason I want to do this is I'd like to write a Mutation testing library for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.

推荐答案

Pythoscope 对自动生成的测试用例执行此操作, 2to3 工具python 2.6(它将python 2.x源转换为python 3.x源)。

Pythoscope does this to the test cases it automatically generates as does the 2to3 tool for python 2.6 (it converts python 2.x source into python 3.x source).

这两个工具都使用 lib2to3 库,它是一个python解析器/编译器机制的实现,可以在源代码 - > AST - >源代码中源代码中保留注释。

Both these tools uses the lib2to3 library which is a implementation of the python parser/compiler machinery that can preserve comments in source when it's round tripped from source -> AST -> source.

绳子项目可以满足您的需求,如果你想做更多的重构像转换。

The rope project may meet your needs if you want to do more refactoring like transforms.

ast 模块是您的其他选项,有一个较旧的示例如何解压缩语法树回代码(使用解析器模块)。但是,当对代码进行AST转换,然后将其转换为代码对象时,ast模块更有用。

The ast module is your other option, and there's an older example of how to "unparse" syntax trees back into code (using the parser module). But the ast module is more useful when doing an AST transform on code that is then transformed into a code object.

redbaron 项目也可能是一个很好的适合(ht Xavier Combelle)

The redbaron project also may be a good fit (ht Xavier Combelle)

这篇关于解析一个.py文件,读取AST,修改它,然后回写修改后的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆