将统一的diff应用于文件的纯Python方法

将统一的diff应用于文件的纯Python方法

本文介绍了将统一的diff应用于文件的纯Python方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个统一的差异文件(我们称其为补丁程序).我需要打开它,将其应用于指定的文件,然后将结果保存回该文件.与Unix patch 工具相同.我需要一个可以从.py脚本轻松调用的Python解决方案,到目前为止,我找不到任何解决方案.

I've got a unified diff file (let's call it a patch). I need to open it, apply to a specified file and save the result back to the file. Same way as Unix patch tool does. I need a Python solution that I could easily call from my .py script, and so far I can't find any.

我查看了 https://code.google.com/p/google-diff-match-patch/wiki/API ,它似乎无法满足我的需要.我还查看了 https://github.com/techtonik/python-patch https://github.com/matiasb/python-unidiff . python-patch 似乎模仿Unix patch util,但这是一个命令行工具,我不知道如何从.py脚本中调用它.

I've looked at https://code.google.com/p/google-diff-match-patch/wiki/API, and it looks like it can't do what I need. I also looked at https://github.com/techtonik/python-patch and https://github.com/matiasb/python-unidiff. python-patch seems to emulate the Unix patch util, but it's a command line tool and I don't understand how to call it from my .py script.

推荐答案

使用 python-patch :

import patch
pset = patch.fromfile(your_unified_diff_file)
pset.apply()

如果要应用于流/命名不同的输出,则必须创建自己的函数(查看应用正在执行此操作,或者在最新).

If you want to apply to a stream / differently named output, you will have to make your own function (look how apply is doing it, or find def apply in the latest).

这篇关于将统一的diff应用于文件的纯Python方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 15:31