在树莓派上用Python执行FFmpeg命令
我在我的树莓派上用FFmpeg录制视频。代码在这里:
ffmpeg -f video4linux2 -y -r 4 -i /dev/video0 -vf "drawtext=fontfile=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf:expansion=strftime:text='%Y-%m-%d %H\\:%M\\:%S': fontcolor=white:box=1:boxcolor=black@0.8:x=w-text_w:y=h-line_h" -vframes 20 -vcodec mpeg4 out.mp4
我在终端里运行了这段代码,效果很好。不过我想用Python来运行这个。于是我写了下面的代码:
from subprocess import Popen
from os import system
x = "drawtext=fontfile=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf:expansion=strftime:text='%Y-%m-%d %H\\:%M\\:%S': fontcolor=white:box=1:boxcolor=black@0.8:x=w-text_w:y=h-line_h"
result = ['ffmpeg', '-f', 'video4linux2', '-y', '-r', '4', '-i', '/dev/video0', '-vf', x, '-vframes ','20', '-vcodec', 'mpeg4', 'out.mp4']
Popen(result)
但是它只工作了很短的时间(绝对少于1秒)。这是不是哪里出问题了?
1 个回答
0
我想我明白了。看起来你遇到了bash中的空格问题。在命令行中,你把整个 -vf
选项放在了引号里。而在python脚本中,你把 x
定义成了一个字符串;这时候 Popen
会把这个字符串当成其他参数一样处理,结果在实际运行的命令中就没有加引号。命令行中看起来会是这样的:
ffmpeg -f video4linux2 -y -r 4 -i /dev/video0 -vf drawtext=fontfile=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf:expansion=strftime:text='%Y-%m-%d %H\\:%M\\:%S': fontcolor=white:box=1:boxcolor=black@0.8:x=w-text_w:y=h-line_h -vframes 20 -vcodec mpeg4 out.mp4
所以实际上,你应该这样做:
x = '"drawtext=fontfile=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf:expansion=strftime:text=\'%Y-%m-%d %H\\:%M\\:%S\': fontcolor=white:box=1:boxcolor=black@0.8:x=w-text_w:y=h-line_h"'
否则,当bash运行这个命令时,日期格式中的空格会把这个参数拆开,导致一些意想不到的情况发生。
(抱歉文字有点多,只是想确保我没有让你困惑。)