Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture keyboardinterrupt in Python without try-except

Is there some way in Python to capture KeyboardInterrupt event without putting all the code inside a try-except statement?

I want to cleanly exit without trace if user presses Ctrl+C.

like image 492
Alex Avatar asked Nov 17 '10 14:11

Alex


People also ask

How do I get KeyboardInterrupt in Python?

In Python, there is no special syntax for the KeyboardInterrupt exception; it is handled in the usual try and except block. The code that potentially causes the problem is written inside the try block, and the 'raise' keyword is used to raise the exception, or the python interpreter raises it automatically.

Does except exception catch KeyboardInterrupt?

KeyboardInterrupt exception inherits the BaseException and similar to the general exceptions in python, it is handled by try except statement in order to stop abrupt exiting of program by interpreter. As seen above, KeyboardInterrupt exception is a normal exception which is thrown to handle the keyboard related issues.

How do I use KeyboardInterrupt?

The KeyboardInterrupt error occurs when a user manually tries to halt the running program by using the Ctrl + C or Ctrl + Z commands or by interrupting the kernel in the case of Jupyter Notebook. To prevent the unintended use of KeyboardInterrupt that often occurs, we can use exception handling in Python.

How do I use Ctrl C in Python?

Python allows us to set up signal -handlers so when a particular signal arrives to our program we can have a behavior different from the default. For example when you run a program on the terminal and press Ctrl-C the default behavior is to quit the program.


2 Answers

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal import sys import time import threading  def signal_handler(signal, frame):     print('You pressed Ctrl+C!')     sys.exit(0)  signal.signal(signal.SIGINT, signal_handler) print('Press Ctrl+C') forever = threading.Event() forever.wait() 
like image 124
Johan Kotlinski Avatar answered Oct 22 '22 14:10

Johan Kotlinski


If all you want is to not show the traceback, make your code like this:

## all your app logic here def main():    ## whatever your app does.   if __name__ == "__main__":    try:       main()    except KeyboardInterrupt:       # do nothing here       pass 

(Yes, I know that this doesn't directly answer the question, but it's not really clear why needing a try/except block is objectionable -- maybe this makes it less annoying to the OP)

like image 33
bgporter Avatar answered Oct 22 '22 15:10

bgporter