ffffpython可以用mpeg捕捉错误吗?

2024-04-25 22:14:07 发布

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

嗨,我正在尝试用python为django制作一个视频转换器,我分叉了django-ffmpeg模块,它几乎可以做我想做的任何事情,只是如果转换失败,它不会捕捉错误。在

基本上,模块将ffmpeg命令传递到命令行界面,进行如下转换:

/usr/bin/ffmpeg -hide_banner -nostats -i %(input_file)s -target film-dvd %(output_file)

模块使用此方法将ffmpeg命令传递给cli并获得输出:

def _cli(self, cmd, without_output=False):
    print 'cli'
    if os.name == 'posix':
        import commands
        return commands.getoutput(cmd)
    else:
        import subprocess
        if without_output:
            DEVNULL = open(os.devnull, 'wb')
            subprocess.Popen(cmd, stdout=DEVNULL, stderr=DEVNULL)
        else:
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            return p.stdout.read()

但是举例来说,我上传了一个损坏的视频文件,它只返回在cli上打印的ffmpeg消息,但是不会触发任何东西来知道发生了什么故障

这是转换失败时的ffmpeg示例输出:

[mov,mp4,m4a,3gp,3g2,mj2 @ 0x237d500] Format mov,mp4,m4a,3gp,3g2,mj2 detected only with low score of 1, misdetection possible! [mov,mp4,m4a,3gp,3g2,mj2 @ 0x237d500] moov atom not found /home/user/PycharmProjects/videotest/media/videos/orig/270f412927f3405aba041265725cdf6b.mp4: Invalid data found when processing input

我想知道有没有什么方法可以让它成为一个例外,如何处理,这样我就可以轻松处理了。在

我想到的唯一选择是在cli输出消息字符串中搜索:“处理输入时发现无效数据”,但我不认为这是最好的方法。任何人都可以帮助我并指导我。在


Tags: 模块django方法命令cmdoutputclistdout
2条回答

您需要检查正在创建的Popen对象的returncode。 检查文档:https://docs.python.org/3/library/subprocess.html#subprocess.Popen

代码应该等待子进程完成(使用wait),然后检查returncode。如果returncode!= 0,那么您可以根据需要引发任何异常。在

我就是这样实现它的,以防对其他人有用:

def _cli(self, cmd):
        errors = False
        import subprocess
        try:
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            stdoutdata, stderrdata = p.communicate()
            if p.wait() != 0:
                # Handle error / raise exception
                errors = True
                print "There were some errors"
                return stderrdata, errors
            print 'conversion success '
            return stderrdata, errors
        except OSError as e:
            errors = True
            return e.strerror, errors

相关问题 更多 >