Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure Python way to apply a unified diff to a file?

Tags:

python

diff

patch

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.

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.

like image 945
Violet Giraffe Avatar asked Jul 15 '15 15:07

Violet Giraffe


1 Answers

Using python-patch:

import patch
pset = patch.fromfile(unified_diff_filename)
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).

like image 151
bufh Avatar answered Nov 04 '22 14:11

bufh