Git Bash for Windows AttributeError: 'NoneType' object has no attribute 'groups' using Python re to parse string

Git Bash for Windows AttributeError: 'NoneType' object has no attribute 'groups' using Python re to parse string

我正在尝试为一个项目使用预训练的 CNN 模型,但一些包含的代码在我的机器上出现问题。 Windows10,git版本 2.28.0.windows.1,Python3.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() 的正则表达式,因为我意识到如果什么都找不到,可以 return 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', '-i', video_file], stdout=subprocess.PIPE, shell=True).communicate()