Speedtest CLI for Python

2.1.3 · active · verified Thu Apr 16

speedtest-cli is a Python library that provides a command-line interface for testing internet bandwidth using speedtest.net. The current version is 2.1.3, and the library maintains an active release cadence with frequent bug fixes and minor improvements. It can also be used programmatically within Python applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import the `speedtest` module, initialize the `Speedtest` object, find the best server, and then measure download and upload speeds programmatically. The speeds are converted to a human-readable format for clarity.

import speedtest
import os

def human_readable_bytes(nbytes):
    suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
    i = 0
    while nbytes >= 1024 and i < len(suffixes)-1:
        nbytes /= 1024
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
    return '%s %s' % (f, suffixes[i])

print('Starting Speedtest...')
st = speedtest.Speedtest()

# Find best server based on ping
print('Finding best server...')
st.get_best_server()
print(f'Hosted by {st.results.server['sponsor']} ({st.results.server['name']}) [Ping: {st.results.ping:.2f} ms]')

# Test download speed
print('Testing download speed...')
download_speed_bps = st.download()
download_speed_mbps = download_speed_bps / 1_000_000 # Convert to Mbps
print(f'Download: {human_readable_bytes(download_speed_bps)} ({download_speed_mbps:.2f} Mbps)')

# Test upload speed
print('Testing upload speed...')
upload_speed_bps = st.upload()
upload_speed_mbps = upload_speed_bps / 1_000_000 # Convert to Mbps
print(f'Upload: {human_readable_bytes(upload_speed_bps)} ({upload_speed_mbps:.2f} Mbps)')

# Get full results (optional)
# results = st.results.dict()
# print(results)

view raw JSON →