Python 使用 Popen 为子进程使用超时

Python use timeout for subprocess with Popen

Im 运行 以下脚本与 popen

process = subprocess.Popen(['python', 'solver.py', 'newsudoku.csp', '-i', 'arc'], stdout=subprocess.PIPE)
out, err = process.communicate()

我需要处理存储在 out 变量中的输出

这个脚本的执行时间会有所不同,如果超过 60 秒,我需要终止它。我知道 python 3 已超时 check_call,但另一个脚本 im 运行 在 python 2.7

那么我怎么能数到 60 秒然后终止子进程呢?如果发生这种情况,理想情况下也做其他事情(向计数器加 1)

您可以使用timeoutwaitmax 命令对您运行 打开的进程设置时间限制。例如,对于 运行 一个 tail -f 命令最多 10 秒 -

import subprocess
process=subprocess.Popen(['timeout' ,'10', 'tail', '-f', '/var/log/syslog'], stdout=subprocess.PIPE)
out,err = process.communicate()

print out
Apr 26 21:40:01 linubuvma CRON[49447]: (smmsp) CMD (test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp)
Apr 26 21:45:01 linubuvma CRON[50065]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
Apr 26 21:55:01 linubuvma CRON[51271]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
Apr 26 22:00:01 linubuvma CRON[51871]: (smmsp) CMD (test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp)
Apr 26 22:05:01 linubuvma CRON[52491]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
Apr 26 22:09:01 linubuvma CRON[52975]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -x /usr/lib/php5/sessionclean ] && [ -d /var/lib/php5 ] && /usr/lib/php5/sessionclean /var/lib/php5 $(/usr/lib/php5/maxlifetime))
Apr 26 22:15:01 linubuvma CRON[53707]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
Apr 26 22:17:01 linubuvma CRON[53951]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Apr 26 22:20:01 linubuvma CRON[54311]: (smmsp) CMD (test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp)
Apr 26 22:25:01 linubuvma CRON[54937]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)

tail 命令恰好在 10 秒后终止。

你也可以在 python 3.7.4:

中做类似的事情
p1 = subprocess.Popen(['python', 'solver.py', 'newsudoku.csp', '-i', 'arc'], stderr = subprocess.PIPE) 
    try:
        outs, errs = p1.communicate(timeout=60) # will raise error and kill any process that runs longer than 60 seconds
    except subprocess.TimeoutExpired as e:
        p1.kill()
        outs, errs = p1.communicate()
        print(outs)
        print(errs)