I was wondering if there is a way to stop recording and export that recording in the finally: statement in python. Example: let’s say I’m recording then all of a sudden my script crashes while I’m recording, would there be a way to stop recording and exporting that were to happen? I’ve tried making a separate function that exports and stops recording and have that run on finally:, but that didn’t work, it just made a new file. Any help would be appreciated. My code is below: import pyaudio import wave import time import signal from datetime import datetime # Configuration CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 10 # Initialize PyAudio audio = pyaudio.PyAudio() def record_audio(filename): stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("Recording started") frames = [] data = stream.read(CHUNK) frames.append(data) print("Recording stopped") stream.stop_stream() stream.close() # Save to WAV file wf = wave.open(filename, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(audio.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close() def main(): try: while True: timestamp = datetime.now().strftime("%m-%d-%Y_%H-%M-%S") wav_filename = f"/home/henrikkoehler/Desktop/Audio_Files/{timestamp}.wav" record_audio(wav_filename) print(f"Audio saved to {wav_filename}") # Wait a bit to avoid multiple recordings from a single press time.sleep(1) except KeyboardInterrupt: print("Exiting...") except: time.sleep(1) t_end = time.time() + 15 * 1 while time.time() < t_end: print("Error! Restart!") finally: audio.terminate() if __name__ == "__main__": main() Continue reading...