繁体   English   中英

subprocess.wait(timeout=15) 不工作

[英]subprocess.wait(timeout=15) is not working

代码:

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)没有引发异常,而是执行该过程。

我也试过[subprocess.Popen(exe, timeout=15) for exe in execs]但得到错误:

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

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

你可能想要这样的东西来给它们最多 15 秒的并行时间。

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)

暂无
暂无

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

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