1. Stefan Scherfke
  2. subproc_handling

Source

subproc_handling / ctrl_c.py

"""
Pressing Ctrl-C on the keyboard results in a ``KeyboardInterrupt`` which
is automatically forwarded to all subprocesses.

Works on:

- Linux
- OS X
- Windows

"""
import subprocess
import sys
import time


def parent():
    print('parent started')
    proc = subprocess.Popen(['python', 'ctrl_c.py', 'child'])
    try:
        time.sleep(60)
    except KeyboardInterrupt:
        print('parent waiting for child')
        proc.wait()
        print('parent terminating')


def child():
    print('child started')
    try:
        time.sleep(60)
    except KeyboardInterrupt:
        print('child terminating')


if __name__ == '__main__':
    if len(sys.argv) > 1:
        child()
    else:
        parent()