0

在 python 中,我想使用 commands.getoutput('diff a.txt b.txt') 来区分两个文件,如果它们相同,则打印“成功!”。如果它们相同,我将如何编写满足的 if 语句?

4

5 回答 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

不要使用命令使用 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 回答
1

你能用filecmp吗?

import filecmp

diff = filecmp.cmp('a.pdf','b.pdf')
if diff:
    print('Success!')
于 2012-05-04T19:32:36.320 回答
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()

给定两个不同文件的路径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 回答