1 | #!/usr/bin/env python2
|
2 | """
|
3 | keyboard_interrupt.py: How to replace KeyboardInterrupt
|
4 | """
|
5 | from __future__ import print_function
|
6 |
|
7 | import signal
|
8 | import sys
|
9 | import time
|
10 |
|
11 |
|
12 |
|
13 | g_sigint = False
|
14 |
|
15 | def SigInt(x, y):
|
16 | print('SIGINT')
|
17 | global g_sigint
|
18 | g_sigint = True
|
19 |
|
20 |
|
21 | def 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 |
|
36 | if __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)
|