Stopping python using ctrl+c


I have a python script that uses threads and makes lots of HTTP requests. I think what's happening is that while a HTTP request (using urllib2) is reading, it's blocking and not responding to CtrlC to stop the program. Is there any way around this?

3/18/2015 6:35:43 AM

Accepted Answer

On Windows, the only sure way is to use CtrlBreak. Stops every python script instantly!

(Note that on some keyboards, "Break" is labeled as "Pause".)

1/21/2018 9:41:21 PM

Pressing Ctrl + c while a python program is running will cause python to raise a KeyboardInterrupt exception. It's likely that a program that makes lots of HTTP requests will have lots of exception handling code. If the except part of the try-except block doesn't specify which exceptions it should catch, it will catch all exceptions including the KeyboardInterrupt that you just caused. A properly coded python program will make use of the python exception hierarchy and only catch exceptions that are derived from Exception.

#This is the wrong way to do things
  #Some stuff might raise an IO exception
  #Code that ignores errors

#This is the right way to do things
  #Some stuff might raise an IO exception
except Exception:
  #This won't catch KeyboardInterrupt

If you can't change the code (or need to kill the program so that your changes will take effect) then you can try pressing Ctrl + c rapidly. The first of the KeyboardInterrupt exceptions will knock your program out of the try block and hopefully one of the later KeyboardInterrupt exceptions will be raised when the program is outside of a try block.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow