将pyffmpeg作为子模块导入时出现错误的排查求助
解决pyffmpeg转换视频时的跨平台错误问题
我用pyffmpeg和pytube构建API,实现YouTube视频下载转.wav并同步LED动画。pyffmpeg被导入到子模块,该子模块又被其他模块导入,在MacBook和树莓派上运行均报错:
MacBook报错信息
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/path/to/venv/lib/python3.11/site-packages/pyffmpeg/__init__.py", line 163, in convert raise Exception(self.error) Exception
树莓派报错信息
File "/path/to/venv/lib/python3.11/site-packages/pyffmpeg/__init__.py", line 154, in convert if 'Output #0' not in stderr: ^^^^^^ UnboundLocalError: cannot access local variable 'stderr' where it is not associated with a value
问题分析
从pyffmpeg的代码片段可以看出,核心问题是stderr变量未初始化就直接进行判断:
if 'Output #0' not in stderr: # ...处理逻辑
- 树莓派上的
UnboundLocalError是因为stderr在当前作用域中未被定义就被使用 - MacBook上的空
Exception是因为stderr为空时,self.error被设为空字符串,最终抛出了无内容的异常
修复方案
修改pyffmpeg的__init__.py中对应的代码块,先初始化stderr变量,同时完善空错误信息的处理:
# 初始化stderr为空字符串,避免未定义错误 stderr = stderr or "" if 'Output #0' not in stderr: lines = stderr.splitlines() if len(lines) > 0: self.error = lines[-1] else: # 当无错误输出时,设置明确提示 self.error = "FFmpeg转换失败,未获取到错误输出" if self.enable_log: self.logger.error(self.error) raise Exception(self.error) else: self.error = '' if self.enable_log: self.logger.info('Conversion Done') return out
修改说明
- 增加
stderr = stderr or "",确保stderr变量始终有值,避免未定义错误 - 当
stderr为空时,设置明确的错误提示,解决空Exception问题 - 保留原有转换成功的逻辑,同时提升错误信息的可读性
内容的提问来源于stack exchange,提问作者Devin Gardner
相关产品推荐
相关产品推荐

