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 | 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 |
|
34 | if __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)
|