子进程在设置的时间量后未终止

2024-09-27 07:16:59 发布

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

我一直在使用Python对大量的.mp4文件集运行一个视频处理程序。视频处理程序(我没有编写也无法更改)在到达视频的最后一帧时不会退出,因此在循环中使用os.system(cmd)遍历所有的.mp4文件对我不起作用,除非我在每个视频结束后坐在那里终止处理程序。在

我试图用一个子进程来解决这个问题,这个子进程在视频结束后终止(预定的时间量):

for file in os.listdir(myPath):
    if file.endswith(".mp4"):
        vidfile = os.path.join(myPath, file)
        command = "./Tracking " + vidfile
        p = subprocess.Popen(command, shell=True)
        sleep(840)
        p.terminate()

但是,Tracking程序仍然没有退出,所以我最终同时打开了大量的视频。我只能通过强制退出每个单独的帧或使用kill -9 id作为程序特定实例的id来消除它们。我读过不推荐使用shell=True,但我不确定这是否会导致这种行为。在

在一段时间后,如何终止Tracking程序?我对Python非常陌生,不知道如何做到这一点。我正考虑在sleep()之后执行类似os.system("kill -9 id")的操作,但我也不知道如何获得程序的id。在


Tags: 文件程序id处理程序视频进程osshell
1条回答
网友
1楼 · 发布于 2024-09-27 07:16:59

删除shell=True,使用p.kill()终止进程:

import subprocess
from time import time as timer, sleep

p = subprocess.Popen(["./Tracking", vidfile])
deadline = timer() + 840
while timer() < deadline:
    if p.poll() is not None: # already finished
        break
    sleep(1)
else: # timeout
    try:
        p.kill()
    except EnvironmentError:
        pass # ignore errors
    p.wait()

如果它没有帮助,那么尝试创建一个新的进程组并终止它。见How to terminate a python subprocess launched with shell=True。在

相关问题 更多 >

    热门问题