Python调用FFprobe无输出结果,请求代码排查分析
代码问题分析与修复方案
核心问题
你的代码目前只完成了命令列表的构建与打印,没有实际调用subprocess执行ffprobe命令,这是没有输出的直接原因。此外,ffprobe的参数还存在格式错误,即使执行也会报错。
具体参数错误点
- 参数
- v存在多余空格,应为-v; show_entries的参数被错误拆分:stream=codec_type和start_time需要合并为stream=codec_type,start_time,否则ffprobe会将start_time识别为无效的独立参数;- 缺少
-i参数:ffprobe必须通过-i指定输入文件,否则无法定位目标媒体文件。
修复后的完整代码
import subprocess class Trial: def __init__(self, filename): self.filename = filename def build_ffprobe(self): # 修正参数格式,合并show_entries参数,添加-i,修正-v的空格问题 self.command_list = [ "ffprobe", "-v", "error", # 使用error级别减少冗余输出,也可以用info等 "-show_entries", "stream=codec_type,start_time", "-of", "compact=p=1:nk=0", "-i", self.filename ] def run_ffprobe(self): self.build_ffprobe() print("执行的命令:", self.command_list) # 执行命令并捕获输出 try: result = subprocess.run( self.command_list, capture_output=True, text=True, check=True ) print("FFprobe输出结果:") print(result.stdout) except subprocess.CalledProcessError as e: print("执行出错,错误信息:") print(e.stderr) if __name__ == "__main__": filename = input('name of the file: ') trial_obj = Trial(filename) trial_obj.run_ffprobe()
修复说明
- 将
filename作为参数传入类的构造方法,避免使用全局变量,代码更规范; - 修正ffprobe的所有参数错误,确保命令能被正确解析;
- 使用
subprocess.run执行命令,通过capture_output=True捕获标准输出和错误,text=True将输出转为字符串; - 添加异常处理,方便排查执行过程中的错误;
- 调整方法名符合Python命名规范(小写加下划线)。
内容的提问来源于stack exchange,提问作者jiraiya_sensei
相关产品推荐
相关产品推荐

