gpt4 book ai didi

python - 如何使用 python 检查状态或终止外部进程

转载 作者:太空狗 更新时间:2023-10-29 21:53:34 26 4
gpt4 key购买 nike

我有一个在我的网络服务器上运行的 python 脚本。然后调用 main 函数,当它返回时它只是休眠几秒钟然后再次调用。它的目的是拾取用户添加的任何新上传的视频并将它们转换为 webm,拉出中间框架作为图像和一堆其他时髦的东西。我正在使用对 ffmpeg 的外部调用。下面的代码片段显示了我是如何调用它的。

    duration = output[durationIndex+10:durationIndex+18]
durationBits = duration.split(":")
lengthInSeconds = (int(durationBits[0])*60*60) + (int(durationBits[1])*60) + (int(durationBits[2]))

child = subprocess.Popen(["ffmpeg","-y","-i",sourceVideo,"-f","mjpeg","-vframes","1","-ss",str(lengthInSeconds/2),destination], shell=True, stderr=subprocess.PIPE)
output = ""
while True:
out = child.stderr.read(1)
if out == '' and child.poll() != None:
break
if out != '':
output += out

updateSQL = "update `videos_graduatevideo` set thumbnail = '" + str(destination) + "' where `original_video` = '" + sourceVideo + "'"
cursor.execute(updateSQL)

此脚本在 Windows 机器 atm 上运行,但我可能会在开发完成后将其部署在 Unix 系统上。

问题是。我需要这个 python 脚本来保持运行。如果 ffmpeg 出现问题并且我的脚本挂起,用户上传的视频将处于“待定”状态,直到我去戳 python 脚本。我知道我拥有的某个 mov 文件使 ffmpeg 无限期挂起。有没有什么方法可以检查一个进程已经运行了多长时间,然后在运行时间过长的情况下将其终止?

最佳答案

我同意 S. Lott 的观点,您似乎会从为您的架构考虑 MQ 中获益,但对于这个特定问题,我认为您使用 Popen没问题。

对于您创建的每个进程,保存创建时间(类似 datetime.datetime.today() 就足够了)。然后每隔一分钟左右检查打开进程和时间的列表,并使用 Popen.send_signal(signal)、terminate() 或 kill() 获取不应该出现的进程。

示例:

import time
from subprocess import Popen
from datetime import datetime
jobs = []
max_life = 600 # in seconds

def reap_jobs(jobs):
now = datetime.datetime.today()
for job in jobs:
if job[0] < now - datetime.timedelta(seconds=max_life)
job[1].kill()
# remove the job from the list if you want.
# but remember not to do it while iterating over the list

for video in list_of_videos:
time = datetime.datetime.today()
job = Popen(...)
jobs.append((time,child))

while True:
reap_jobs(jobs)
time.sleep(60)

关于python - 如何使用 python 检查状态或终止外部进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8602922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com