Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 421
Kyle Hotchkiss Avatar asked Aug 16 '11 03:08

Kyle Hotchkiss


People also ask

How do I fix Python traceback error?

If there is no variable defined with that name you will get a NameError exception. To fix the problem, in Python 2, you can use raw_input() . This returns the string entered by the user and does not attempt to evaluate it. Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

What is traceback message?

The traceback module works with the call stack to produce error messages. A traceback is a stack trace from the point of an exception handler down the call chain to the point where the exception was raised.

What is traceback library in Python?

Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter. Useful when you want to print the stack trace at any step.

Is traceback an error in Python?

In Python, A traceback is a report containing the function calls made in your code at a specific point i.e when you get an error it is recommended that you should trace it backward(traceback). Whenever the code gets an exception, the traceback will give the information about what went wrong in the code.


2 Answers

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.

like image 99
jleahy Avatar answered Sep 20 '22 17:09

jleahy


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

like image 33
agf Avatar answered Sep 21 '22 17:09

agf