A feature-rich command-line audio/video downloader forked from youtube-dl
Comprehensive configuration system with 100+ parameters controlling download behavior, format selection, output templates, networking, post-processing options, and other aspects of yt-dlp operation. Configuration can be provided via dictionary to YoutubeDL constructor or parsed from command-line arguments.
Functions for command-line interface operation and parsing arguments into configuration dictionaries.
def main(argv=None):
"""
Main CLI entry point for yt-dlp command-line interface.
Parses arguments, sets up YoutubeDL instance, and executes downloads
with proper error handling and exit codes.
Parameters:
- argv: list[str]|None, command-line arguments (default: sys.argv)
Returns:
None: exits with appropriate exit code
"""
def parse_options(argv=None):
"""
Main option parsing function that processes command-line arguments.
Parameters:
- argv: list[str]|None, command-line arguments (default: sys.argv)
Returns:
ParsedOptions: named tuple with (parser, options, urls, ydl_opts)
"""
def parseOpts(overrideArguments=None, ignore_config_files='if_override'):
"""
Parse command-line options and return configuration.
Parameters:
- overrideArguments: list[str]|None, arguments to use instead of sys.argv
- ignore_config_files: str, how to handle config files ('if_override', 'always', 'never')
Returns:
tuple: (parser, options, urls) where options contains parsed configuration
"""Options controlling what content to download and in what format.
# Format selection and quality options
YDLOptions = {
'format': str, # Format selector string (e.g., 'best', 'worst', 'mp4')
'format_sort': list[str], # Format sorting criteria
'format_sort_force': bool, # Force format sorting
'listformats': bool, # List available formats instead of downloading
'listformats_table': bool, # Use table format for format listing
# Quality and size limits
'min_filesize': int, # Minimum file size in bytes
'max_filesize': int, # Maximum file size in bytes
'min_views': int, # Minimum view count
'max_views': int, # Maximum view count
# Multiple streams
'allow_multiple_video_streams': bool, # Allow multiple video streams
'allow_multiple_audio_streams': bool, # Allow multiple audio streams
'allow_unplayable_formats': bool, # Allow unplayable formats
'ignore_no_formats_error': bool, # Ignore no formats error
'check_formats': str, # Check format availability
}Options controlling where and how files are saved.
# Output templates and paths
YDLOptions = {
'outtmpl': dict[str, str], # Output filename templates by type
'outtmpl_na_placeholder': str, # Placeholder for unavailable fields
'paths': dict[str, str], # Output paths by type
'restrictfilenames': bool, # Restrict filenames to ASCII
'windowsfilenames': bool, # Use Windows-compatible filenames
'trim_file_name': int, # Maximum filename length
# File handling
'overwrites': bool, # Overwrite existing files
'nopart': bool, # Don't use .part files
'updatetime': bool, # Update file modification times
'continuedl': bool, # Continue partial downloads
'noresizebuffer': bool, # Don't resize download buffer
# Directory and file organization
'allow_playlist_files': bool, # Allow playlist info files
'clean_infojson': bool, # Clean info JSON files
}Options controlling network behavior, requests, and connectivity.
# Network configuration
YDLOptions = {
'proxy': str, # HTTP/HTTPS proxy URL
'socket_timeout': float, # Socket timeout in seconds
'source_address': str, # Source IP address to bind to
'cn_verification_proxy': str, # Proxy for CN verification
'geo_verification_proxy': str, # Proxy for geo verification
'geo_bypass': bool, # Attempt geo bypass
'geo_bypass_country': str, # Country code for geo bypass
'geo_bypass_ip_block': str, # IP block for geo bypass
# Request headers and user agent
'http_headers': dict[str, str], # Custom HTTP headers
'user_agent': str, # Custom user agent string
'referer': str, # Custom referer header
# Connection behavior
'nocheckcertificate': bool, # Skip SSL certificate verification
'prefer_insecure': bool, # Prefer insecure connections
'enable_file_urls': bool, # Enable file:// URLs
'legacyserverconnect': bool, # Use legacy server connect
# Rate limiting and retries
'ratelimit': int, # Download rate limit in bytes/sec
'throttledratelimit': int, # Throttled rate limit
'retries': int, # Number of download retries
'file_access_retries': int, # File access retries
'fragment_retries': int, # Fragment download retries
'extractor_retries': int, # Extractor retries
'retry_sleep_functions': dict, # Retry sleep functions
# Request timing
'sleep_interval': float, # Sleep between requests
'max_sleep_interval': float, # Maximum sleep interval
'sleep_interval_requests': float, # Sleep between requests
'sleep_interval_subtitles': float, # Sleep between subtitle requests
}Options for handling authentication, login credentials, and cookies.
# Authentication options
YDLOptions = {
'username': str, # Account username
'password': str, # Account password
'twofactor': str, # Two-factor authentication code
'videopassword': str, # Video-specific password
'usenetrc': bool, # Use .netrc file for credentials
'netrc_location': str, # Custom .netrc file location
'netrc_cmd': str, # Command to get credentials
# TV provider authentication
'ap_mso': str, # TV provider MSO
'ap_username': str, # TV provider username
'ap_password': str, # TV provider password
# Client certificates
'client_certificate': str, # Client certificate file
'client_certificate_key': str, # Client certificate key file
'client_certificate_password': str, # Client certificate password
# Cookie handling
'cookiefile': str, # Cookie file path
'cookiesfrombrowser': tuple, # Extract cookies from browser
}Options for handling playlists, channels, and batch operations.
# Playlist options
YDLOptions = {
'playliststart': int, # Playlist start index
'playlistend': int, # Playlist end index
'playlistreverse': bool, # Reverse playlist order
'playlistrandom': bool, # Randomize playlist order
'lazy_playlist': bool, # Lazy playlist loading
'noplaylist': bool, # Download single video instead of playlist
'extract_flat': str, # Extract playlist info only
'playlist_items': str, # Specific playlist items to download
# Batch processing
'max_downloads': int, # Maximum number of downloads
'break_on_existing': bool, # Stop on existing files
'break_on_reject': bool, # Stop on rejected videos
'break_per_url': bool, # Break processing per URL
'skip_playlist_after_errors': int, # Skip playlist after N errors
# Archive and filtering
'download_archive': str, # Download archive file path
'force_write_download_archive': bool, # Force writing archive
'match_filter': callable, # Match filter function
'daterange': object, # Date range filter
}Options controlling what information is displayed and how.
# Output and logging options
YDLOptions = {
'quiet': bool, # Suppress output messages
'no_warnings': bool, # Suppress warning messages
'verbose': bool, # Enable verbose output
'noprogress': bool, # Disable progress reporting
'progress_with_newline': bool, # Progress on new lines
'progress_template': dict[str, str], # Progress message templates
'progress_delta': float, # Progress update interval
'consoletitle': bool, # Set console title
'color': dict[str, str], # Color configuration
# Information extraction
'forceurl': bool, # Force URL extraction
'forcetitle': bool, # Force title extraction
'forceid': bool, # Force ID extraction
'forcethumbnail': bool, # Force thumbnail extraction
'forcedescription': bool, # Force description extraction
'forceduration': bool, # Force duration extraction
'forcefilename': bool, # Force filename extraction
'forceformat': bool, # Force format extraction
'forceprint': dict[str, list], # Force print specific fields
'print_to_file': dict[str, list], # Print to file
'forcejson': bool, # Force JSON output
'dump_single_json': bool, # Dump single JSON
# File output options
'simulate': bool, # Simulate download
'skip_download': bool, # Skip actual download
'logtostderr': bool, # Log to stderr
'writedescription': bool, # Write description file
'writeinfojson': bool, # Write info JSON file
'writeannotations': bool, # Write annotations file
'writelink': bool, # Write link file
'writeurllink': bool, # Write URL link file
'writewebloclink': bool, # Write webloc link file
'writedesktoplink': bool, # Write desktop link file
}Options for handling subtitles, captions, and text content.
# Subtitle options
YDLOptions = {
'writesubtitles': bool, # Write subtitle files
'writeautomaticsub': bool, # Write automatic subtitles
'allsubtitles': bool, # Download all available subtitles
'listsubtitles': bool, # List available subtitles
'subtitlesformat': str, # Subtitle format preference
'subtitleslangs': list[str], # Subtitle language codes
# Caption processing
'getcomments': bool, # Extract comments
'embedsubtitles': bool, # Embed subtitles in video
'convertsubtitles': str, # Convert subtitle format
}Options for handling thumbnail images and visual content.
# Thumbnail options
YDLOptions = {
'writethumbnail': bool, # Write thumbnail file
'write_all_thumbnails': bool, # Write all available thumbnails
'list_thumbnails': bool, # List available thumbnails
'embedthumbnail': bool, # Embed thumbnail in media
'convertthumbnails': str, # Convert thumbnail format
}Advanced options for specialized processing and customization.
# Advanced options
YDLOptions = {
# Extractor options
'allowed_extractors': list[str], # Allowed extractor list
'force_generic_extractor': bool, # Force generic extractor
'default_search': str, # Default search prefix
'age_limit': int, # Age limit for content
'extractor_args': dict, # Extractor-specific arguments
# Processing options
'external_downloader': dict, # External downloader configuration
'external_downloader_args': dict, # External downloader arguments
'postprocessors': list[dict], # Post-processor configuration
'postprocessor_args': dict, # Post-processor arguments
'fixup': str, # Video fixup mode
'merge_output_format': str, # Merge output format
'final_ext': str, # Final file extension
# Experimental options
'dynamic_mpd': bool, # Dynamic MPD support
'hls_prefer_native': bool, # Prefer native HLS
'hls_use_mpegts': bool, # Use MPEGTS for HLS
'hls_split_discontinuity': bool, # Split on HLS discontinuity
'include_ads': bool, # Include advertisements
'mark_watched': bool, # Mark videos as watched
# Hook functions
'progress_hooks': list[callable], # Progress hook functions
'postprocessor_hooks': list[callable], # Post-processor hooks
# Internal options
'test': bool, # Test mode
'keepvideo': bool, # Keep video after extraction
'encoding': str, # Text encoding
}import yt_dlp
# Simple configuration
ydl_opts = {
'format': 'best[height<=720]',
'outtmpl': '%(title)s.%(ext)s',
'writesubtitles': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=example'])import yt_dlp
# Comprehensive configuration
ydl_opts = {
# Format selection
'format': 'best[height<=1080][ext=mp4]/best[height<=1080]/best',
'format_sort': ['res:1080', 'ext:mp4', 'vcodec:h264'],
# Output configuration
'outtmpl': {
'default': '%(uploader)s/%(title)s [%(id)s].%(ext)s',
'playlist': '%(uploader)s - %(playlist)s/%(playlist_index)02d - %(title)s.%(ext)s',
},
'restrictfilenames': True,
'trim_file_name': 200,
# Network settings
'socket_timeout': 30,
'retries': 3,
'sleep_interval': 1,
# Subtitles and metadata
'writesubtitles': True,
'writeautomaticsub': True,
'subtitleslangs': ['en', 'es'],
'writeinfojson': True,
'writethumbnail': True,
# Post-processing
'postprocessors': [
{
'key': 'FFmpegSubtitlesConvertor',
'format': 'srt',
},
{
'key': 'FFmpegMetadata',
'add_metadata': True,
},
{
'key': 'EmbedThumbnail',
},
],
# Progress monitoring
'progress_hooks': [lambda d: print(f"Status: {d['status']}")],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=example'])import yt_dlp
# Playlist-specific configuration
ydl_opts = {
'format': 'best[height<=720]',
'playliststart': 1,
'playlistend': 10,
'outtmpl': '%(playlist_title)s/%(playlist_index)02d - %(title)s.%(ext)s',
'writeinfojson': True,
'extract_flat': False,
'skip_playlist_after_errors': 3,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/playlist?list=example'])import yt_dlp
# Audio-only configuration
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': '%(artist)s - %(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'extractaudio': True,
'audioformat': 'mp3',
'embed_infojson': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=example'])import yt_dlp
# Parse command-line options
args = ['--format', 'best[height<=720]', '--write-subs', 'https://www.youtube.com/watch?v=example']
parsed = yt_dlp.parse_options(args)
print(f"URLs: {parsed.urls}")
print(f"Format: {parsed.ydl_opts.get('format')}")
print(f"Write subs: {parsed.ydl_opts.get('writesubtitles')}")
# Use parsed options
with yt_dlp.YoutubeDL(parsed.ydl_opts) as ydl:
ydl.download(parsed.urls)import yt_dlp
# Network-specific configuration
ydl_opts = {
'proxy': 'http://proxy.example.com:8080',
'socket_timeout': 60,
'source_address': '192.168.1.100',
'http_headers': {
'User-Agent': 'Mozilla/5.0 (Custom User Agent)',
'Accept-Language': 'en-US,en;q=0.9',
},
'retries': 5,
'sleep_interval': 2,
'cookiefile': '/path/to/cookies.txt',
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=example'])# Main configuration options type
YDLOptions = dict[str, Any]
# Parsed options result
class ParsedOptions:
parser: argparse.ArgumentParser
options: argparse.Namespace
urls: list[str]
ydl_opts: YDLOptions
# Progress hook function signature
ProgressHook = Callable[[dict[str, Any]], None]
# Post-processor configuration
PostProcessorDict = dict[str, Any]
# Format selector string patterns
FormatSelector = str # e.g., 'best', 'worst', 'mp4', 'best[height<=720]'
# Output template string with field substitution
OutputTemplate = str # e.g., '%(title)s.%(ext)s'Install with Tessl CLI
npx tessl i tessl/pypi-yt-dlp