From 996cec42e9621701edb83354232b2c0ca0121560 Mon Sep 17 00:00:00 2001 From: Eric Joanis Date: Thu, 8 Dec 2022 12:49:19 -0500 Subject: [PATCH] Delete temporary files in AudioSegment.export() (#665) * Delete temporary files even when export() AudioSegment.export() has an error * refactor: clean up temp files with a finally block This is a cleaner solution where we don't need to repeat the clean up code, since the finally block executes in all cases. Co-authored-by: James Robert --- pydub/audio_segment.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/pydub/audio_segment.py b/pydub/audio_segment.py index ce141aa9..3b9e2881 100644 --- a/pydub/audio_segment.py +++ b/pydub/audio_segment.py @@ -966,19 +966,20 @@ def export(self, out_f=None, format='mp3', codec=None, bitrate=None, parameters= log_subprocess_output(p_out) log_subprocess_output(p_err) - if p.returncode != 0: - raise CouldntEncodeError( - "Encoding failed. ffmpeg/avlib returned error code: {0}\n\nCommand:{1}\n\nOutput from ffmpeg/avlib:\n\n{2}".format( - p.returncode, conversion_command, p_err.decode(errors='ignore') )) - - output.seek(0) - out_f.write(output.read()) + try: + if p.returncode != 0: + raise CouldntEncodeError( + "Encoding failed. ffmpeg/avlib returned error code: {0}\n\nCommand:{1}\n\nOutput from ffmpeg/avlib:\n\n{2}".format( + p.returncode, conversion_command, p_err.decode(errors='ignore') )) - data.close() - output.close() + output.seek(0) + out_f.write(output.read()) - os.unlink(data.name) - os.unlink(output.name) + finally: + data.close() + output.close() + os.unlink(data.name) + os.unlink(output.name) out_f.seek(0) return out_f