Last active
September 10, 2024 20:24
-
-
Save simonLeary42/aaf1ba0198905fb9927d143204ca6386 to your computer and use it in GitHub Desktop.
Runs GNU Diff and [diffr](https://github.com/mookid/diffr) to compare strings without tempfiles. UNIX only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import threading | |
import subprocess | |
before = "" | |
after = "" | |
before_read_fd, before_write_fd = os.pipe() | |
after_read_fd, after_write_fd = os.pipe() | |
diff_proc = subprocess.Popen( | |
[ | |
"diff", | |
"-u", | |
"--color=always", | |
f"/dev/fd/{before_read_fd}", | |
f"/dev/fd/{after_read_fd}", | |
], | |
pass_fds=[before_read_fd, after_read_fd], | |
stdout=subprocess.PIPE, | |
stderr=subprocess.STDOUT, | |
) | |
before_write_thread = threading.Thread( | |
target=os.write, args=(before_write_fd, before.encode()) | |
) | |
after_write_thread = threading.Thread( | |
target=os.write, args=(after_write_fd, after.encode()) | |
) | |
before_write_thread.start() | |
after_write_thread.start() | |
before_write_thread.join() | |
after_write_thread.join() | |
os.close(before_write_fd) | |
os.close(after_write_fd) | |
diff_output, _ = diff_proc.communicate() | |
diffr_proc = subprocess.Popen( | |
"diffr", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT | |
) | |
diffr_output, _ = diffr_proc.communicate(input=diff_output) | |
print(diffr_output.decode()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment