[英]Why does this code behave differently in Python3.1 than in Python2.6?
I'm very new to programming so I apologize in advance if my question is too silly. 我对编程很陌生,所以如果我的问题太傻,我会事先道歉。
#!/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)
Executing this code in Python 2.6 prints letters a, b, c, d , each line of output appears after a second. 在Python 2.6中执行此代码会打印字母a,b,c,d,每行输出一秒钟后出现。 This is expected behavior. 这是预期的行为。 But in Python 3.1 execution is blocked at line output=p.stdout.readline()
. 但是在Python 3.1中,在line output=p.stdout.readline()
处阻止了执行。 How to correct this for Python 3.1? 如何为Python 3.1更正此问题?
Appears to be a difference in buffering. 似乎是缓冲的差异。 Adding a p.stdin.flush()
call solved the problem. 添加p.stdin.flush()
调用解决了这个问题。 (See the comments above). (见上面的评论)。
Community wiki as I deserve no credits for this answer, but some answer needs to be marked accepted. 社区维基因为这个答案我没有得到任何学分,但有些答案需要被标记为已被接受。
[@Geo Pop: Please "accept" this question, as it apparently is correct.] [@Geo Pop:请“接受”这个问题,因为它显然是正确的。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.