r/learnpython•
ss0ny

I need help seeing if this code works as it should

import os import yt_dlp import sys

Function to download a video from the given URL

def download_video(url, output_path='downloads'): # Ensure the output directory exists if not os.path.exists(output_path): os.makedirs(output_path)

# Options for yt-dlp
ydl_opts = {
    'outtmpl': os.path.join(output_path, '%(title)s.%(ext)s'),  # Save with video title as filename
    'format': 'bestvideo+bestaudio/best',  # Best video + audio combination
    'merge_output_format': 'mp4',  # Ensure output is in mp4 format
    'quiet': False,  # Set to True to silence output (optional)
    'noplaylist': True,  # Prevent downloading playlists if URL is a playlist
}

# Create the yt-dlp downloader instance
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    try:
        print(f"Downloading video from: {url}")
        ydl.download([url])  # Start download
        print("Download completed successfully.")
    except Exception as e:
        print(f"Error occurred while downloading: {e}")

Main function for user interaction

def main(): print("Welcome to the Video Downloader!") print("Please enter the URL of the video you want to download:")

# Get the video URL from the user
video_url = input("Enter the video URL: ")

# Ensure the URL is not empty
if not video_url.strip():
    print("Error: You must enter a valid URL.")
    sys.exit(1)

# Start the download process
download_video(video_url)

Run the program

if name == "main": main()

Posted May 7, 2025, 2:36 PM UTC

111
Loading comments…