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

问题描述

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

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

更新:我想这样做的原因是我想写一个突变测试库 对于python,主要是通过删除语句/表达式,重新运行测试并查看中断的内容.

解决方案

Pythoscope 对它自动生成测试用例,就像用于 python 2.6 的 2to3 工具一样(它转换 python 2.x 源代码转换为 python 3.x 源代码).

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

rope 项目 可以满足您的需求,如果您想进行更多的重构(如转换).

ast 模块是您的另一个选择,有一个关于如何解析"的旧示例语法树回到代码(使用解析器模块).但是 ast 模块在对代码执行 AST 转换然后转换为代码对象时更有用.

redbaron 项目也很适合(ht Xavier Combelle)>

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).

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: 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 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).

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.

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

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.

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

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

09-05 12:12