I have the following snippet of code:
    def terminal_command(command, timeout=5*60):
        """Executes a terminal command."""
        cmd = command.split(" ")
        timer = time.strftime('%Hh %Mm %Ss', time.gmtime(timeout))
        proc = None
        try:
            proc = subprocess.run(cmd, timeout=timeout, capture_output=True)
        except subprocess.TimeoutExpired:
            print("Timeout")
            proc.terminate()
            reason = "timeout"
            stdout = b'error'
            stderr = b'error'
        if proc != None:
            # Finished!
            stdout = proc.stdout
            stderr = proc.stderr
            reason = "finished"
        return stdout.decode('utf-8').strip(), stderr.decode('utf-8').strip(), reason
I ran a command which takes significantly longer than 5 minutes. In this instance, subprocess.run raises an exception, but proc is now None so I cannot use proc.terminate(). When the code terminates, as has been well documented elsewhere, the child process continues to run. I would like to terminate it.
Is there any way to terminate a subprocess on a TimeoutExpired, whilst redirecting output? I am on a Linux system so am open to requiring Popen but ideally I would like this to be cross-platform.
