获取输入另一个程序的输出动态 [英] Getting another program's output as input on the fly
问题描述
我有两个方案,我用这种方式:
$ c_program | python_program.py
使用
c_program打印的东西 我想使python_program.py过程c_program的输出,它打印,马上,使之可以打印自己的电流输出。不幸的是python_program.py后才c_program端获取输入。 我该如何解决呢? 只需设置标准输出到你的C程序的开头行缓冲(之前执行任何输出),就像这样:的printf()
,并使用 sys.stdin.readline()
的#include<&stdio.h中GT;
setvbuf用来(标准输出,NULL,_IOLBF,0);
或
的#include<&stdio.h中GT;
setlinebuf与(标准输出);
任一个在Linux上的工作,但 setvbuf用来
是C标准的一部分,因此它完全可以在多个系统。
在默认情况下标准输出将是块缓冲带缓冲的终端管道或文件,或线路。因为stdout是在这种情况下的管中,默认将块缓冲。如果是块,然后缓存缓冲区会被刷新,当它满了,或者当你调用 fflush(标准输出)
。如果是行缓冲,然后它会自动在每行之后被刷新。
I've two programs I'm using in this way:
$ c_program | python_program.py
c_program prints something using printf()
and python_program.py reads using sys.stdin.readline()
I'd like to make the python_program.py process c_program's output as it prints, immediately, so that it can print its own current output. Unfortunately python_program.py gets its input only after c_program ends.
How can I solve this?
Just set stdout to be line buffered at the beginning of your C program (before performing any output), like this:
#include <stdio.h>
setvbuf(stdout, NULL, _IOLBF, 0);
or
#include <stdio.h>
setlinebuf(stdout);
Either one will work on Linux, but setvbuf
is part of the C standard so it will work on more systems.
By default stdout will be block buffered for a pipe or file, or line buffered for a terminal. Since stdout is a pipe in this case, the default will be block buffered. If it is block buffered then the buffer will be flushed when it is full, or when you call fflush(stdout)
. If it is line buffered then it will be flushed automatically after each line.
这篇关于获取输入另一个程序的输出动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!