我有两个文件:
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
。有没有办法:
logfile
。 (不要等待子进程完成,就像现在一样。)还有其他问题(like this one),其中解决方案是逐行阅读,但他们让main.py
等待。是否可以在后台执行所有操作,而无需保持main.py等待?
作为子进程的filehandler的缓冲区都可以设置为'line-buffering',其中换行符会导致每个对象的缓冲区被转发。这可以通过将buffer参数设置为1
来完成,请参阅open()命令和subprocess。
您需要确保子进程不会自行缓冲。通过看到你也在运行Python脚本,你需要在那里的代码中实现它,比如flush = True表示print语句:
print(this_and_that, flush=True)