【问题标题】:Why does this code behave differently in Python3.1 than in Python2.6?为什么这段代码在 Python3.1 中的行为与在 Python2.6 中的行为不同?
【发布时间】: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


【解决方案1】:

似乎在缓冲方面有所不同。添加p.stdin.flush() 电话解决了这个问题。 (参见上面的 cmets)。

社区 wiki,因为我的这个答案不值得赞扬,但需要将某些答案标记为已接受。

[@Geo Pop:请“接受”这个问题,因为它显然是正确的。]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多