【问题标题】:Python subprocess: capture output of ffmpeg and run regular expression against itPython 子进程:捕获 ffmpeg 的输出并对其运行正则表达式
【发布时间】:2014-12-31 19:26:00
【问题描述】:

我有以下代码

import subprocess
import re
from itertools import *

command = ['ffprobe', '-i', '/media/some_file.mp4']
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
text = p.stderr.read()
retcode = p.wait()
text = text.decode('utf-8')
p = re.compile("Duration(.*)")

num = 0 #for debugging
for line in iter(text.splitlines()):
    print(str(num) + line) #for debugging
    m = p.match(str(line))
    if m != None:
        print(m.group(1))

当我查看输出时,上面有一行写着“持续时间”,但是它没有被捕获, print(m.group(1)) 永远不会到达。如果我将文本变量更改为“持续时间 blahblah”的硬编码字符串,我会得到“blahblah”,这是我所期望的。似乎正则表达式无法识别从标准错误返回的文本。如何将文本转换为正则表达式可以识别和匹配的格式?


我想出了以下解决方案,它是否可以帮助其他尝试使用 python 从 ffmpeg 捕获持续时间的人

import subprocess
import re

command = ['ffprobe', '-i', '/media/some_file.mp4']
p = subprocess.Popen(command, stderr=subprocess.PIPE)
text = p.stderr.read()
retcode = p.wait()
text = text.decode('utf-8')
p = re.compile(".*Duration:\s([0-9:\.]*),", re.MULTILINE|re.DOTALL)
m = p.match(text)
print(m.group(1))

【问题讨论】:

    标签: python regex utf-8 ffmpeg stderr


    【解决方案1】:
    p = re.compile(r".*?Duration(.*)")
    

    试试这个。match从头开始,而duration之前可能有一些东西。

    【讨论】:

    • 这里用greedy应该没问题。
    • @JesseAdam 如果你可以在这里发布stderr 会更容易调试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2019-05-31
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2016-10-29
    • 2019-10-16
    相关资源
    最近更新 更多