简体   繁体   English

在子进程终止之前,子进程的输出在无缓冲stdout管道上不可用?

[英]Output from subprocess is not available on unbuffered stdout pipe before the subprocess terminates?

I've created a subprocess using subprocess.Popen(['myapp'], stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0) that executes a C-program that writes to stdout using eg puts() . 我使用subprocess.Popen(['myapp'], stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0)创建了一个子subprocess.Popen(['myapp'], stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0)该子subprocess.Popen(['myapp'], stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0)执行一个使用例如puts()写入stdout的C程序。

The problem is that the Python program blocks in p.stdout.read(1024) , although the subprocess starts by puts("HelloWorld") . 问题是尽管子p.stdout.read(1024)puts("HelloWorld")开始,但Python程序在p.stdout.read(1024)p.stdout.read(1024) Only after the subprocess terminates, is output available on p.stdout . 仅在子p.stdout终止后,才能在p.stdout上输出。 I thought that bufsize=0 would mean that pipes become unbuffered, so that output is immediately available on the pipe. 我认为bufsize=0意味着管道变得无缓冲,因此输出立即在管道上可用。

I have read the below question, which states that newlines should cause output to be flushed. 我已阅读以下问题,该问题指出换行符应导致输出被刷新。 However, puts() prints a newline, so are the pipes not recognized as an interactive device? 但是, puts()打印换行符,因此管道不被识别为交互式设备吗?

Difference between puts() and printf() in C while using sleep() 使用sleep()时C中puts()和printf()之间的区别

It's because puts is also outputting a newline character which, on devices that can be determined to be interactive, causes flushing by default (for standard output) (a). 这是因为puts还输出换行符,在可以确定是交互式的设备上,默认情况下会导致刷新(对于标准输出)(a)。

Any ideas? 有任何想法吗?

This is application behavior. 这是应用程序行为。 Even if the pipe is unbuffered, applications normally buffer information that they are going to write to a file (any type of file) for some time before actually writing it. 即使管道是未缓冲的,应用程序通常也会在实际写入文件之前缓冲一段时间要写入文件(任何类型的文件)的信息。 As Jon's comment above indicates, a system-call like fflush() can be used by programs to ensure that they actually have posted the data, and, if applicable, that a physical I/O operation has actually completed. 正如Jon在上面的评论所指出的那样,程序可以使用诸如fflush()类的系统调用来确保它们实际上已经发布了数据,并且在适用的情况下还可以确保物理I / O操作实际上已经完成。

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

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