自制YouTube下载器报错:module 'ffmpeg' has no attribute 'input'
问题分析与解决:AttributeError: module 'ffmpeg' has no attribute 'input'
核心原因
你当前安装的ffmpeg Python包不是用于调用ffmpeg命令行工具的官方库——PyPI上存在一个同名的无关包,它没有input方法,直接导致了报错。真正用于音视频处理的是ffmpeg-python库,你大概率装错了依赖包。
此外代码里还有几处逻辑错误,也会影响正常运行:
- 路径拼接格式错误,传给
ffmpeg.input的参数不符合要求 - 目录存在性检查逻辑错误,
path1 and path2的写法无法正确判断两个目录是否都存在 - Windows路径的反斜杠未转义,可能引发路径解析异常
解决步骤
1. 替换正确的Python库
先卸载错误的ffmpeg包,再安装官方的ffmpeg-python:
pip uninstall ffmpeg -y pip install ffmpeg-python
2. 修正代码中的错误
(1)修复路径拼接
原代码中ffmpeg.input(path1, video.title + '.mp4')的写法错误,需将路径拼接成完整的文件路径,而非传递两个参数:
video_stream = ffmpeg.input(os.path.join(path1, video.title + '.mp4')) audio_stream = ffmpeg.input(os.path.join(path2, video.title + '.mp4'))
(2)修复目录存在性检查
把os.path.exists(path1 and path2)改为分别判断两个路径的存在性:
if os.path.exists(path1) and os.path.exists(path2): boo = True else: boo = False
(3)修复路径转义问题
Windows路径使用原始字符串(加r前缀)避免转义错误:
raw = r'C:\ProgramData\ytChache' path1 = r'C:\ProgramData\ytChache\Video' path2 = r'C:\ProgramData\ytChache\Audio'
(4)明确输出文件路径
原代码输出文件默认在脚本目录,建议指定到缓存目录,方便管理:
output_file = os.path.join(raw, f"{video.title}.mp4") ffmpeg.output(audio_stream, video_stream, output_file).run()
修正后的完整代码
from pytube import YouTube import ffmpeg import os # 使用原始字符串避免路径转义问题 raw = r'C:\ProgramData\ytChache' path1 = r'C:\ProgramData\ytChache\Video' path2 = r'C:\ProgramData\ytChache\Audio' file_type = "mp4" # 正确检查两个目录是否都存在 if os.path.exists(path1) and os.path.exists(path2): boo = True else: boo = False while boo: url = input("Link : ") choice = int(input('Enter 1 for Only Audio and Enter 2 For Both Audio and Video \n: ')) video = YouTube(url) streams = video.streams # 变量名小写更符合PEP8规范 if choice == 1: streams.filter(only_audio=True).first().download(path2) elif choice == 2: resol = input("Resolution : ") # 下载视频和音频 streams.filter(res=resol, file_extension=file_type).first().download(path1) streams.filter(only_audio=True).first().download(path2) # 拼接文件路径 video_file = os.path.join(path1, f"{video.title}.mp4") audio_file = os.path.join(path2, f"{video.title}.mp4") output_file = os.path.join(raw, f"{video.title}.mp4") # 使用ffmpeg合并音视频 video_stream = ffmpeg.input(video_file) audio_stream = ffmpeg.input(audio_file) ffmpeg.output(audio_stream, video_stream, output_file).run() # 删除临时文件 os.remove(video_file) os.remove(audio_file) else: print('Invalid Selection') # 创建目录的逻辑放在循环外,避免重复创建 if not boo: os.makedirs(raw, exist_ok=True) # 使用makedirs一次性创建多级目录 os.makedirs(path1, exist_ok=True) os.makedirs(path2, exist_ok=True)
内容的提问来源于stack exchange,提问作者Robin Singh
相关产品推荐
相关产品推荐

