import sys import subprocess import time def wait_and_print(): """Do nothing for 5 seconds except print something each second""" for i in range(5): print("waited ", i, flush=True) time.sleep(1) def start_grandchild(): """Start a subprocess to run wait_and_print""" subprocess.run([sys.executable, __file__, "wait_and_print"]) def run_with_timeout(function, timeout=None): """Run a function in this file with subprocess.run and a timeout of 1 second. Print the stdout of the process if it completed or timed out""" try: p = subprocess.run([sys.executable, __file__, function], stdout=subprocess.PIPE, timeout=timeout) print("Finished: ", repr(p.stdout)) except subprocess.TimeoutExpired as e: print("Timeout: ", repr(e.stdout)) if __name__ == "__main__": if(len(sys.argv) > 1): # If we have an argument interpret it as function name to execute func = sys.argv[1] globals()[func](*sys.argv[2:]) sys.exit(0) # Ok, if we run wait_and_print() in a subprocess with timeout we will get a # Timeout: b'waited 0\n' run_with_timeout("wait_and_print") # But if we run the start_grandchild() in a subprocess it will wait for the # grandchild to be completed and thus we get # Timeout: b'waited 0\nwaited 1\nwaited 2\nwaited 3\nwaited 4\n run_with_timeout("start_grandchild")