tags:

views:

76

answers:

2

I have a python script which is freezing (I think it stalls waiting for socket data somewhere), but I am having trouble getting a backtrace because the only way to stop it is to kill the process in. There is a timeout on the socket also, but it doesn't seem to work.

I am hoping that Python has a feature like PHP's set_time_limit() function which can stop the script and give me a useful backtrace, perhaps showing a sock.recv() call which is frozen, or an endless loop somewhere.

+3  A: 

signal.alarm can help (on Unix platforms), but (depending on the platform) there may be uninterruptable system calls (and if I get the docs right, on Unix, PHP's set_time_limit does not count time spent in system calls, so a hanging system call would be a problem there too).

Alex Martelli
Do you think signal.alarm will give him the backtrace he mentioned?
Gattster
SIGALRM (or any other signal) can be handled (via signal.signal) by a handler function that gets called with the current stack frame as the second argument, so of course it's feasible (among other things) to do a stack trace from there.
Alex Martelli
+1  A: 

You could set a timeout on your sockets instead.

import socket
socket.setdefaulttimeout(10) #10 seconds

Do that at the start of your program and everything making socket connections should respect it.

Gattster