Command line interface for testing internet bandwidth using speedtest.net
—
Primary speed testing functionality through the Speedtest class. Provides comprehensive bandwidth measurement capabilities with server selection, configuration management, and concurrent testing support.
import speedtestMain class for performing internet speed tests with full control over configuration, server selection, and test execution.
class Speedtest:
def __init__(self, config=None, source_address=None, timeout=10, secure=False, shutdown_event=None):
"""
Initialize Speedtest instance.
Parameters:
- config (dict, optional): Custom configuration dictionary
- source_address (str, optional): Source address to bind to
- timeout (int): Request timeout in seconds (default: 10)
- secure (bool): Use HTTPS connections (default: False)
- shutdown_event (threading.Event, optional): Event for graceful shutdown
"""Properties:
best (dict): Best server information (lazy-loaded)config (dict): Configuration dictionary with client info and settingsservers (dict): Available servers grouped by distanceclosest (list): List of closest serversresults (SpeedtestResults): Test results objectlat_lon (tuple): Client coordinates (latitude, longitude)Download and manage speedtest.net configuration including client information and server endpoints.
def get_config(self):
"""
Download speedtest configuration from speedtest.net.
Returns:
dict: Configuration containing client info, server URLs, and timing settings
Raises:
ConfigRetrievalError: Failed to download configuration
"""Usage example:
s = speedtest.Speedtest()
config = s.get_config()
print(f"Client IP: {config['client']['ip']}")
print(f"ISP: {config['client']['isp']}")Retrieve and manage available speed test servers with filtering and selection capabilities.
def get_servers(self, servers=None, exclude=None):
"""
Retrieve list of speedtest.net servers.
Parameters:
- servers (list, optional): List of server IDs to retrieve
- exclude (list, optional): List of server IDs to exclude
Returns:
dict: Servers grouped by distance from client
Raises:
ServersRetrievalError: Failed to retrieve server list
NoMatchedServers: No servers match provided criteria
"""
def get_closest_servers(self, limit=5):
"""
Get closest servers by geographic distance.
Parameters:
- limit (int): Maximum number of servers to return (default: 5)
Returns:
list: List of closest server dictionaries sorted by distance
"""
def get_best_server(self, servers=None):
"""
Determine best server by latency testing.
Parameters:
- servers (list, optional): List of servers to test (default: closest servers)
Returns:
dict: Best server information
Raises:
SpeedtestBestServerFailure: Failed to determine best server
"""Usage example:
s = speedtest.Speedtest()
s.get_servers()
# Get 10 closest servers
closest = s.get_closest_servers(limit=10)
print(f"Found {len(closest)} closest servers")
# Auto-select best server
best = s.get_best_server()
print(f"Best server: {best['sponsor']} in {best['name']}")Support for testing against custom speedtest Mini servers.
def set_mini_server(self, server):
"""
Set Mini server URL for testing.
Parameters:
- server (str): Mini server URL
Raises:
InvalidSpeedtestMiniServer: Invalid Mini server URL
SpeedtestMiniConnectFailure: Failed to connect to Mini server
"""Execute download and upload speed tests with progress callbacks and threading control.
def download(self, callback=None, threads=None):
"""
Perform download speed test.
Parameters:
- callback (callable, optional): Progress callback function(bytes_received, total_bytes)
- threads (int, optional): Number of threads to use (default: determined by server)
Returns:
float: Download speed in bits per second
Raises:
SpeedtestMissingBestServer: Best server not set (call get_best_server first)
"""
def upload(self, callback=None, pre_allocate=True, threads=None):
"""
Perform upload speed test.
Parameters:
- callback (callable, optional): Progress callback function(bytes_sent, total_bytes)
- pre_allocate (bool): Pre-allocate upload data in memory (default: True)
- threads (int, optional): Number of threads to use (default: determined by server)
Returns:
float: Upload speed in bits per second
Raises:
SpeedtestMissingBestServer: Best server not set (call get_best_server first)
SpeedtestUploadTimeout: Upload test timed out
"""Usage example:
def progress_callback(bytes_done, total_bytes):
percent = (bytes_done / total_bytes) * 100
print(f"Progress: {percent:.1f}%")
s = speedtest.Speedtest()
s.get_best_server()
# Run tests with progress callback
download_speed = s.download(callback=progress_callback)
upload_speed = s.upload(callback=progress_callback)
print(f"Download: {download_speed / 1000000:.2f} Mbps")
print(f"Upload: {upload_speed / 1000000:.2f} Mbps")def build_user_agent():
"""Build HTTP User-Agent string for requests."""
def distance(origin, destination):
"""
Calculate distance between coordinate points.
Parameters:
- origin (dict): Origin coordinates with 'lat' and 'lon' keys
- destination (dict): Destination coordinates with 'lat' and 'lon' keys
Returns:
float: Distance in kilometers
"""Install with Tessl CLI
npx tessl i tessl/pypi-speedtest-cli