【发布时间】:2010-12-28 13:08:25
【问题描述】:
我对编程很陌生,所以如果我的问题太愚蠢,我提前道歉。
#!/usr/bin/python2.6
import subprocess, time
p=subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for i in 'abcd':
p.stdin.write(str.encode(i+'\n'))
output=p.stdout.readline()
print(output)
time.sleep(1)
在 Python 2.6 中执行此代码会打印字母 a、b、c、d ,每行输出会在一秒钟后出现。这是预期的行为。
但在 Python 3.1 中,执行在行 output=p.stdout.readline() 处被阻止。
如何为 Python 3.1 更正此问题?
【问题讨论】:
-
当执行被阻塞时究竟会发生什么?您有可以显示的错误吗?
-
不是错误,只是提示输入;此代码是在终端窗口中执行的
-
猜测可能是缓冲不同;如果在写入后添加对 p.stdin.flush 的调用,会发生什么变化吗?
-
非常感谢,您回答了我的问题;添加 p.stdin.flush() 解决我的问题
标签: python subprocess stdout stdin popen