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

41 lines, 23 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 old = signal.signal(signal.SIGINT, SigInt)
26 # We may want to restore the old handler!
27 print(old)
28
29 while True:
30 print('----')
31 time.sleep(0.5)
32 if g_sigint:
33 raise Exception('interrupted')
34
35
36if __name__ == '__main__':
37 try:
38 main(sys.argv)
39 except RuntimeError as e:
40 print('FATAL: %s' % e, file=sys.stderr)
41 sys.exit(1)