我在Python中使用Python调用WINDOWS上的外部程序。我用ThreadPool控制这个进程,这样我可以将它限制在最大的6个进程同时,当一个进程被完成时,新的进程不断地开始。
守则如下:
### some codes above
### Code of Subprocess Part
from multiprocessing.pool import ThreadPool as Pool
def FAST_worker(file):
p = subprocess.Popen([r'E:/pyworkspace/FAST/FAST_RV_W64.exe', file],
cwd = r'E:/pyworkspace/FAST/',
shell = True)
p.wait()
# List of *.in filenames
FAST_in_pathname_li = [
'334.in',
'893.in',
'9527.in',
...
'114514.in',
'1919810.in',
]
# Limit max 6 processes at same time
with Pool(processes = 6) as pool:
for result in pool.imap_unordered(FAST_worker, FAST_in_pathname_li):
pass
### some codes below当外部程序意外终止并显示错误消息弹出时,我遇到了问题.尽管其他5个进程仍在继续,但整个进程最终将陷入“子流程部分”,无法继续前进。(除非我来到办公桌前,手动单击“关闭程序”)
我想知道的是,如何避免弹出,使整个脚本过程继续进行,比如绕过错误消息或其他什么,而不是手动单击,以避免浪费时间。
发布于 2019-09-16 12:39:49
由于我们对FAST_worker正在调用的程序还不太了解,所以我假设您已经检查过了,没有任何在脚本中使用更方便的“杀死错误”或“安静”模式。
我的两分钱:也许您可以在工作人员执行时设置一个超时,以便在某个延迟之后自动终止被卡住的进程。
在这里提供的片段的基础上,下面是一个草案:
from threading import Timer
def FAST_worker(file, timeout_sec):
def kill_proc():
"""called by the Timer thread upon expiration"""
p.kill()
# maybe add task to list of failed task, for tracability
p = subprocess.Popen([r'E:/pyworkspace/FAST/FAST_RV_W64.exe', file],
cwd = r'E:/pyworkspace/FAST/',
shell = True)
# setup timer to kill the process after a timeout
timer = Timer(timeout_sec, kill_proc)
try:
timer.start()
stdout, stderr = p.wait()
finally:
timer.cancel()请注意,python中也有GUI自动化库,可以为您执行单击操作,但编写程序可能会更加繁琐:
https://stackoverflow.com/questions/57956209
复制相似问题