0

I have the code below in a Python module; it uses subprocess to start a command line app and reads the output the app writes to stdout.

If the command line app doesn't complete after 15 seconds, I want the code to time out. I have used signal.alarm to try to achieve this.

When testing the module without Django it times out after 15s as expected. However, when I call the code from a Django view it doesn't timeout after 15s, but continues to run until the spawned process times out.

How can I get this to do what I want?

p = get_process() # spawns a process using subproccess and returns the process handle

signal.signal(signal.SIGALRM, alarm_handler)                           
signal.alarm(15)   
try:
    s= p.stdout.read()
except:
    p.kill()
    s = "Operation timed out"
TonyM
  • 708
  • 1
  • 8
  • 15
  • 3
    Maybe Django is running your code in a distinct thread? The interrupt will always occur in the main thread, which might not be your code. – Thomas K Apr 02 '12 at 12:28

2 Answers2

1

This approach, of just spawning a thread for running the subprocess and using a timeout on joining said thread, should avoid any problems with interrupts occurring in the wrong thread and also work on Windows.

Community
  • 1
  • 1
Danica
  • 28,423
  • 6
  • 90
  • 122
0

Consider using select() call which allows you to specify a timeout for the I/O operation(s).

9000
  • 39,899
  • 9
  • 66
  • 104
  • 1
    Just keep in mind that using `select()` with pipes for redirected I/O only works on UNIX-like systems and will not work on Windows, where `select()` only works on sockets. This might or might not be a problem (no OS was specified in the question). – André Caron Apr 02 '12 at 19:34