Remove traceback in Python on Ctrl-C

2019-02-11 16:28发布

Is there a way to keep tracebacks from coming up when you hit Ctrl+c, i.e. raise KeyboardInterrupt in a Python script?

7条回答
再贱就再见
2楼-- · 2019-02-11 16:52

Catch it with a try/except block:

while True:
   try:
      print "This will go on forever"
   except KeyboardInterrupt:
      pass
查看更多
男人必须洒脱
3楼-- · 2019-02-11 16:53

Try this:

import signal
signal.signal(signal.SIGINT, lambda x,y: sys.exit(0))

This way you don't need to wrap everything in an exception handler.

查看更多
干净又极端
4楼-- · 2019-02-11 16:54
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..

查看更多
老娘就宠你
5楼-- · 2019-02-11 16:54

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
查看更多
Animai°情兽
6楼-- · 2019-02-11 16:56
import sys
try:
    print("HELLO")
    english = input("Enter your main launguage: ")
    print("GOODBYE")
except KeyboardInterrupt:
    print("GET LOST")
查看更多
女痞
7楼-- · 2019-02-11 17:00

Catch the KeyboardInterrupt:

try:
    # do something
except KeyboardInterrupt:
    pass
查看更多
登录 后发表回答