Violet Giraffe
Violet Giraffe

Reputation: 33579

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

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.

Upvotes: 10

Views: 12450

Answers (1)

bufh
bufh

Reputation: 3410

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

Upvotes: 11

Related Questions