简体   繁体   English

如何以超时终止此子进程?

[英]How do I terminate this subprocess with a timeout?

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). 我知道终止子进程调用的问题已经问过几次了,包括在这里,但是,尝试遵循这些答案,如果脚本挂起,我似乎无法退出(在我的情况下,我正在执行phantomjs脚本) )。 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. 例如,如果我尝试在幻象代码中加载不存在的jquery文件,即使我超时,脚本也会挂起。 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): 我的phantomjs脚本(正在进行中):

var page = require('webpage').create();
page.includeJs("http://localhost/jquery.js",function(){ 
    phantom.exit();
});

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. 我认为您的问题可能是p.communicate()将“ 等待进程终止 ”,这意味着如果脚本挂起,您的计时器将永远无法启动。

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. 在计时器启动后将您的通话移至与之通信(并在kill_proc函数中将process.kill()更改为p.kill()),我认为它将满足您的要求。

As my comment above mentions, Python 3.3's subprocess module functions have a timeout parameter that makes this all happen automatically. 正如我在上面的评论中提到的那样,Python 3.3的子进程模块函数具有一个超时参数,该参数使所有这些自动发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM