如何在Python中跳过带有子进程的错误消息弹出窗口

2024-04-24 11:40:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python中的subprocess调用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个流程仍在继续,但整个流程最终会停留在“子流程部分”,无法继续前进。(除非我来到我的办公桌,手动点击“关闭程序”)

我想知道的是如何避免弹出窗口,让整个脚本过程继续进行,比如绕过错误消息之类的,而不是手动单击,以避免浪费时间。你知道吗


Tags: ofin程序进程assome流程codes
1条回答
网友
1楼 · 发布于 2024-04-24 11:40:53

由于我们对FAST_worker正在调用的程序了解不够,我假设您已经检查了脚本中没有更方便使用的“出错时杀死”或“安静”模式。你知道吗

我的二分钱:也许你可以在worker执行上设置一个超时,这样一个卡住的进程在一定的延迟后会自动终止。你知道吗

here提供的代码片段的基础上,这里有一个草稿:

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自动化库可以为您执行单击操作,但编程可能会更加繁琐:

相关问题 更多 >