Python では、commands.getoutput('diff a.txt b.txt') を使用して 2 つのファイルを比較し、それらが同じ場合は「成功!」と出力します。それらが同じである場合に満たされるif文をどのように書くのですか?
1077 次
5 に答える
3
以下の方が高速です。両方のファイル全体を読み取って差分を計算するのではなく、最初の違いでファイルが同一ではないと判断します。commands
また、名前に空白または印刷できない文字が含まれるファイルを正しく処理し、モジュールが削除された後もPythonの将来のバージョンで引き続き機能します。
import subprocess
if subprocess.Popen(['cmp', '-s', '--', 'a.txt', 'b.txt']).wait() == 0:
print 'Files are identical'
の使用がdiff
不自然な例であり、実際の目標が出力が与えられたかどうかを判断することであった場合、Popenを使用してこれを行うこともできます。
import subprocess
p = subprocess.Popen(['diff', '--', 'a.txt', 'b.txt'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
(stdout, _) = p.communicate()
if p.returncode != 0:
print 'Process exited with error code %r' % p.returncode
if stdout:
print 'Process emitted some output: \n%s' % stdout
else:
print 'Process emitted no output'
チェックreturncode
は、出力なしが成功を意味する場合と失敗が発生した場合を区別する必要があるUNIXツールで特に重要です。出力を見るだけでは、必ずしもこの区別ができるとは限りません。
于 2012-05-04T19:12:30.473 に答える
1
使えますfilecmp
か?
import filecmp
diff = filecmp.cmp('a.pdf','b.pdf')
if diff:
print('Success!')
于 2012-05-04T19:32:36.320 に答える
1
コマンドを使用しないで os を使用する方がはるかに優れています...
import os
os.system("diff a.txt b.txt" + "> diffOutput")
fDiff = open("diffOutput", 'r')
output = ''.join(fDiff.readlines())
if len(output) == 0:
print "Success!"
else:
print output
fDiff.close()
于 2012-05-04T19:00:45.177 に答える
0
commands.getoutput
を使用する理由 このモジュールはpython 2.6から廃止されました。また、pythonだけでファイルを比較することもできます。
file_1_path = 'some/path/to/file1'
file_2_path = 'some/path/to/file2'
file_1 = open(file_1_path)
file_2 = open(file_2_path)
if file_1.read() == file_2.read():
print "Success!"
file_1.close()
file_2.close()
異なるファイルへの 2 つのパスが与えられた場合、それらは両方を文字列に ing しopen
た結果を比較します。read
于 2012-05-04T19:01:34.227 に答える
0
result = commands.getoutput('diff a.txt b.txt')
if len(result) == 0:
print 'Success'
于 2012-05-04T19:02:47.263 に答える