【问题标题】:Why does input flush stdout为什么输入刷新标准输出
【发布时间】:2019-11-22 06:58:21
【问题描述】:

当我创建一个子进程并通过标准输入和标准输出进行通信时,除非我刷新缓冲区或执行输入(),否则消息不会到达。

所以我想知道 input() 是否刷新缓冲区,如果是,我想知道为什么。

# file1
import subprocess
import time
import select

process = subprocess.Popen(['python3',  'file2.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

read_ready, _, _ = select.select([process.stdout], [], [])
message = read_ready[0].readline().decode()
print(message)

time.sleep(11)

process.kill()

-

# file2
import sys
import time

print('1')

message = input()

# I added the sleep because the buffer gets flushed if the program stops
time.sleep(10)

如果我执行此代码,它会立即打印 1。如果我用 input() 注释掉该行,那么我需要等到文件关闭

【问题讨论】:

    标签: python-3.x input flush


    【解决方案1】:

    是的,input() 函数会刷新缓冲区。如果您考虑一下,它必须 - 该函数的目的是向用户显示提示,然后询问他们的输入,并且为了确保用户看到提示,需要刷新打印缓冲区。

    【讨论】:

    • 啊,是的,这很有意义。我忘记了输入也会打印一些东西
    猜你喜欢
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多