pythontracebackkeyboardinterrupt

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

  • 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..