gpt4 book ai didi

python - 为什么缓冲来自子进程的标准输出(重定向到无缓冲文件)?

转载 作者:太空狗 更新时间:2023-10-29 20:19:16 26 4
gpt4 key购买 nike

来自 http://docs.python.org/library/functions.html#open

The optional bufsize argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.

我在下面将 0 作为 bufsize 传递,但没有使用 flush(),当我运行 main_process 时没有输出写入文件。
这是什么原因?

# --------------------------------- sub_process.py
import sys
import time

if __name__ == '__main__':
print 'printed from redirect.py'
# why is the following flush() needed? 'std-output' is (?) unbuffered...
sys.stdout.flush()
time.sleep(6)


# --------------------------------- main_process.py
import subprocess
import time

if __name__ == '__main__':
p = subprocess.Popen(
['python', 'sub_process.py'],
stdout=open('std-output', 'w', 0))
time.sleep(3)
p.terminate()

最佳答案

使用带有 -u 标志的 python,例如:

if __name__ == '__main__':
p = subprocess.Popen(
['python', '-u', 'sub_process.py'],
stdout=open('std-output', 'w'))
time.sleep(3)
p.terminate()

关于python - 为什么缓冲来自子进程的标准输出(重定向到无缓冲文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5922554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com