There were times when I wanted to run diff in python. Specifically, when you want to take a quick look at the differences between the files you are monitoring.
--Take the result of diff with python --Embed the result in the body of email or chat
Well, you can do everything with a shell, but if you want to do various things before that, python is more convenient.
In such a case, check_output of subprocess is convenient. diff is exit 1 when a diff occurs and check_output throws an exception when not 0. So, the return code and output are included in the exception attributes, so you can pick them up.
subprocess_sample.py
# -*- coding: utf-8 -*-
import subprocess
import shlex
import sys
file1 = sys.argv[1]
file2 = sys.argv[2]
command_line = "diff -u {} {}".format(file1, file2)
command_args = shlex.split(command_line)
rc = 0
try:
rc = subprocess.check_output(command_args)
except subprocess.CalledProcessError as cpe:
print "shell returncode is not 0."
print "returncode: {}".format(cpe.returncode)
print "output: {}".format(cpe.output)
rc = cpe.returncode
print rc
% python subprocess_sample.py hoge_old.txt hoge_new.txt
shell returncode is not 0.
returncode: 1
output: --- hoge_old.txt 2015-06-27 14:29:03.000000000 +0900
+++ hoge_new.txt 2015-06-27 14:28:54.000000000 +0900
@@ -1,2 +1,2 @@
-hoge
+hogo
foo
1
There used to be a commands module, but this is obsolete in Series 3 and is deprecated in Series 2 (2.7 and later).
Recommended Posts