A feature-rich command-line audio/video downloader forked from youtube-dl
The YoutubeDL class is the central interface for all download and extraction operations. It manages configuration, coordinates extractors and post-processors, handles progress reporting, and provides comprehensive download functionality.
The main API class that handles downloads, extraction, and coordination of all yt-dlp functionality.
class YoutubeDL:
"""
Main yt-dlp class for downloading and extracting video information.
Manages configuration, coordinates extractors and post-processors,
handles progress reporting, and provides comprehensive download functionality.
"""
def __init__(self, params=None, auto_init=True):
"""
Initialize YoutubeDL instance.
Parameters:
- params: dict, configuration options (see YDLOptions type)
- auto_init: bool, whether to initialize automatically
"""
def __enter__(self):
"""Context manager entry."""
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
def close(self):
"""Clean up resources and close connections."""Primary methods for downloading content from URLs with various configuration options.
def download(self, url_list):
"""
Download from a list of URLs.
Parameters:
- url_list: list[str], URLs to download
Returns:
int: Exit code (0 for success, non-zero for errors)
"""
def download_with_info_file(self, info_filename):
"""
Download using information from a saved info file.
Parameters:
- info_filename: str, path to info file
Returns:
int: exit code
"""Methods for extracting metadata and processing information without necessarily downloading files.
def extract_info(self, url, download=True, ie_key=None, extra_info=None, process=True, force_generic_extractor=False):
"""
Extract information from URL and optionally download.
Parameters:
- url: str, URL to extract from
- download: bool, whether to download files
- ie_key: str|None, specific extractor to use
- extra_info: dict|None, additional information
- process: bool, whether to process extracted info
- force_generic_extractor: bool, force generic extractor
Returns:
dict: extracted information dictionary
"""
def process_ie_result(self, ie_result, download=True, extra_info=None):
"""
Process result from information extractor.
Parameters:
- ie_result: dict, result from extractor
- download: bool, whether to download files
- extra_info: dict|None, additional information
Returns:
dict: processed information
"""
def process_video_result(self, info_dict, download=True):
"""
Process information for a single video.
Parameters:
- info_dict: dict, video information
- download: bool, whether to download
Returns:
dict: processed video information
"""
@staticmethod
def sanitize_info(info_dict, remove_private_keys=False):
"""
Clean and sanitize information dictionary.
Parameters:
- info_dict: dict, information to sanitize
- remove_private_keys: bool, remove private keys
Returns:
dict: sanitized information
"""Methods for generating output filenames and processing output templates.
def prepare_filename(self, info_dict, dir_type='', *, outtmpl=None, warn=False):
"""
Generate output filename from template and info.
Parameters:
- info_dict: dict, video information
- dir_type: str, directory type for template
- outtmpl: str|None, custom output template
- warn: bool, whether to warn on issues
Returns:
str: generated filename
"""
def prepare_outtmpl(self, outtmpl, info_dict, sanitize=False):
"""
Process output template with information.
Parameters:
- outtmpl: str, output template string
- info_dict: dict, information for substitution
- sanitize: bool, whether to sanitize filename
Returns:
str: processed template
"""
@classmethod
def validate_outtmpl(cls, outtmpl):
"""
Validate output template syntax.
Parameters:
- outtmpl: str, template to validate
Returns:
str|None: error message if invalid, None if valid
"""Methods for managing and interacting with the extractor system.
def add_info_extractor(self, ie):
"""
Register a custom information extractor.
Parameters:
- ie: InfoExtractor, extractor instance to add
"""
def get_info_extractor(self, ie_key):
"""
Get information extractor by key.
Parameters:
- ie_key: str, extractor key/name
Returns:
InfoExtractor: extractor instance
"""
def add_default_info_extractors(self):
"""Load and register all built-in extractors."""Methods for managing the post-processing pipeline.
def add_post_processor(self, pp, when='post_process'):
"""
Add a post-processor to the pipeline.
Parameters:
- pp: PostProcessor, processor to add
- when: str, when to run ('post_process', 'after_move', etc.)
"""
def run_pp(self, pp, infodict):
"""
Run a single post-processor.
Parameters:
- pp: PostProcessor, processor to run
- infodict: dict, information dictionary
Returns:
tuple: (updated_info_dict, list_of_files_to_delete)
"""
def run_all_pps(self, key, info, *, additional_pps=None):
"""
Run all applicable post-processors.
Parameters:
- key: str, processing phase key
- info: dict, information dictionary
- additional_pps: list|None, additional processors
Returns:
dict: updated information dictionary
"""Methods for setting up callbacks and monitoring download progress.
def add_progress_hook(self, ph):
"""
Add download progress callback.
Parameters:
- ph: ProgressHook, callback function
"""
def add_post_hook(self, ph):
"""
Add post-download callback.
Parameters:
- ph: PostProcessorHook, callback function
"""
def add_postprocessor_hook(self, ph):
"""
Add post-processor callback.
Parameters:
- ph: PostProcessorHook, callback function
"""Methods for controlling output and logging behavior.
def to_screen(self, message, skip_eol=False, quiet=None, only_once=False):
"""
Print message to terminal/screen.
Parameters:
- message: str, message to print
- skip_eol: bool, skip end of line
- quiet: bool|None, override quiet setting
- only_once: bool, show message only once
"""
def to_stdout(self, message, skip_eol=False, quiet=None):
"""
Print message to stdout.
Parameters:
- message: str, message to print
- skip_eol: bool, skip end of line
- quiet: bool|None, override quiet setting
"""
def to_stderr(self, message, skip_eol=False, quiet=None):
"""
Print message to stderr.
Parameters:
- message: str, message to print
- skip_eol: bool, skip end of line
- quiet: bool|None, override quiet setting
"""
def write_debug(self, message, only_once=False):
"""
Write debug information.
Parameters:
- message: str, debug message
- only_once: bool, write only once per message
"""
def report_warning(self, message, only_once=False):
"""
Report warning message.
Parameters:
- message: str, warning message
- only_once: bool, show warning only once
"""
def report_error(self, message, *args, **kwargs):
"""
Report error message.
Parameters:
- message: str, error message
- *args: additional positional arguments
- **kwargs: additional keyword arguments
"""Methods for network operations and accessing utility functionality.
def urlopen(self, req):
"""
Make HTTP request using configured settings.
Parameters:
- req: Request, request object
Returns:
response object
"""
@property
def cache(self):
"""
Access to cache system.
Returns:
Cache: cache instance
"""import yt_dlp
# Configure download options
ydl_opts = {
'format': 'best[height<=720]',
'outtmpl': '%(uploader)s - %(title)s.%(ext)s',
'writesubtitles': True,
'writeautomaticsub': True,
}
# Download with options
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=example'])import yt_dlp
# Extract information without downloading
ydl_opts = {'skip_download': True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info('https://www.youtube.com/watch?v=example')
print(f"Title: {info['title']}")
print(f"Duration: {info['duration']} seconds")
print(f"Uploader: {info['uploader']}")
print(f"Upload date: {info['upload_date']}")
print(f"Available formats: {len(info['formats'])}")import yt_dlp
def progress_hook(d):
if d['status'] == 'downloading':
print(f"Downloading: {d['_percent_str']} of {d['_total_bytes_str']}")
elif d['status'] == 'finished':
print(f"Downloaded: {d['filename']}")
ydl_opts = {
'progress_hooks': [progress_hook],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=example'])import yt_dlp
ydl_opts = {
'outtmpl': {
'default': '%(uploader)s/%(title)s [%(id)s].%(ext)s',
'playlist': '%(uploader)s - %(playlist)s/%(playlist_index)02d - %(title)s.%(ext)s',
}
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/playlist?list=example'])# Configuration options dictionary for YoutubeDL
YDLOptions = dict[str, Any]
# Information dictionary returned by extractors
InfoDict = dict[str, Any]
# Progress hook function signature
ProgressHook = Callable[[dict[str, Any]], None]
# Post-processor hook function signature
PostProcessorHook = Callable[[dict[str, Any]], None]Install with Tessl CLI
npx tessl i tessl/pypi-yt-dlp