【问题标题】:subprocess run in background and write output line by line to a file子进程在后台运行并将输出逐行写入文件
【发布时间】:2026-02-10 07:45:02
【问题描述】:

我有两个文件:

main.py

import subprocess
import shlex


def main():
    command = 'python test_output.py'
    logfile =  open('output', 'w')
    proc = subprocess.Popen(shlex.split(command), stdout=logfile)


if __name__ == "__main__":
    main()

test_output.py

from time import sleep
import os

for i in range(0, 30):
    print("Slept for => ", i+1, "s")
    sleep(1)
os.system("notify-send completed -t 1500")

一旦子进程完成,进程的输出就会写入logfile。有什么办法:

  1. 从 main 启动子进程并退出它(就像现在一样)。
  2. 继续在后台运行子进程。
  3. 当子进程产生输出时,立即将其写入logfile。 (不要像现在这样等待子进程完成。)

还有其他问题 (like this one) 给出了逐行阅读的解决方案,但它们使main.py 等待。是否可以在后台执行所有操作,而无需让 main.py 等待?

【问题讨论】:

    标签: python file subprocess pipe


    【解决方案1】:

    作为子进程的文件处理程序的两个缓冲区都可以设置为'line-buffering',其中换行符会导致每个对象的缓冲区被转发。这是通过将缓冲区参数设置为1 来完成的,请参见open() 命令和subprocess

    您需要确保子进程不会自行缓冲。看到你也在运行一个 Python 脚本,你要么需要在代码中实现它,比如 flush=True 用于打印语句:

    print(this_and_that, flush=True)
    

    Source

    Credit

    【讨论】:

      最近更新 更多