Is there a way to keep tracebacks from coming up when you hit Ctrl+c,
i.e. raise KeyboardInterrupt in a Python script?
25
votes
7 Answers
31
votes
import sys
try:
# your code
except KeyboardInterrupt:
sys.exit(0) # or 1, or whatever
Is the simplest way, assuming you still want to exit when you get a Ctrl+c.
If you want to trap it without a try/except, you can use a recipe like this using the signal module, except it doesn't seem to work for me on Windows..
39
votes
7
votes
2
votes
1
votes
Also note that by default the interpreter exits with the status code 128 + the value of SIGINT on your platform (which is 2 on most systems).
import sys, signal
try:
# code...
except KeyboardInterrupt: # Suppress tracebacks on SIGINT
sys.exit(128 + signal.SIGINT) # http://tldp.org/LDP/abs/html/exitcodes.html