使用python文本处理模块编辑多个文件
Python-Mass-Editor的Python项目详细描述
实现一个python mass editor类来使用python处理多个文件 代码。修改作为diff输出显示在stdout上。一个 然后可以使用-w/-write选项修改目标文件。
警告
这个工具是有用的,但它确实依赖于python eval()函数,不检查正在执行的代码。 这是一个重大的安全风险,不应该使用这个工具 在生产环境中。
有关危险的详细讨论,请参见Ned Batchelder’s article。 链接到eval()和规避它们的方法。请注意 本文提出的对策是在这个时候实施的。
用法
您可能需要了解Python re module(常规 表达式)。
usage: massedit.py [-h] [-v] [-w] [-V] [-e EXPRESSIONS] [-s STARTDIR] [-m MAXDEPTH] [-o output] pattern [pattern ...] Python mass editor positional arguments: pattern file patterns to process. optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -w, --write modify target file(s) in place. Shows diff otherwise. -V, --verbose increases log verbosity (can be specified multiple times) -e EXPRESSIONS, --expression EXPRESSIONS Python expressions to be applied on all files. Use the line variable to reference the current line. -s START_DIR, --start START_DIR Starting directory in which to look for the files. If there is one pattern only and it includes a directory, the start dir will be that directory and the max depth level will be set to 1. -m MAX_DEPTH, --max-depth-level MAX_DEPTH Maximum depth when walking subdirectories. -o output, --output output redirect output to a file example: massedit.py -e "re.sub('failIf', 'assertFalse', line)" *.py
如果massedit作为一个包安装(例如从pypi安装),则可以 作为命令行工具与之交互:
python -m massedit -e "re.sub('assertEquals', 'assertEqual', line)" test.py
或作为库(上面的命令行选项将作为kewyord参数传递):
>>> import massedit >>> filenames = ['massedit.py'] >>> massedit.edit_files(filenames, ["re.sub('Jerome', 'J.', line)"])
最后,在 分配。
安装
从http://github.com/elmotec/massedit或:
下载massedit.py。pip install massedit
计划
- 添加对第三方工具(例如autopep8)的支持以处理文件。
- 添加对表达式文件的支持作为参数以允许多个 立即修改。
- 找到一个令人满意的方法(即易于使用)来处理多行regex 当前版本是逐行工作的。
- 除了line之外,还要添加魔法变量lineno和filename。
基本原理
- 我很难练习几种以上的方言 表达。
- 我需要一个可以移植到windows的东西,而不必担心eol。
- 我相信python是构建比 基于正则表达式的简单替换。
背景
我已经使用runsed和checksed(来自unix电动工具)很多年了,而且 直到我碰到格雷厄姆,才在窗户下找到一个好的替代品 fawcett python recipe437932在activestate上。它激励我写 python质量编辑器。
核心有点肉质化了,我们到了。如果你觉得有用 请增强它,不要忘记提交补丁。谢谢!
如果您对awk类工具更感兴趣,您可能会发现pypa 更好的选择。这当然是一个更成熟的工具。
许可证
根据MIT License条款授权。见附件license.txt。
更改
- 0.61(2012-07-06)
- 添加了massedit.edit_files功能,以方便作为库而不是作为 命令行工具(由Maxm VEKSLER建议).< /DD>
- 0.60(2012-07-04)
- 将参数作为模式而不是文件来处理 多个子目录中的多个文件。添加了-s(开始目录) 和-m(最大深度)选项。
- 0.52(2012-06-05)
- 为python 3升级。仍然与Python2.7兼容。
- 0.51(2012-05年)
- 初始版本(beta版)。