子进程stdin缓冲区未在bufsize = 1的换行符上刷新 [英] subprocess stdin buffer not flushing on newline with bufsize=1
问题描述
我有两个小python文件,第一个使用input
读取一行,然后打印另一行
I have two small python files, the first reads a line using input
and then prints another line
a = input()
print('complete')
第二次尝试将此操作作为子进程
The second attempts to run this as a subprocess
import subprocess
proc = subprocess.Popen('./simp.py',
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
bufsize=1)
print('writing')
proc.stdin.write(b'hey\n')
print('reading')
proc.stdout.readline()
上面的脚本将先打印正在书写",然后显示正在阅读",然后挂起.起初我以为这是标准输出缓冲问题,所以我将bufsize=1
更改为bufsize=0
,这确实解决了该问题.但是,似乎是导致问题的标准输入.
The above script will print "writing" then "reading" but then hang. At first I thought this was a stdout buffering issue, so I changed bufsize=1
to bufsize=0
, and this does fix the problem. However, it seems it's the stdin that's causing the problem.
对于bufsize=1
,如果我在写操作下方添加proc.stdin.flush()
,则该过程将继续.这两种方法都显得笨拙,因为(1)未缓冲的流很慢(2)在所有地方添加刷新都很容易出错.为什么上述write
不能在换行符上刷新?文档说bufsize
是在为子进程创建stdin,stdout和stderr流时使用的,那么是什么原因导致写操作不能在换行符上刷新?
With bufsize=1
, if I add proc.stdin.flush()
below the write, the process continues. Both of these approaches seem clumsy since (1) unbuffered streams are slow (2) adding flushes everywhere is error-prone. Why does the above write
not flush on a newline? The docs say that bufsize
is used when creating stdin, stdout, and stderr stream for the subprocess, so what's causing the write to not flush on the newline?
推荐答案
来自文档:"1表示行缓冲(仅当Universal_newlines = True,即在文本模式下可用)" .这有效:
import subprocess
proc = subprocess.Popen('./simp.py',
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
bufsize=1,
universal_newlines=True)
print('writing')
proc.stdin.write('hey\n')
print('reading')
proc.stdout.readline()
这篇关于子进程stdin缓冲区未在bufsize = 1的换行符上刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!