2026-07-035 min readpython m3u8 download, python script m3u8, m3u8 download script

Writing a Python Script to Download M3U8 Streams

Create a Python script to download and merge M3U8/HLS streams. Automate downloading with custom logic and error handling.

Using the m3u8 Python Library

The m3u8 Python library makes it easy to parse and download HLS streams:

import m3u8
import requests

# Parse the playlist
playlist = m3u8.load('https://example.com/stream.m3u8')

# Download all segments
segments = []
for segment in playlist.segments:
resp = requests.get(segment.uri)
segments.append(resp.content)

# Merge and save
with open('output.ts', 'wb') as f:
for seg in segments:
f.write(seg)

Complete Download Script

A more complete script with progress tracking:

import m3u8, requests, os
from concurrent.futures import ThreadPoolExecutor

def download_m3u8(url, output="output.mp4"):
playlist = m3u8.load(url)
base_url = "/".join(url.split("/")[:-1]) + "/"

def fetch_seg(seg):
seg_url = seg.uri if seg.uri.startswith("http") else base_url + seg.uri
resp = requests.get(seg_url)
return resp.content

print(f"Downloading {len(playlist.segments)} segments...")
with ThreadPoolExecutor(max_workers=8) as executor:
data = list(executor.map(fetch_seg, playlist.segments))

print("Merging...")
with open(output, 'wb') as f:
for seg_data in data:
f.write(seg_data)
print(f"Saved to {output}")

Using FFmpeg from Python

For production use, it's easier to call FFmpeg from Python:

import subprocess

def download_m3u8(url, output="output.mp4"):
cmd = [
'ffmpeg', '-i', url,
'-c', 'copy',
'-bsf:a', 'aac_adtstoasc',
output
]
subprocess.run(cmd, check=True)

download_m3u8('https://example.com/stream.m3u8')

Related Articles