问题描述
我想以编程方式编辑python源代码。基本上我想读一个 .py
文件,生成,然后写回修改后的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源代码,例如或。但是,我不认为任何人都支持修改源代码的方法(例如删除此函数声明),然后回写修改的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.
推荐答案
对自动生成的测试用例执行此操作,工具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).
这两个工具都使用库,它是一个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模块更有用。
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.
项目也可能是一个很好的适合(ht Xavier Combelle)
The redbaron project also may be a good fit (ht Xavier Combelle)
这篇关于解析一个.py文件,读取AST,修改它,然后回写修改后的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!