问题描述
我想以编程方式编辑 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.
更新:我想这样做的原因是我想写一个 突变测试库 对于 python,主要是通过删除语句/表达式,重新运行测试并查看什么中断.
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 an implementation of the python parser/compiler machinery that can preserve comments in source when it's round tripped from source -> AST -> source.
rope 项目可以满足你的需求,如果你想做更多的重构,比如转换.
The rope project may meet your needs if you want to do more refactoring like transforms.
ast 模块是您的另一个选择,有一个更老的例子来说明如何unparse"语法树回到代码中(使用解析器模块).但是 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,修改它,然后写回修改后的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!