在监视文件大小的同时执行子流程



我正在执行一个生成文件的子流程。但是,我想确保生成的文件不会大于特定的大小。因为我无法提前知道文件的大小,所以我想执行子流程,并在文件达到一定大小时终止它。类似于:

while os.path.getsize(path_to_file) < max_file_size:
cmd_csound=subprocess.Popen(['exec', path_to_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

您需要一个循环来检查文件大小并相应地处理它,类似

import os
import subprocess
import time
max_size = 1024
path_to_file = "..."
csound_proc = subprocess.Popen(['csound', ..., path_to_file])
try:
while True:
if csound_proc.poll() is not None:
break  # process exited
if os.path.isfile(path_to_file) and os.stat(path_to_file).st_size > max_size:
raise RuntimeError("Oh no, file big.")
time.sleep(.5)
finally:
csound_proc.kill()

因此,您需要循环,直到(a(进程退出,或者(b(文件过大。你需要这样的东西:

cmd_csound=subprocess.Popen(['exec', path_to_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while cmd_csound.returncode is None:
if os.path.getsize(path_to_file) > max_file_size:
cmd_csound.kill()
break
time.sleep(1)
cmd_csound.poll()

最新更新