1

I know the question on terminating a subprocess call has been asked a few times, including here but, trying to follow those answers, I can't seem to get mine to exit if the script hangs (in my case I am executing a phantomjs script). For instance, if I try to load a non-existent jquery file in my phantom code, the script will hang, even though I have a timeout. Here's my code:

def kill_proc():
    if p.poll() != 0:
        process.kill()


p = subprocess.Popen(['phantomjs','file.js'],stdout=subprocess.PIPE)
    out, phantomError = p.communicate()

t = Timer(5, kill_proc) # should kill it after 5 seconds
t.start()
p.wait()

My phantomjs script (a work in progress):

var page = require('webpage').create();
page.includeJs("http://localhost/jquery.js",function(){ 
    phantom.exit();
});
Community
  • 1
  • 1
kristen
  • 478
  • 2
  • 10
  • 34
  • 1
    If you can update to Python 3.3 the [subprocess](http://docs.python.org/3/library/subprocess.html) module's functions gained a `timeout` parameter that can do this automatically. – bbayles Apr 13 '13 at 20:03

1 Answers1

1

I think your problem might be that p.communicate() will "Wait for process to terminate" , meaning your timer never actually gets to start if the script hangs.

Move your call to communicate to after the start of the timer (and change process.kill() to p.kill() in the kill_proc function) and I think it will do what you want.

As my comment above mentions, Python 3.3's subprocess module functions have a timeout parameter that makes this all happen automatically.

bbayles
  • 4,389
  • 1
  • 26
  • 34