如何实时比较文件和输出流?
我需要用标准的UNIX diff命令和Python的subprocess模块来创建一个差异文件。问题是我必须比较一个文件和一个流,而不想创建临时文件。我考虑过使用命名管道,通过os.mkfifo方法来实现,但没有得到好的结果。请问你能写一个简单的例子来解决这个问题吗?我尝试过这样做:
fifo = 'pipe'
os.mkfifo(fifo)
op = popen('cat ', fifo)
print >> open(fifo, 'w'), output
os.unlink(fifo)
proc = Popen(['diff', '-u', dumpfile], stdin=op, stdout=PIPE)
但是看起来diff没有看到第二个参数。
2 个回答
8
你可以考虑使用 difflib 这个Python模块(我这里有个例子链接),这样你就可以直接生成并打印出差异,而不是依赖于 diff
命令。difflib里面有很多函数方法,可以接收字符缓冲区,这些缓冲区可以处理成不同类型的差异。
另外,你也可以构建一个shell管道,使用进程替换,像这样:
diff <(cat pipe) dumpfile # You compare the output of a process and a physical file without explicitly using a temporary file.
想了解更多细节,可以查看 http://tldp.org/LDP/abs/html/process-sub.html
38
你可以用“-”作为diff
的一个参数,这样就表示要从标准输入(stdin)读取数据。