subprocess.wait(timeout = 15)不起作用 [英] subprocess.wait(timeout=15) is not working

查看:105
本文介绍了subprocess.wait(timeout = 15)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

import os
import subprocess


execs = ['C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\Multiof2.exe', # --> Child 1
         'C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\Multiof5.exe', # --> Child 2
         'C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\Multiof10.exe',...] # --> Child 3 and more
print('Parent Process id : ', os.getpid())
process = [subprocess.Popen(exe) for exe in execs]
for proc in process:
    try:
        proc.wait(timeout=15)
        print('Child Process id : ', proc.pid)
        if proc.returncode == 0:
            print(proc.pid, 'Exited')

    except subprocess.TimeoutExpired:
        proc.terminate()
        print('Child Process with pid',proc.pid ,'is killed')

某些子进程将花费15秒钟以上的时间来执行.因此,我必须终止进程超时.但是 proc.wait(timeout = 15)不会引发异常,而是执行该过程.

Some Child Processes will take more than 15 sec to execute. So, I have to kill the process which timeout. But proc.wait(timeout=15) is not raising an exception instead it executes the process.

我也尝试了 [exec中exe的subprocess.Popen(exe,timeout = 15)] ,但得到了错误:

I also tried [subprocess.Popen(exe, timeout=15) for exe in execs] but got Error:

TypeError: __init__() got an unexpected keyword argument 'timeout'

推荐答案

您不是在等待并行的进程-您要给他们每个连续15秒的时间来做他们的事情.

You're not waiting for the processes in parallel - you're giving them each a sequential 15 seconds to do their thing.

您可能希望像这样使所有这些并行达到15秒.

You might want something like this to give all of them up to 15 seconds in parallel.

import os
import subprocess
import time


execs = [
    "C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\Multiof2.exe",
    "C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\Multiof5.exe",
    "C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\Multiof10.exe",
]
print("Parent Process id : ", os.getpid())
process = [subprocess.Popen(exe) for exe in execs]
start_time = time.time()
while True:
    elapsed_time = time.time() - start_time
    any_alive = False
    for proc in process:
        ret = proc.poll()
        if ret is None:  # still alive
            if elapsed_time >= 15:
                print("Killing:", proc.pid)
                proc.terminate()
            any_alive = True
    if not any_alive:
        break
    time.sleep(1)

这篇关于subprocess.wait(timeout = 15)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆