
本文介绍一种高效、内存友好的方法:直接将远程视频 URL 传给 ffprobe 获取时长,避免使用 Python Requests 流式下载 + pipe 的复杂方案,彻底解决不可寻址流导致的 Invalid data found when processing input 错误。
本文介绍一种高效、内存友好的方法:直接将远程视频 url 传给 ffprobe 获取时长,避免使用 python requests 流式下载 + pipe 的复杂方案,彻底解决不可寻址流导致的 `invalid data found when processing input` 错误。
ffprobe(FFmpeg 工具集的一部分)原生支持通过 HTTP/HTTPS 协议直接读取远程媒体资源——无需先下载、无需模拟管道(pipe:0)、无需处理非 seekable 文件描述符的兼容性问题。这正是解决你当前困境的最简、最健壮方案。
✅ 正确做法:URL 直接作为输入
只需将视频 URL 直接传递给 ffprobe,并配合精简输出参数,即可秒级获取精确时长(单位:秒):
ffprobe \ -v quiet \ -show_entries format=duration \ -of default=noprint_wrappers=1:nokey=1 \ "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
输出示例:
596.474195
? 参数说明:
-v quiet:静默模式,屏蔽所有日志与版本信息(也可用-hide_banner替代,仅隐藏 banner);-show_entries format=duration:仅提取format结构中的duration字段;-of default=noprint_wrappers=1:nokey=1:输出格式设为简洁纯值模式(无[FORMAT]包裹、无duration=前缀)。
? 在 Python 中安全调用
推荐使用 subprocess.run() 安全执行,并捕获异常与空值:
import subprocess
import shlex
def get_remote_video_duration(url: str) -> float:
cmd = (
f'ffprobe -v quiet -show_entries format=duration '
f'-of default=noprint_wrappers=1:nokey=1 "{url}"'
)
try:
result = subprocess.run(
shlex.split(cmd),
capture_output=True,
text=True,
timeout=30 # 防止网络卡死
)
if result.returncode != 0:
raise RuntimeError(f"ffprobe failed: {result.stderr.strip()}")
duration_str = result.stdout.strip()
if not duration_str:
raise ValueError("Duration not found in ffprobe output")
return float(duration_str)
except subprocess.TimeoutExpired:
raise TimeoutError(f"ffprobe timed out while probing {url}")
except ValueError as e:
raise ValueError(f"Invalid duration value: {e}")
# 使用示例
url = "https://gist.github.com/SeunghoonBaek/f35e0fd3db80bf55c2707cae5d0f7184"
try:
dur = get_remote_video_duration(url)
print(f"Video duration: {dur:.3f} seconds")
except Exception as e:
print(f"Error: {e}")⚠️ 重要注意事项
-
服务器需支持范围请求(Range Requests):
ffprobe依赖 HTTPRange头快速定位文件头(如 MP4 的moovbox)。若目标服务器禁用Accept-Ranges或返回 200 全量响应(而非 206 Partial Content),ffprobe可能无法解析或超时。可先用curl -I {url}检查响应头是否含Accept-Ranges: bytes。 -
不适用于所有协议/格式:HLS(
.m3u8)、DASH 等分段协议需额外处理;某些编码异常或损坏的远程文件可能仍失败。 -
避免
stream=True+pipe:0组合:正如你已验证,req.raw是单向流,而部分ffprobe内部逻辑(即使未显式 seek)可能隐式依赖缓冲或重试机制,导致解析失败。直接 URL 输入由ffprobe自行管理 HTTP 连接,完全规避该问题。 -
批量处理建议加缓存:对同一 URL 多次调用时,建议本地缓存结果(如使用
functools.lru_cache或 Redis),避免重复网络开销。
✅ 总结
与其在 Python 层绕路构造不可靠的流式管道,不如信任 ffprobe 原生的网络能力——它专为媒体元数据探测而生,成熟、高效、零内存拷贝。只要确保目标 URL 可被 ffprobe 直接访问(检查 CORS / Range 支持),这就是获取远程视频时长的黄金标准方案。

















