如何通过Python代码终止youtube-dl的音频下载任务
解决Python中终止youtube-dl音频下载的问题
原代码存在的问题
- 定义的
threading.Event()对象e从未在download()函数中被检查,调用e.set()无法触发下载终止 - Python线程无法被强制终止,必须等待线程内代码主动退出,但
ydl.download()是阻塞式调用,不会主动响应外部信号
方案一:使用进程替代线程(推荐,强制终止更可靠)
进程支持强制终止,适合处理第三方库的阻塞操作:
import youtube_dl from multiprocessing import Process import time # 设置下载选项 def download(): # 修复原代码语法错误:移除postprocessors中无效的'start'键 options = { 'nopart': True, 'format': 'bestaudio/best', 'outtmpl': '%(title)s.%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'wav', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(options) as ydl: ydl.download(['https://www.youtube.com/watch?v=q130lTDaua0']) if __name__ == "__main__": p = Process(target=download, args=()) p.start() # 等待30秒 p.join(30) if p.is_alive(): print("下载未完成,强制终止进程") p.terminate() p.join() # 等待进程彻底退出 else: print("下载已完成")
方案二:利用youtube-dl进度钩子主动终止
通过进度钩子检查终止信号,让下载线程主动退出,更优雅:
import youtube_dl import threading # 终止信号事件 terminate_event = threading.Event() def download_progress_hook(d): # 检查终止信号,若已设置则抛出异常终止下载 if terminate_event.is_set(): raise Exception("用户终止下载") # 设置下载选项 def download(): options = { 'nopart': True, 'format': 'bestaudio/best', 'outtmpl': '%(title)s.%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'wav', 'preferredquality': '192', }], 'progress_hooks': [download_progress_hook], # 添加进度钩子 } try: with youtube_dl.YoutubeDL(options) as ydl: ydl.download(['https://www.youtube.com/watch?v=q130lTDaua0']) except Exception as e: print(f"下载终止:{e}") if __name__ == "__main__": t = threading.Thread(target=download, args=()) t.start() # 等待30秒 t.join(30) if t.is_alive(): print("下载未完成,发送终止信号") terminate_event.set() t.join() # 等待线程退出 else: print("下载已完成")
内容的提问来源于stack exchange,提问作者Ahmad Raza
相关产品推荐
相关产品推荐

