0
# PySRT
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: pysrt
7
- **Language**: Python
8
- **Installation**: `pip install pysrt`
9
- **License**: GPLv3
10
- **Python Support**: 2.7, 3.4+
11
12
## Core Imports
13
14
```python
15
import pysrt
16
```
17
18
For direct access to main classes:
19
20
```python
21
from pysrt import SubRipFile, SubRipItem, SubRipTime
22
```
23
24
For exceptions:
25
26
```python
27
from pysrt import Error, InvalidItem, InvalidTimeString
28
```
29
30
## Basic Usage
31
32
```python
33
import pysrt
34
35
# Load a subtitle file with automatic encoding detection
36
subs = pysrt.open('movie.srt')
37
38
# Access individual subtitle items
39
first_sub = subs[0]
40
print(f"Start: {first_sub.start}, End: {first_sub.end}")
41
print(f"Text: {first_sub.text}")
42
43
# Modify subtitle content
44
first_sub.text = "Modified subtitle text"
45
46
# Shift all subtitles by 2 seconds forward
47
subs.shift(seconds=2)
48
49
# Get subtitles visible at specific timestamp
50
current_subs = subs.at(seconds=30)
51
52
# Save modified subtitles
53
subs.save('modified_movie.srt')
54
55
# Create subtitles from scratch
56
new_subs = pysrt.SubRipFile()
57
new_subs.append(pysrt.SubRipItem(
58
index=1,
59
start=pysrt.SubRipTime(0, 0, 1, 500), # 00:00:01,500
60
end=pysrt.SubRipTime(0, 0, 5, 0), # 00:00:05,000
61
text="Hello, World!"
62
))
63
new_subs.save('new_subtitles.srt')
64
```
65
66
## Architecture
67
68
PySRT is built around three core classes that represent the hierarchy of subtitle data:
69
70
- **SubRipFile**: Container for entire subtitle file with file I/O and batch operations
71
- **SubRipItem**: Individual subtitle entry with timing, text, and positioning
72
- **SubRipTime**: Time representation supporting arithmetic and various input formats
73
74
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.
75
76
## Capabilities
77
78
### Subtitle Files
79
80
File-level operations including opening, parsing, saving subtitle files, and batch operations like shifting, slicing, and cleaning subtitle collections.
81
82
```python { .api }
83
class SubRipFile:
84
def __init__(self, items=None, eol=None, path=None, encoding='utf-8'): ...
85
@classmethod
86
def open(cls, path='', encoding=None, error_handling=0): ...
87
@classmethod
88
def from_string(cls, source, **kwargs): ...
89
def save(self, path=None, encoding=None, eol=None): ...
90
def shift(self, *args, **kwargs): ...
91
def slice(self, starts_before=None, starts_after=None, ends_before=None, ends_after=None): ...
92
def at(self, timestamp=None, **kwargs): ...
93
```
94
95
[Subtitle Files](./subtitle-files.md)
96
97
### Subtitle Items
98
99
Individual subtitle manipulation including timing, text content, positioning, and per-item operations like shifting and duration calculations.
100
101
```python { .api }
102
class SubRipItem:
103
def __init__(self, index=0, start=None, end=None, text='', position=''): ...
104
@classmethod
105
def from_string(cls, source): ...
106
def shift(self, *args, **kwargs): ...
107
@property
108
def duration(self): ...
109
@property
110
def text_without_tags(self): ...
111
```
112
113
[Subtitle Items](./subtitle-items.md)
114
115
### Time Handling
116
117
Time representation and manipulation with support for arithmetic operations, format conversion, and coercion from various input types.
118
119
```python { .api }
120
class SubRipTime:
121
def __init__(self, hours=0, minutes=0, seconds=0, milliseconds=0): ...
122
@classmethod
123
def coerce(cls, other): ...
124
@classmethod
125
def from_string(cls, source): ...
126
def shift(self, *args, **kwargs): ...
127
def to_time(self): ...
128
```
129
130
[Time Handling](./time-handling.md)
131
132
### Command Line Tools
133
134
Command-line interface for batch subtitle processing including time shifting, framerate conversion, file splitting, and line breaking.
135
136
```bash { .api }
137
srt shift [-i] <offset> <file>
138
srt rate [-i] <initial_fps> <final_fps> <file>
139
srt split [-i] <durations...> <file>
140
srt break [-i] <max_line_length> <file>
141
```
142
143
[Command Line Tools](./command-line.md)
144
145
## Error Handling
146
147
PySRT provides structured exception handling for common subtitle parsing and processing errors:
148
149
```python { .api }
150
class Error(Exception): ...
151
class InvalidItem(Error): ...
152
class InvalidTimeString(Error): ...
153
class InvalidIndex(InvalidItem): ...
154
```
155
156
Error handling modes can be configured when opening files:
157
158
```python
159
# Pass errors silently (default)
160
subs = pysrt.open('file.srt', error_handling=pysrt.ERROR_PASS)
161
162
# Log errors to stderr
163
subs = pysrt.open('file.srt', error_handling=pysrt.ERROR_LOG)
164
165
# Raise exceptions on errors
166
subs = pysrt.open('file.srt', error_handling=pysrt.ERROR_RAISE)
167
```
168
169
## Module-Level Functions
170
171
Convenience functions available directly from the pysrt module for common operations.
172
173
```python { .api }
174
def open(path='', encoding=None, error_handling=0):
175
"""
176
Open and parse a SubRip file from filesystem.
177
Convenience function that calls SubRipFile.open().
178
179
Args:
180
path (str): Path to subtitle file
181
encoding (str, optional): File encoding (auto-detected if None)
182
error_handling (int): Error handling mode (ERROR_PASS/ERROR_LOG/ERROR_RAISE)
183
184
Returns:
185
SubRipFile: Parsed subtitle file
186
"""
187
188
def stream(source_file, error_handling=0):
189
"""
190
Generator that yields SubRipItem instances as they are parsed.
191
Convenience function that calls SubRipFile.stream().
192
193
Args:
194
source_file: Iterable yielding unicode strings (file-like object)
195
error_handling (int): Error handling mode
196
197
Yields:
198
SubRipItem: Parsed subtitle items
199
"""
200
201
def from_string(source, **kwargs):
202
"""
203
Create SubRipFile from string content.
204
Convenience function that calls SubRipFile.from_string().
205
206
Args:
207
source (str): Subtitle content as string
208
**kwargs: Additional arguments passed to SubRipFile constructor
209
210
Returns:
211
SubRipFile: Parsed subtitle file
212
"""
213
```
214
215
## Types
216
217
```python { .api }
218
# Error handling constants
219
ERROR_PASS: int = 0
220
ERROR_LOG: int = 1
221
ERROR_RAISE: int = 2
222
223
# Version information
224
VERSION: tuple = (1, 0, 1)
225
VERSION_STRING: str = "1.0.1"
226
```