简体   繁体   English

如何“动态”区分文件和输出流?

[英]How to diff file and output stream “on-the-fly”?

I need to create a diff file using standard UNIX diff command with python subprocess module. 我需要使用带有python 子进程模块的标准UNIX diff命令创建一个diff文件。 The problem is that I must compare file and stream without creating tempopary file. 问题是我必须比较文件和流而不创建tempopary文件。 I thought about using named pipes via os.mkfifo method, but didn't reach any good result. 我想过通过os.mkfifo方法使用命名管道,但没有达到任何好结果。 Please, can you write a simple example on how to solve this stuff? 请问,你能写一个关于如何解决这个问题的简单例子吗? I tried like so: 我试过这样:

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)

but it seems like diff doesn't see the second argument. 但似乎diff没有看到第二个论点。

您可以使用“ - ”作为diff的参数来表示stdin

You could perhaps consider using the difflib python module (I've linked to an example here) and create something that generates and prints the diff directly rather than relying on diff . 你也许可以考虑使用difflib python模块(我已经链接到这里的一个例子)并创建一些直接生成和打印diff的东西,而不是依赖diff The various function methods inside difflib can receive character buffers which can be processed into diffs of various types. difflib中的各种函数方法可以接收字符缓冲区,可以将其处理成各种类型的差异。

Alternatively, you can construct a shell pipeline and use process substitution like so 或者,您可以构造一个shell管道并像这样使用进程替换

diff <(cat pipe) dumpfile # You compare the output of a process and a physical file without explicitly using a temporary file.

For details, check out http://tldp.org/LDP/abs/html/process-sub.html 有关详细信息,请查看http://tldp.org/LDP/abs/html/process-sub.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM