子进程在后台运行,并逐行将输出写入文件

问题描述 投票:0回答:1

我有两个文件:

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个回答
0
投票

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

您需要确保子进程不会自行缓冲。通过看到你也在运行Python脚本,你需要在那里的代码中实现它,比如flush = True表示print语句:

print(this_and_that, flush=True)

Source

Credit

© www.soinside.com 2019 - 2024. All rights reserved.