How to Use Pyutube Programmatically: A Complete Python Guide
Import DownloadService from pyutube.services and call download_preparing() followed by download_video() or download_audio() to download YouTube content without touching the command line.
Pyutube is an open-source Python library that wraps YouTube download logic into reusable service classes. While many users interact with it via the CLI entry point in pyutube/cli.py, the hetari/pyutube repository is designed to be imported directly into your Python projects. This guide shows you how to use Pyutube programmatically to automate downloads, customize resolution selection, and handle playlists.
Understanding Pyutube's Architecture
Pyutube abstracts YouTube interactions into a layered architecture. At the entry point, pyutube.handlers.URLHandler validates links and determines whether the target is a single video, short, or playlist. The orchestration layer lives in pyutube.services.DownloadService, which coordinates specialized handlers:
pyutube.services.VideoService– Fetches available streams, handles resolution selection, and merges video with audio tracks when necessary.pyutube.services.AudioService– Retrieves the best audio-only stream for music downloads.pyutube.services.FileService– Generates safe filenames, resolves naming conflicts, and writes bytes to disk.
Utility functions in pyutube.utils provide console UI helpers, internet connectivity checks, and update notifications.
Downloading Single Videos Programmatically
The most common use case is downloading a single video without interactive prompts. Instantiate DownloadService with your target URL, output directory, and desired quality.
from pyutube.services import DownloadService
url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
output_dir = "/tmp/downloads"
quality = "720p" # Set to None to trigger interactive selection
is_audio = False
# Initialize the service
dl = DownloadService(url, output_dir, quality, is_audio)
# Prepare download: fetches metadata and available streams
video, video_id, streams, audio_stream, chosen_quality = dl.download_preparing()
# Execute the download
if is_audio:
dl.download_audio(video, audio_stream, video_id)
else:
video_file = dl.video_service.get_video_streams(chosen_quality, streams)
dl.download_video(video, video_id, video_file, audio_stream)
This pattern bypasses the CLI layer in pyutube/cli.py while retaining all stream handling and file management logic.
Bulk Downloading Playlists
To process entire playlists, pass a playlist URL to DownloadService and invoke get_playlist_links(). This method leverages pyutube/handlers/PlaylistHandler.py to parse the playlist page, enumerate videos, and handle ordering.
from pyutube.services import DownloadService
playlist_url = "https://www.youtube.com/playlist?list=PL..."
output_dir = "/tmp/playlist"
dl = DownloadService(playlist_url, output_dir, None) # None for quality prompts per video
dl.get_playlist_links() # Handles all playlist logic, ordering, and downloads
The service automatically iterates through the playlist, applying the same download preparation and execution logic used for single videos.
Custom Resolution Selection Without Prompts
For fully automated pipelines where interactive prompts are unacceptable, use VideoService directly to inspect available resolutions before downloading. This approach uses pyutube/services/VideoService.py to expose stream metadata.
from pyutube.services import DownloadService, VideoService
from pyutube.services import FileService
from pytubefix import YouTube
url = "https://www.youtube.com/watch?v=example"
# Initialize services
dl = DownloadService(url, "/tmp", None)
vs = VideoService(url, None, "/tmp")
# Access the underlying YouTube object
yt = dl.video # or create manually: YouTube(url)
# Get available resolutions and metadata
resolutions, sizes, streams, audio_stream = vs.get_available_resolutions(yt)
# Automatically select highest resolution
best_quality = max(resolutions, key=lambda r: int(r.rstrip('p')))
video_stream = vs.get_video_streams(best_quality, streams)
# Save directly using FileService
FileService().save_file(video_stream, f"{yt.title}_{best_quality}.mp4", "/tmp")
This granular control allows you to implement custom logic—such as filtering by file size, resolution caps, or specific codecs—before committing to the download.
Utility Functions for Automation
The pyutube/utils.py module provides helper functions useful for headless automation, such as checking internet connectivity before attempting downloads.
from pyutube.utils import check_internet_connection, clear
if check_internet_connection():
clear() # Clears terminal cross-platform
# Proceed with download logic
else:
print("No internet connection available")
These utilities ensure your programmatic scripts handle environment prerequisites gracefully.
Key Source Files and Their Roles
Understanding the codebase structure helps when extending functionality or debugging:
| File | Role |
|---|---|
pyutube/cli.py |
Typer-based command-line entry point that wraps the service layer. |
pyutube/services/DownloadService.py |
High-level orchestration of downloads and playlist handling. |
pyutube/services/VideoService.py |
Video stream selection, resolution handling, and audio merging. |
pyutube/services/AudioService.py |
Retrieves best audio-only streams. |
pyutube/services/FileService.py |
Safe filename generation, conflict resolution, and disk writes. |
pyutube/handlers/URLHandler.py |
Validates URLs and determines content type (video, short, playlist). |
pyutube/handlers/PlaylistHandler.py |
Parses playlist pages and manages video ordering. |
pyutube/utils.py |
Console UI helpers, internet checks, and update notifications. |
Summary
- Import
DownloadServicefrompyutube.servicesto orchestrate downloads without CLI interaction. - Call
download_preparing()to fetch metadata and available streams before executing the download. - Use
VideoServicedirectly for custom resolution selection logic when you need to avoid interactive prompts. - Process playlists by passing a playlist URL to
DownloadServiceand invokingget_playlist_links(). - Leverage
FileServiceandutilsfor filename management and environment validation in automated scripts.
Frequently Asked Questions
Can I use Pyutube without the command line?
Yes. While Pyutube provides a CLI interface in pyutube/cli.py, the library is designed for programmatic use. Import DownloadService, VideoService, or AudioService from pyutube.services to execute downloads directly from your Python scripts without spawning shell processes.
How do I select specific video resolutions programmatically?
To avoid interactive prompts, instantiate VideoService directly and call get_available_resolutions() with a YouTube object. This returns available resolutions, file sizes, and stream objects. You can then pass your chosen quality to get_video_streams() and save the file via FileService().save_file().
Is it possible to download entire playlists with Pyutube?
Yes. Pass a playlist URL to DownloadService and call get_playlist_links(). This method uses pyutube/handlers/PlaylistHandler.py to parse the playlist, enumerate videos, and process each item sequentially using the same download logic available for single videos.
What is the difference between DownloadService and VideoService?
DownloadService is the high-level orchestrator that handles URL validation, playlist processing, and coordinates between audio and video downloads. VideoService is a specialized component focused specifically on video stream inspection, resolution selection, and video-audio merging. Use DownloadService for standard workflows; use VideoService directly when you need granular control over stream selection.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →