Python subprocess.stdout.readline() 挂起 [英] Python subprocess.stdout.readline() hang
问题描述
我在 python 上使用 subprocess 尝试简单的代码,同时调用 process.stdout.readline() 它会挂在它上面.如何解决这个问题呢?在输出中尝试 fcntl 用于非阻塞时,我得到了空白输出.
I try simple code using subprocess on python, while calling process.stdout.readline() it will hang on it. How to solve this problem? While trying fcntl for nonblock in the output I got blank output.
我的源代码:
from subprocess import Popen,PIPE
import fcntl
import os
proc = Popen(['./test'],stdin=PIPE,stdout=PIPE)
fcntl.fcntl(proc.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
print "Started!"
print proc.stdout.readline()
proc.stdin.write('5\n')
proc.stdin.flush()
print proc.stdout.readline()
proc.stdin.write('5\n')
proc.stdin.flush()
print proc.stdout.readline()
proc.stdout.close()
proc.stdin.close()
输出应该是这样的:
First number: 5
Second number: 5
Answer: 10
推荐答案
您想要的输出表明 First number:
之后没有换行符,因此阻塞 proc.stdout.readline()
调用(在 proc.stdin.write('5\n')
行之前)挂起并且非阻塞变体不返回任何内容(空字节串)——没有换行符/EOF还没回来.
Your desired output suggests that there is no newline after First number:
and therefore the blocking proc.stdout.readline()
call (before proc.stdin.write('5\n')
line) hangs and non-blocking variant returns nothing (empty bytestring) -- there is no newline/EOF to return yet.
要修复它,您可以在提示的末尾(在冒号 ':'
处)停止阅读.请参阅子进程 readline 挂起等待 EOF
To fix it, you could stop reading at the end of the prompt (at the colon ':'
). See subprocess readline hangs waiting for EOF
即使提示后有换行符;readline()
可能由于缓冲问题而挂起.参见 Python C 程序子进程在for line in iter"处挂起
Even if there were a newline after the prompt; readline()
may hang due to buffering issues. See Python C program subprocess hangs at "for line in iter"
例如,如果 test
等价于:
For example, if test
is equivalent to:
#!/usr/bin/env python3
a = int(input('First number: '))
b = int(input('Second number: '))
print('Answer:', a + b)
然后要得到答案,您可以使用pexpect
模块::>
then to get the answer, you could use pexpect
module:
#!/usr/bin/env python
import pexpect # $ pip install pexpect
def print_result(locals):
result = int(locals['child'].after.rpartition(b' ')[2])
print(result)
pexpect.run('./test', events={'First number': '5\n', 'Second number': '5\n',
r'Answer:\s*\d+': print_result})
如果你想同时看到输入和输出;您可以设置 logfile=sys.stdout
参数.
If you want to see both input and output; you could set logfile=sys.stdout
parameter.
这篇关于Python subprocess.stdout.readline() 挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!