You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python subprocess调用ffmpeg无输出且未生成文件问题排查

解决方法

1. 修正subprocess.run的参数传递格式

"bufsize must be an integer"错误几乎都是参数传递结构错误导致的。subprocess.run的第一个参数args需为参数列表(推荐)或完整命令字符串(需配合shell=True),若错误地将ffmpeg的命令参数拆分作为subprocess.run的位置参数,会把这些参数误传给bufsize等后续参数,触发报错。

正确写法示例:

方式1:参数列表(推荐,规避shell注入风险)

import subprocess

# 将ffmpeg命令拆分为列表,每个参数单独作为元素
cmd = [
    "ffmpeg",
    "-i", "input.mp4",  # 输入文件路径
    "-ss", "00:00:10",  # 起始时间(支持时分秒或纯秒数)
    "-t", "20",         # 截取时长(单位:秒)
    "-c", "copy",       # 直接复制流,提升处理速度
    "output.mp4"        # 输出文件路径
]

# 执行命令,check=True会在ffmpeg出错时抛出异常,方便排查问题
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
# 打印ffmpeg的输出和错误信息
print("STDOUT:", result.stdout)
print("STDERR:", result.stderr)

方式2:字符串命令+shell=True(仅在信任命令内容时使用)

import subprocess

cmd_str = 'ffmpeg -i input.mp4 -ss 00:00:10 -t 20 -c copy output.mp4'
result = subprocess.run(cmd_str, shell=True, check=True, capture_output=True, text=True)
print("STDOUT:", result.stdout)
print("STDERR:", result.stderr)

2. 排查ffmpeg执行失败的隐性问题

修正参数格式后若仍未生成文件,需通过ffmpeg的输出信息定位问题:

  • 开启capture_output=True和text=True,捕获ffmpeg的标准输出与错误信息,可发现输入文件不存在、格式不支持、权限不足等问题。
  • 启用check=True,当ffmpeg返回非0退出码时会直接抛出subprocess.CalledProcessError,强制暴露执行错误。

3. 确认ffmpeg路径正确性

若系统环境变量未配置ffmpeg,需指定完整路径:

# Linux/macOS示例
cmd = ["/usr/local/bin/ffmpeg", "-i", "input.mp4", ...]
# Windows示例
cmd = ["C:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe", "-i", "input.mp4", ...]

额外提示:用ffmpeg-python简化操作

既然已安装ffmpeg-python,直接使用其API可避免手动拼接参数的错误:

import ffmpeg

input_stream = ffmpeg.input('input.mp4', ss='00:00:10', t=20)
output_stream = ffmpeg.output(input_stream, 'output.mp4', c='copy')
ffmpeg.run(output_stream, capture_stdout=True, capture_stderr=True)

内容的提问来源于stack exchange,提问作者confused

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:12:17