Advertisement
Guest User

multithreading for youtube-dl

a guest
Nov 28th, 2021
614
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. import youtube_dl
  2. import threading
  3. import sys
  4.  
  5. # help command
  6. if sys.argv[1] == "help":
  7.     print("Usage: python multithreaded.py YT-Playlist-Link")
  8.     print("Usage: python multithreaded.py YT-Playlist-Link StartAtInt")
  9.     print("Usage: python multithreaded.py YT-Playlist-Link StartAtInt EndAtInt")
  10.     sys.exit(0)
  11.  
  12. # Optional StartAt and EndAt parameter
  13. hasstart = False
  14. hasend = False
  15. try:
  16.     if sys.argv[2] != None:
  17.         hasstart = True
  18.         startat = int(sys.argv[2])
  19.  
  20.     if sys.argv[3] != None:
  21.         hasend = True
  22.         endat = int(sys.argv[3])
  23. except:
  24.     pass
  25.  
  26. # Method executed by individual threads
  27. def download(url: str, title: str):
  28.     ydl_opts = {
  29.         'format': 'best',
  30.         'outtmpl': title + '.%(ext)s',
  31.         'noplaylist': True,
  32.         'ignoreerrors': True,
  33.         'abort_on_unavailable_fragments': True,
  34.         'quiet': True,
  35.     }
  36.     try:
  37.         with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  38.             ydl.download([url])
  39.             print("Download comlete: " + title)
  40.     except Exception as e:
  41.         print("Download exception: " + str(e))
  42.  
  43. # Select options based on input parameters
  44. if not hasstart and not hasend:
  45.     ydl_opts = {
  46.         'ignoreerrors': True,
  47.         'abort_on_unavailable_fragments': True,
  48.     }
  49. elif hasstart and not hasend:
  50.     ydl_opts = {
  51.         'ignoreerrors': True,
  52.         'abort_on_unavailable_fragments': True,
  53.         'playliststart': startat,
  54.     }
  55. elif hasend:
  56.     ydl_opts = {
  57.         'ignoreerrors': True,
  58.         'abort_on_unavailable_fragments': True,
  59.         'playliststart': startat,
  60.         'playlistend': endat,
  61.     }
  62.  
  63. # Get all videos in the playlist and run download in individual thread
  64. try:
  65.     with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  66.         result = ydl.extract_info(sys.argv[1], download=False)
  67.         for video in result['entries']:
  68.             try:
  69.                 threading.Thread(target=download, args=(video['webpage_url'], video['title'])).start()
  70.             except:
  71.                 print("Skipped one due to error")
  72.                 continue
  73. except KeyboardInterrupt:
  74.     # Doesnt work for some reason
  75.     for thread in threading.enumerate():
  76.         thread.join()
  77. except Exception as e:
  78.     print("General exception: " + str(e))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement