Remove traceback in Python on Ctrl-C

有些话、适合烂在心里 提交于 2019-11-30 00:33:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!