import os
import fcntl
import time
from subprocess import Popen, PIPE
def setNonBlocking(fd):
"""
Set the file description of the given file descriptor to non-blocking.
"""
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
flags = flags | os.O_NONBLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
p = Popen("./a.out", stdin = PIPE, stdout = PIPE, stderr = PIPE, bufsize = 1)
setNonBlocking(p.stdout)
setNonBlocking(p.stderr)
while True:
try:
time.sleep(.1) //wait for writing complete
out1 = p.stdout.read()
except IOError:
pass
else:
print out1
if p.poll() == 0:
break
line = raw_input()
p.stdin.write(line)
p.stdin.write('\n')
p.stdin.flush()
使用python进行交互式输入/输出。 a.out是一个小型C ++程序,它输入a,b和输出a + b。代码没问题。但我认为如果a.out是一个大程序,并且需要超过0.1秒才能执行。我应该改变下面的一行。
time.sleep(.1)
我想检查我们当前是否正在写入管道。所以我可以像下面这样做。
while pipe is writing:
continue;
我是Python的新手。我整天都在google,但未能解决问题。谁能帮我?非常感谢你!
答案 0 :(得分:0)
请勿将p.stdout
设置为非阻止。这样p.stdout.read()
将自动使程序等到子进程的输出准备就绪。