CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pysrt

SubRip (.srt) subtitle parser and writer for Python

Pending
Overview
Eval results
Files

command-line.mddocs/

Command Line Tools

Command-line interface for batch subtitle processing. The srt command provides utilities for common subtitle operations including time shifting, framerate conversion, file splitting, and line breaking.

Installation

The command-line tool is automatically installed with the pysrt package:

pip install pysrt

This makes the srt command available in your terminal.

Capabilities

Global Options

Options available for all commands.

srt [global_options] <command> [command_options] <file>

Global Options:
  -i, --in-place          Edit file in-place, saving backup as file.bak
  -e, --output-encoding   Set output file encoding
  -v, --version          Show version information
  -h, --help             Show help message

Time Shifting

Shift all subtitles by a specified time offset.

srt shift [options] <offset> <file>

Arguments:
  offset                 Time offset in format: [-][Hh][Mm]S[s][MSms]
  file                   Input subtitle file

Examples:
  srt shift 2s movie.srt                    # 2 seconds forward
  srt shift -1m30s movie.srt                # 1 minute 30 seconds backward  
  srt shift 500ms movie.srt                 # 500 milliseconds forward
  srt -i shift -2s500ms movie.srt           # 2.5 seconds backward (in-place)

Framerate Conversion

Convert subtitles between different framerates.

srt rate [options] <initial_fps> <final_fps> <file>

Arguments:
  initial_fps            Original framerate (e.g., 23.976)
  final_fps              Target framerate (e.g., 25)
  file                   Input subtitle file

Examples:
  srt rate 23.976 25 movie.srt              # Convert 23.976fps to 25fps
  srt -i rate 25 23.976 movie.srt           # Convert 25fps to 23.976fps (in-place)
  srt rate 30 24 movie.srt > slow_movie.srt # Convert and save to new file

File Splitting

Split subtitle files into multiple parts.

srt split [options] <duration>... <file>

Arguments:
  duration               Duration of each part in format: [Hh][Mm]S[s][MSms]
  file                   Input subtitle file

Output:
  Creates numbered files: basename.1.srt, basename.2.srt, etc.

Examples:
  srt split 45m movie.srt                    # Split at 45 minutes
  srt split 30m 30m movie.srt                # Three parts: 0-30m, 30m-60m, 60m-end
  srt split 1h30m movie.srt                  # Split at 1 hour 30 minutes

Line Breaking

Break long subtitle lines at word boundaries.

srt break [options] <max_length> <file>

Arguments:
  max_length             Maximum characters per line
  file                   Input subtitle file

Examples:
  srt break 40 movie.srt                     # Break lines longer than 40 characters
  srt -i break 32 movie.srt                  # Break lines (in-place edit)
  srt break 50 movie.srt > formatted.srt     # Break lines and save to new file

Time Format Specification

All commands use a flexible time format for specifying durations and offsets:

Time Format: [-][Hh][Mm]S[s][MSms]

Components (all optional):
  -          Negative (backward) time
  H, h       Hours
  M, m       Minutes  
  S, s       Seconds (default unit if no suffix)
  MS, ms     Milliseconds

Examples:
  5          5 seconds
  1m30s      1 minute 30 seconds
  -2s500ms   2.5 seconds backward  
  1h15m      1 hour 15 minutes
  750ms      750 milliseconds
  2h30m45s   2 hours 30 minutes 45 seconds

Usage Examples

Basic Operations

# Simple time adjustments
srt shift 2s movie.srt > delayed_movie.srt
srt shift -1s500ms movie.srt > advanced_movie.srt

# In-place editing with backup
srt -i shift 3s movie.srt  # Creates movie.srt.bak

# Framerate conversion for different media
srt rate 23.976 25 ntsc_movie.srt > pal_movie.srt

File Processing Workflows

# Split long movie into parts  
srt split 50m long_movie.srt
# Creates: long_movie.1.srt, long_movie.2.srt, long_movie.3.srt

# Format subtitles for small screens
srt break 30 movie.srt > mobile_movie.srt

# Chain operations using pipes
srt shift 1s movie.srt | srt break 40 > processed_movie.srt

Encoding Handling

# Convert encoding while processing
srt -e latin1 shift 2s utf8_movie.srt > latin1_movie.srt

# Process files with specific input encoding
# (Automatic detection usually works, but can be overridden in code)

Batch Processing

# Process multiple files
for file in *.srt; do
  srt -i shift 1s500ms "$file"
done

# Split all movies in directory
for movie in *.srt; do
  srt split 45m "$movie"
done

# Convert all subtitles for different framerate
for sub in *.srt; do
  srt rate 25 23.976 "$sub" > "ntsc_${sub}"
done

Advanced Examples

# Complex timing adjustment
srt shift -2m30s500ms movie.srt > synced_movie.srt

# Multi-part processing
srt split 1h movie.srt                    # Split into 1-hour parts
srt -i shift 500ms movie.1.srt            # Adjust first part
srt -i shift 1s movie.2.srt               # Different adjustment for second part

# Format for specific display requirements
srt break 25 movie.srt | srt shift 2s > tv_movie.srt

# Prepare subtitles for different distributions
srt rate 25 23.976 movie.srt > movie_ntsc.srt     # NTSC version
srt rate 25 24 movie.srt > movie_film.srt         # Film version
srt -e latin1 shift 0 movie.srt > movie_compat.srt # Compatibility version

Error Handling

The command-line tool provides informative error messages:

# File not found
$ srt shift 2s nonexistent.srt
No such file nonexistent.srt

# Invalid time format  
$ srt shift 99x movie.srt
# Will show usage help and error message

# Encoding issues
$ srt -e invalid_encoding shift 1s movie.srt  
# Will report encoding error

Integration with Scripts

Shell Scripting

#!/bin/bash
# Subtitle processing script

input_file="$1"
delay="${2:-2s}"  # Default 2 second delay

if [[ ! -f "$input_file" ]]; then
    echo "Error: File $input_file not found"
    exit 1
fi

# Create processed version
echo "Processing $input_file with $delay delay..."
srt shift "$delay" "$input_file" > "processed_$(basename "$input_file")"

# Also create formatted version
srt break 40 "processed_$(basename "$input_file")" > "formatted_$(basename "$input_file")"

echo "Created processed and formatted versions"

Python Integration

import subprocess
import sys

def process_subtitle_cli(input_file, delay="2s"):
    """Process subtitle using command-line tool"""
    try:
        result = subprocess.run([
            'srt', 'shift', delay, input_file
        ], capture_output=True, text=True, check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Error processing subtitle: {e.stderr}")
        return None

# Usage
processed_content = process_subtitle_cli('movie.srt', '1s500ms')
if processed_content:
    with open('processed_movie.srt', 'w') as f:
        f.write(processed_content)

Makefile Integration

# Subtitle processing Makefile

SUBTITLES = $(wildcard *.srt)
PROCESSED = $(SUBTITLES:.srt=_processed.srt)
MOBILE = $(SUBTITLES:.srt=_mobile.srt)

# Process all subtitles with 2 second delay
processed: $(PROCESSED)

%_processed.srt: %.srt
	srt shift 2s $< > $@

# Create mobile-friendly versions  
mobile: $(MOBILE)

%_mobile.srt: %.srt
	srt break 30 $< > $@

# Clean up generated files
clean:
	rm -f *_processed.srt *_mobile.srt

.PHONY: processed mobile clean

Comparison with Library Usage

While the command-line tool is convenient for batch operations, the Python library offers more flexibility:

# Command line equivalent: srt shift 2s movie.srt
import pysrt
subs = pysrt.open('movie.srt')
subs.shift(seconds=2)
subs.save('processed_movie.srt')

# Command line equivalent: srt rate 25 23.976 movie.srt  
subs = pysrt.open('movie.srt')
subs.shift(ratio=23.976/25)
subs.save('converted_movie.srt')

# More complex operations not available via CLI
subs = pysrt.open('movie.srt')
for item in subs:
    if item.duration.ordinal < 1000:  # Less than 1 second
        item.end += pysrt.SubRipTime(milliseconds=500)
subs.save('extended_movie.srt')

Install with Tessl CLI

npx tessl i tessl/pypi-pysrt

docs

command-line.md

index.md

subtitle-files.md

subtitle-items.md

time-handling.md

tile.json