Install & Compatibility
Where this runs
tested against v1.16 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.110s · 19.2MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 2.4s · import 0.098s · 20MB
17MB installed
● package 17MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
PatchSet
✓ from patch import PatchSet
Used for representing a collection of patches and applying them.
fromstring
✓ from patch import fromstring
Function to parse a unified diff from a string.
fromfile
✓ from patch import fromfile
Function to parse a unified diff from a file.
This quickstart demonstrates how to programmatically apply a unified diff to a file. It creates a temporary original file, defines a diff string, parses the diff using `fromstring`, and then applies it to a simulated target file. Note that the `apply` method modifies files on the filesystem.
import os
import tempfile
from patch import fromstring, PatchSet
# Create a dummy original file
original_content = """Line 1
Line 2
Line 3
"""
with tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.txt') as f_orig:
f_orig.write(original_content)
original_filepath = f_orig.name
# Create a diff that adds a line and modifies another
diff_content = """--- a/test.txt 2023-01-01 00:00:00.000000000 +0000
+++ b/test.txt 2023-01-01 00:00:00.000000000 +0000
@@ -1,3 +1,4 @@
Line 1 modified
+Line 1.5 added
Line 2
Line 3
"""
# Parse the diff
patch_set = fromstring(diff_content)
# Apply the patch to the original file
# The library assumes the files are in the current working directory
# or specified by path. Here, we'll patch a file named 'test.txt'
# which we'll simulate by reading from original_filepath and applying to a new file.
target_filename = os.path.basename(original_filepath)
# To apply, the patch expects the target file to exist at a specific relative path.
# We will simulate this by copying our temp file and then patching that copy.
patched_content = None
with open(original_filepath, 'r') as f_read:
original_lines = f_read.readlines()
# Manually apply the patch (as the library's apply() method typically writes to disk)
# For a quickstart, it's easier to show the logic.
# In a real scenario, you'd do: patch_set.apply(strip=0, root=os.path.dirname(original_filepath))
# But it requires writing to the same filename specified in the diff.
# Let's write the original content to a file that matches the diff's target name
with open(target_filename, 'w') as f_target:
f_target.write(original_content)
# Now, apply the patch using the library's method
# The apply method attempts to write back to the file system.
success = patch_set.apply(strip=0, root='.') # root is current dir where target_filename is
if success:
with open(target_filename, 'r') as f_patched:
patched_content = f_patched.read()
print("Patch applied successfully.")
print("Patched content:\n", patched_content)
else:
print("Failed to apply patch.")
# Cleanup temporary files
os.remove(original_filepath)
os.remove(target_filename)
patch --version
Debug
Known issues
deprecatedThe `patch` library (techtonik/python-patch) has not seen an official release since February 2016 (version 1.16). This suggests it is largely unmaintained. Users seeking active development and support should consider alternatives or forks.fixConsider using the `patch-ng` library, which is a community fork actively maintained and compatible with Python 3.6+. `pip install "patch-ng"`
affects: <=1.16
breakingThe library documentation explicitly warns against future API breaks. If a version 2.x were ever released, it is expected to introduce breaking changes.fixWhen declaring `patch` as a dependency, use strict version specifiers like `patch==1.*` to prevent unintended upgrades to a potentially breaking 2.x release.
affects: All versions 1.x (regarding potential future 2.x)
gotchaThis `patch` library is distinct from `unittest.mock.patch`, which is part of Python's standard library for testing and mocking objects. Confusing the two can lead to incorrect usage and debugging challenges.fixEnsure you import from `patch` (for diffs) or `unittest.mock` (for testing mocks) as appropriate for your task.
affects: All versions
gotchaThe library has known limitations; it does not support file renaming, creation, or removal, directory tree operations, version control specific properties, or non-unified diff formats.fixFor complex patching scenarios involving file system changes beyond content modification or non-unified diffs, alternative tools or manual pre/post-processing may be required.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'patch'
The `patch` library is not installed in your Python environment or is not accessible via the Python path.
fixInstall the library using pip: `pip install "patch==1.*"` or ensure the `patch.py` file is in your project directory or Python path if using it as a standalone script.
'patch' is not recognized as an internal or external command
This error occurs when attempting to run the `patch` library as a command-line tool without properly invoking the Python interpreter, or if the `patch.py` script (or its executable wrapper) is not in a directory included in your system's PATH.
fixExecute the script explicitly with Python: `python -m patch <your_patch_file>` (if installed) or `python patch.py <your_patch_file>` (if using the standalone script).
Hunk #X failed at Y
This message indicates that the `patch` tool could not apply a specific section (hunk) of the diff to the target file, usually because the target file's content doesn't exactly match what the patch expects.
fixManually inspect the diff and the original file to identify the discrepancies. You may need to edit the patch file, the target file, or apply the changes manually. This error can also occur if the patch tries to perform unsupported operations like file renaming, creation, or directory operations, or if the diff format is not unified.
Upgrade
Version history
1.16latest on PyPI · released Feb 13, 2016
Audit
Dependencies
No dependency data recorded yet.