Python - 我可以知道是否发生了打印

时间:2012-08-12 08:12:44

标签: python command-line

我写了一个简单的python脚本。 在脚本中我正在使用

os.system ("diff file1 file2")

检查两个文本文件是否相似。 我知道如果没有打印出来的话文件是相似的。 如果没有打印,我想打印一些东西 到命令行,如“>文件类似”。

有什么想法吗?

2 个答案:

答案 0 :(得分:9)

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True

如果True那么只打印两个类似的消息 filecmp - 逐字节有效比较

答案 1 :(得分:5)

类似这样的事情

import os
import copy
import subprocess

def command(command):
    env = copy.deepcopy(os.environ)
    proc = subprocess.Popen(command,
                shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    result = proc.stdout.read()
    return result

ret = command("cmd /c diff file1 file2")
if ret == "":
    print "no result files are same"
else:
    print "results: \r\n %s" % ret

这是一种更通用的解决方案,适用于任何类型的命令。