为什么这段代码在Python3.1 中的行为与Python2.6 中不同?

发布于 2024-08-15 16:39:48 字数 469 浏览 4 评论 0原文

我对编程很陌生,所以如果我的问题太愚蠢,我提前道歉。

#!/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 纠正此问题?

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. This is expected behavior.
But in Python 3.1 execution is blocked at line output=p.stdout.readline().
How to correct this for Python 3.1?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够运 2024-08-22 16:39:48

看来缓冲有区别。添加 p.stdin.flush() 调用解决了问题。 (参见上面的评论)。

社区维基,因为我不应该为这个答案加分,但有些答案需要标记为接受。

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

Appears to be a difference in buffering. Adding a p.stdin.flush() call solved the problem. (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.]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文