问题
Is there a way to keep tracebacks from coming up when you hit Ctrl+c,
i.e. raise KeyboardInterrupt
in a Python script?
回答1:
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..
回答2:
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.
回答3:
Catch the KeyboardInterrupt:
try:
# do something
except KeyboardInterrupt:
pass
回答4:
try:
your_stuff()
except KeyboardInterrupt:
print("no traceback")
回答5:
Catch it with a try/except block:
while True:
try:
print "This will go on forever"
except KeyboardInterrupt:
pass
回答6:
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
回答7:
import sys
try:
print("HELLO")
english = input("Enter your main launguage: ")
print("GOODBYE")
except KeyboardInterrupt:
print("GET LOST")
来源:https://stackoverflow.com/questions/7073268/remove-traceback-in-python-on-ctrl-c