如何解决Git Bash for Windows AttributeError: 'NoneType' 对象没有属性 'groups' 使用 Python re 解析字符串
我正在尝试为一个项目使用预训练的 CNN 模型,但其中的一些代码在我的机器上存在问题。 Windows 10,git 版本 2.28.0.windows.1,Python 3.9.0
此代码来自https://github.com/zhoubolei/moments_models/tree/v2
output = subprocess.Popen(['ffmpeg','-i',video_file],stderr=subprocess.PIPE,shell=True).communicate()
# Search and parse 'Duration: 00:05:24.13,' from ffmpeg stderr.
re_duration = re.compile(r'Duration: (.*?)\.')
duration = re_duration.search(str(output[1])).groups()[0]
我得到以下回溯:
Traceback (most recent call last):
File "C:\Users\gradx\PycharmProjects\final\moments_models\test_video.py",line 62,in <module>
frames = extract_frames(args.video_file,args.num_segments)
File "C:\Users\gradx\PycharmProjects\final\moments_models\utils.py",line 21,in extract_frames
duration = re_duration.search(str(output[1])).groups()[0]
AttributeError: 'nonetype' object has no attribute 'groups'
本质上的目标是从一些字符串 Popen 和 re.complile() 中收集输入视频文件的运行时间。这不是我的代码,所以我不能说为什么使用这种方法,但也不能建议不同的方法。我已经尝试修改传递给 re.compile() 的正则表达式,因为我意识到如果没有找到任何东西可能会返回 None ,但这并没有帮助。
感谢任何支持。
编辑: 原来问题是缺少 ffmpeg。
解决方法
你代码的主要问题
您正在搜索模式并尝试获取其组,甚至在检查搜索是否返回某些内容之前。
# As the code is returning only the errors (stderr=subprocess.PIPE)
# it is better to create a variable called error instead of output:
_,error = subprocess.Popen(['ffmpeg','-i',video_file],stderr=subprocess.PIPE,shell=True).communicate()
# Lets check if the execution returned some error
if error:
print(f"Omg some error occurred: {str(error)}")
# Get the duration returned by the error
# error are bytes,so we need to decode it
re_duration = re.search(r'Duration: (.*?)\.',error.decode())
# if the search by duration returned something
# then we are taking the group 1 (00:05:24)
if re_duration:
re_duration = re_duration.group(1)
print(re_duration)
# 00:05:24
我们假设发生某些错误时会返回 Duration...
,但如果它由成功输出返回,则您必须反转变量并向您的子流程添加更改:
# Changing variable to output and changing the return to stdout (successful return)
output,_ = subprocess.Popen(['ffmpeg',stdout=subprocess.PIPE,shell=True).communicate()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。