
在自动化视频上传到youtube的场景中,尤其当处理大文件时,缺乏实时进度反馈会使得用户难以判断上传状态,甚至误认为程序卡死。本教程将详细介绍如何在现有的python youtube上传脚本中,通过集成进度条来提供清晰的上传进度可视化。
Google API Python客户端库在执行可恢复上传(resumable upload)时,提供了一个关键机制来获取上传进度。youtube.videos().insert()方法配合googleapiclient.http.MediaFileUpload(..., resumable=True),在调用request.next_chunk()时,会返回两个值:status和response。
利用status.resumable_progress和status.total_size,我们就可以计算出上传的百分比和剩余量,从而驱动进度条的显示。
为了在控制台输出中优雅地显示进度条,同时不干扰其他print语句,推荐使用Enlighten库。Enlighten具有以下优点:
首先,确保你的环境中安装了Enlighten:
立即学习“Python免费学习笔记(深入)”;
pip install enlighten
我们将修改原有的upload_video函数,以引入Enlighten进度条。
import os
import webbrowser
import re
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
import pickle
import shutil
import time
import requests
import enlighten # 导入enlighten库
WEBHOOK_URL = "xxxx" # 请替换为您的Webhook URL
# ... (authenticate_youtube, save_token, load_token, format_title, send_discord_webhook 函数保持不变) ...
def upload_video(youtube, file_path, manager):
"""
上传视频到YouTube,并显示进度条。
:param youtube: YouTube API服务对象。
:param file_path: 待上传视频文件的完整路径。
:param manager: Enlighten管理器实例。
"""
print(f" -> Detected file: {file_path}")
title = format_title(os.path.basename(file_path)).replace("_", "|").replace(".mkv", "")
print(f" * Uploading : {title}...")
send_discord_webhook(f'- Uploading : {title}')
# Load predefined tags from the file
tags_file_path = "tags.txt"
with open(tags_file_path, 'r') as tags_file:
tags = tags_file.read().splitlines()
description = (
"⏬ Déroule-moi ! ⏬
"
f"VOD HD d'un stream Twitch de Ben_OnAir uploadée automatiquement
"
"═════════════════════
"
"► Je stream ici : https://www.twitch.tv/ben_onair
"
"► Ma Chaîne Youtube : https://www.youtube.com/@BenOnAir
"
"► Mon Twitter : https://twitter.com/Ben_OnAir
"
"► Mon Insta : https://www.instagram.com/ben_onair/
"
"► Mon Book : https://ben-book.fr/"
)
# 获取文件总大小
file_size = os.path.getsize(file_path)
# 创建Enlighten进度条
# desc: 进度条前缀描述
# unit: 单位,例如'bytes'
# total: 总大小
# min_display_duration: 最小显示时长,防止进度条闪烁
pbar = manager.counter(total=file_size, unit='bytes', desc=f"Uploading {title[:40]}...", min_display_duration=0.5)
# Setup request for resumable upload
request = youtube.videos().insert(
part="snippet,status",
body={
"snippet": {
"categoryId": "20",
"description": description,
"title": title,
"tags": tags
},
"status": {
"privacyStatus": "private"
}
},
# MediaFileUpload的chunksize=-1对于resumable=True通常是默认行为,可以省略
media_body=googleapiclient.http.MediaFileUpload(file_path, resumable=True)
)
response = None
while response is None:
try:
status, response = request.next_chunk()
if status: # 检查status是否为MediaUploadProgress对象
# 更新进度条的当前值
pbar.count = status.resumable_progress
# pbar会自动处理显示,无需额外print
if response is not None:
if 'id' in response:
video_url = f"https://www.youtube.com/watch?v={response['id']}"
print(f" -> Uploaded {file_path} with video ID {response['id']} - {video_url}")
send_discord_webhook(f'- Uploaded : {title} | {video_url}')
webbrowser.open(video_url, new=2)
else:
print(f"Failed to upload {file_path}. No video ID returned from YouTube.")
send_discord_webhook(f'- Failed uploading : {title}') # 修正原代码中的end_discord_webhook
pbar.close() # 上传完成,关闭进度条
except googleapiclient.errors.HttpError as e:
print(f"An HTTP error {e.resp.status} occurred while uploading {file_path}: {e.content}")
pbar.close() # 发生错误,关闭进度条
break
# You can handle specific HTTP error codes here if needed
def main(directory_path):
"""
主函数,处理指定目录下的所有视频文件上传。
:param directory_path: 包含待上传视频文件的目录路径。
"""
youtube = authenticate_youtube()
# 初始化Enlighten管理器,最好在主循环外一次性创建
manager = enlighten.get_manager()
try:
files = [os.path.join(directory_path, f) for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]
for file_path in files:
# 将manager实例传递给upload_video函数
upload_video(youtube, file_path, manager)
# Move the local video file to a different directory after upload
print(f" * Moving local file: {file_path}")
shutil.move(file_path, "M:\VOD UPLOADED")
print(f" -> Moved local file: {file_path}")
finally:
# 确保在程序结束时关闭Enlighten管理器,即使发生异常
manager.stop()
try:
main("M:\VOD TO UPLOAD")
except googleapiclient.errors.HttpError:
print(f" -> Quota Exceeded!")
except Exception as e:
print(f" -> An error occured : {e}")
send_discord_webhook(f'-> An error occured : {e}')
通过以上修改,您的YouTube上传脚本将能提供清晰、专业的实时上传进度反馈,极大地提升用户体验。这不仅让用户了解上传状态,也方便调试和监控自动化流程。
以上就是Python YouTube上传脚本中集成实时进度条:使用Enlighten库的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号