tags:

views:

429

answers:

3

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 ctrl+c to stop the program. Is there any way around this?

+2  A: 

If it is running in the Python shell use Ctrl + Z, otherwise locate the python process and kill it.

Andrew Hare
`^Z` --> `[1]+ Stopped ` --> `kill %1` to stop job #1 (or job %1 as bash puts it)
kaizer.se
+4  A: 

The only sure way is to use Ctrl-Break. Stops every python script instantly!

Denis M
It works, thanks
jonatron
What is `Break`? How do I type it?
kaizer.se
There should be a Pause_Break button on your keyboard
jonatron
What if there isn't? I'm on a Intel Macbook, and it doesn't have a very full-featured keyboard.
Bluu
+2  A: 

Pressing Ctrl + c while a python program is running will cause python to raise a KeyboardInterupt 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 KeyboardInterupt 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
try:
  #Some stuff might raise an IO exception
except:
  #Code that ignores errors

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

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

David Locke