Why does subprocess.run() have unexpected behavior in try else block?

37 Views Asked by At

Trying to make a "to mp4" converter function using ffmpeg that is going to convert a file to mp4, delete the original file, and return True or False for specific conditions. But I get some unexpected behavior of a subprocess.

Initially I used this construction:

def to_mp4_converter(file):

    input_file = file
    output_file = f"{re.sub(r'\..+$', "", file)}.mp4"

    try:
        subprocess.run(['ffmpeg', '-i', input_file, output_file])
    except subprocess.SubprocessError as e:
        print(f"Subprocess Error: {e}")
        return False
    else:
        try:
            os.remove(path=file)
        except OSError as e:
            print(f"Can't remove {file} file: {e}")
        finally:
            return True

Original file is removed, but output file is half of the expected size and quality of video is low.

But if I place subprocess.run() and os.remove() into separate try else blocks like that:

def to_mp4_converter(file):

    input_file = file
    output_file = f"{re.sub(r'\..+$', "", file)}.mp4"

    try:
        subprocess.run(['ffmpeg', '-i', input_file, output_file])
    except subprocess.SubprocessError as e:
        print(f"Subprocess Error: {e}")
        return False
    else:
        pass

    try:
        os.remove(path=file)
    except OSError as e:
        print(f"Can't remove {file} file: {e}")
    finally:
        return True

Everything works fine.

Isn't subprocess.run() should be a blocking operation, so the else statement in 1st example is unreachable until conversion is done?

0

There are 0 best solutions below