问题描述
python脚本正在Linux上控制外部应用程序,将输入通过管道传递到外部应用程序stdin,并通过管道从外部应用程序stdout读取输出.
A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout.
问题在于,对管道的写入是按块而不是按行进行缓冲的,因此在控制脚本接收外部应用程序中的printf等输出数据之前会发生延迟.
The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.
不能更改外部应用程序以添加显式的fflush(0)调用.
The external application cannot be altered to add explicit fflush(0) calls.
python标准库的 pty 模块如何可以与 subprocess 模块一起使用以实现此目的?
How can the pty module of the python standard library be used with the subprocess module to achieve this?
推荐答案
您可以使用PTY通过以下方式解决此问题:
You can use PTYs to solve this by:
- 创建pty主/从对;
- 将子进程的stdin,stdout和stderr连接到pty从设备;
- 在父级中读取和写入pty主机.
这篇关于强制使用Python取消缓冲另一个程序的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!