OILS / demo / cpython / keyboard_interrupt.py View on Github | oilshell.org

39 lines, 22 significant
1#!/usr/bin/env python2
2"""
3keyboard_interrupt.py: How to replace KeyboardInterrupt
4"""
5from __future__ import print_function
6
7import signal
8import sys
9import time
10
11
12
13g_sigint = False
14
15def SigInt(x, y):
16 print('SIGINT')
17 global g_sigint
18 g_sigint = True
19
20
21def main(argv):
22
23 # This suppresses KeyboardInterrupt. You can still do Ctrl-\ or check a flag
24 # and throw your own exception.
25 signal.signal(signal.SIGINT, SigInt)
26
27 while True:
28 print('----')
29 time.sleep(0.5)
30 if g_sigint:
31 raise Exception('interrupted')
32
33
34if __name__ == '__main__':
35 try:
36 main(sys.argv)
37 except RuntimeError as e:
38 print('FATAL: %s' % e, file=sys.stderr)
39 sys.exit(1)