Search code examples
pythonsubprocesspopenfilesize

Execute subprocess while monitoring file size


I'm executing a subprocess that generates a file. However I want to make sure the file generated won't be larger than a specific size. Because I can't know in advance how large the file will be I'd like to execute the subprocess and terminate it if the file reaches a certain size. Something like:

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

Solution

  • You'll need a loop to check the file size and deal with it accordingly, something like

    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()