SubRip (.srt) subtitle parser and writer for Python
npx @tessl/cli install tessl/pypi-pysrt@1.1.0A comprehensive Python library for parsing, editing, and creating SubRip (.srt) subtitle files. PySRT provides high-level APIs for loading subtitle files with automatic encoding detection, manipulating subtitle timing and content through object-oriented interfaces, and performing common operations like time shifting, splitting, and rescaling subtitles.
pip install pysrtimport pysrtFor direct access to main classes:
from pysrt import SubRipFile, SubRipItem, SubRipTimeFor exceptions:
from pysrt import Error, InvalidItem, InvalidTimeStringimport pysrt
# Load a subtitle file with automatic encoding detection
subs = pysrt.open('movie.srt')
# Access individual subtitle items
first_sub = subs[0]
print(f"Start: {first_sub.start}, End: {first_sub.end}")
print(f"Text: {first_sub.text}")
# Modify subtitle content
first_sub.text = "Modified subtitle text"
# Shift all subtitles by 2 seconds forward
subs.shift(seconds=2)
# Get subtitles visible at specific timestamp
current_subs = subs.at(seconds=30)
# Save modified subtitles
subs.save('modified_movie.srt')
# Create subtitles from scratch
new_subs = pysrt.SubRipFile()
new_subs.append(pysrt.SubRipItem(
index=1,
start=pysrt.SubRipTime(0, 0, 1, 500), # 00:00:01,500
end=pysrt.SubRipTime(0, 0, 5, 0), # 00:00:05,000
text="Hello, World!"
))
new_subs.save('new_subtitles.srt')PySRT is built around three core classes that represent the hierarchy of subtitle data:
The library supports both programmatic access through Python classes and command-line tools for batch processing, with robust error handling for malformed subtitle files and automatic encoding detection for maximum compatibility.
File-level operations including opening, parsing, saving subtitle files, and batch operations like shifting, slicing, and cleaning subtitle collections.
class SubRipFile:
def __init__(self, items=None, eol=None, path=None, encoding='utf-8'): ...
@classmethod
def open(cls, path='', encoding=None, error_handling=0): ...
@classmethod
def from_string(cls, source, **kwargs): ...
def save(self, path=None, encoding=None, eol=None): ...
def shift(self, *args, **kwargs): ...
def slice(self, starts_before=None, starts_after=None, ends_before=None, ends_after=None): ...
def at(self, timestamp=None, **kwargs): ...Individual subtitle manipulation including timing, text content, positioning, and per-item operations like shifting and duration calculations.
class SubRipItem:
def __init__(self, index=0, start=None, end=None, text='', position=''): ...
@classmethod
def from_string(cls, source): ...
def shift(self, *args, **kwargs): ...
@property
def duration(self): ...
@property
def text_without_tags(self): ...Time representation and manipulation with support for arithmetic operations, format conversion, and coercion from various input types.
class SubRipTime:
def __init__(self, hours=0, minutes=0, seconds=0, milliseconds=0): ...
@classmethod
def coerce(cls, other): ...
@classmethod
def from_string(cls, source): ...
def shift(self, *args, **kwargs): ...
def to_time(self): ...Command-line interface for batch subtitle processing including time shifting, framerate conversion, file splitting, and line breaking.
srt shift [-i] <offset> <file>
srt rate [-i] <initial_fps> <final_fps> <file>
srt split [-i] <durations...> <file>
srt break [-i] <max_line_length> <file>PySRT provides structured exception handling for common subtitle parsing and processing errors:
class Error(Exception): ...
class InvalidItem(Error): ...
class InvalidTimeString(Error): ...
class InvalidIndex(InvalidItem): ...Error handling modes can be configured when opening files:
# Pass errors silently (default)
subs = pysrt.open('file.srt', error_handling=pysrt.ERROR_PASS)
# Log errors to stderr
subs = pysrt.open('file.srt', error_handling=pysrt.ERROR_LOG)
# Raise exceptions on errors
subs = pysrt.open('file.srt', error_handling=pysrt.ERROR_RAISE)Convenience functions available directly from the pysrt module for common operations.
def open(path='', encoding=None, error_handling=0):
"""
Open and parse a SubRip file from filesystem.
Convenience function that calls SubRipFile.open().
Args:
path (str): Path to subtitle file
encoding (str, optional): File encoding (auto-detected if None)
error_handling (int): Error handling mode (ERROR_PASS/ERROR_LOG/ERROR_RAISE)
Returns:
SubRipFile: Parsed subtitle file
"""
def stream(source_file, error_handling=0):
"""
Generator that yields SubRipItem instances as they are parsed.
Convenience function that calls SubRipFile.stream().
Args:
source_file: Iterable yielding unicode strings (file-like object)
error_handling (int): Error handling mode
Yields:
SubRipItem: Parsed subtitle items
"""
def from_string(source, **kwargs):
"""
Create SubRipFile from string content.
Convenience function that calls SubRipFile.from_string().
Args:
source (str): Subtitle content as string
**kwargs: Additional arguments passed to SubRipFile constructor
Returns:
SubRipFile: Parsed subtitle file
"""# Error handling constants
ERROR_PASS: int = 0
ERROR_LOG: int = 1
ERROR_RAISE: int = 2
# Version information
VERSION: tuple = (1, 0, 1)
VERSION_STRING: str = "1.0.1"