'Remove traceback in Python on Ctrl-C
Is there a way to keep tracebacks from coming up when you hit Ctrl+c,
i.e. raise KeyboardInterrupt in a Python script?
Solution 1:[1]
Try this:
import signal
import sys
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
This way you don't need to wrap everything in an exception handler.
Solution 2:[2]
Solution 3:[3]
Catch it with a try/except block:
while True:
try:
print "This will go on forever"
except KeyboardInterrupt:
pass
Solution 4:[4]
try:
your_stuff()
except KeyboardInterrupt:
print("no traceback")
Solution 5:[5]
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
Solution 6:[6]
suppress exception using context manager:
from contextlib import suppress
def output_forever():
while True:
print('endless script output. Press ctrl + C to exit')
if __name__ == '__main__':
with suppress(KeyboardInterrupt):
output_forever()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | scrutari |
| Solution 2 | icktoofay |
| Solution 3 | Manny D |
| Solution 4 | ?s??o? |
| Solution 5 | toksaitov |
| Solution 6 | Roman Kazakov |
