[英]subprocess.wait(timeout=15) is not working
Code:代码:
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')
Some Child Processes will take more than 15 sec to execute.一些子进程将需要超过 15 秒才能执行。 So, I have to kill the process which timeout.
所以,我必须杀死超时的进程。 But
proc.wait(timeout=15)
is not raising an exception instead it executes the process.但是
proc.wait(timeout=15)
没有引发异常,而是执行该过程。
I also tried [subprocess.Popen(exe, timeout=15) for exe in execs]
but got Error:我也试过
[subprocess.Popen(exe, timeout=15) for exe in execs]
但得到错误:
TypeError: __init__() got an unexpected keyword argument 'timeout'
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.你可能想要这样的东西来给它们最多 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.