python 如何“即时”区分文件和输出流?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2022492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to diff file and output stream "on-the-fly"?
提问by Enchantner
I need to create a diff file using standard UNIX diffcommand with python subprocessmodule. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via os.mkfifomethod, but didn't reach any good result. Please, can you write a simple example on how to solve this stuff? I tried like so:
我需要使用标准 UNIX diff命令和 python subprocess模块创建一个 diff 文件。问题是我必须在不创建临时文件的情况下比较文件和流。我想过通过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)
but it seems like diff
doesn't see the second argument.
但似乎diff
没有看到第二个论点。
回答by Fred Larson
You can use "-" as an argument to diff
to mean stdin
.
您可以使用“-”作为参数diff
来表示stdin
。
回答by Noufal Ibrahim
You could perhaps consider using the difflibpython module (I've linked to an example here) and create something that generates and prints the diff directly rather than relying on diff
. The various function methods inside difflib can receive character buffers which can be processed into diffs of various types.
您或许可以考虑使用difflibpython 模块(我已在此处链接到一个示例)并创建一些直接生成和打印 diff 而不是依赖diff
. difflib 中的各种函数方法可以接收字符缓冲区,这些缓冲区可以处理成各种类型的 diff。
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