#!/usr/bin/env python import subprocess def run_tunnel(): process = subprocess.Popen( ['/root/code', 'tunnel'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) with process.stdout: try: for line in iter(process.stdout.readline, ''): print(line, end='') except KeyboardInterrupt: print('KeyboardInterrupt') finally: process.terminate() try: # Give some time to gracefully shutdown returncode = process.wait(timeout=5) except subprocess.TimeoutExpired: print('Timeout expired, sending SIGKILL') process.kill() returncode = process.wait() print(f'Process finished with {returncode}') if __name__ == '__main__': run_tunnel()