2 min read

Internet Speed Tester

This utility measures your internet connection's performance (Download, Upload, Ping) using the speedtest-cli library. It connects to the nearest Speedtest.net server to perform the test.

Modules Used:

  • speedtest-cli: A command line interface for testing internet bandwidth using speedtest.net.
  • argparse: To handle command-line arguments.

Installation

You need to install the speedtest-cli package (which provides the speedtest module).

pip install speedtest-cli

The Code

Save this as speed_test.py.

import speedtest
import argparse

def test_speed(share=False):
    print("Initializing Speedtest...")
    try:
        # Initialize the Speedtest object
        st = speedtest.Speedtest()
    except speedtest.ConfigRetrievalError:
        print("Error: Could not retrieve speedtest configuration. Check your internet connection.")
        return

    print("Finding best server...")
    st.get_best_server()

    print("Testing Download Speed...")
    # download() returns bits/s, convert to Mbps
    download_speed = st.download() / 1_000_000 

    print("Testing Upload Speed...")
    # upload() returns bits/s, convert to Mbps
    upload_speed = st.upload() / 1_000_000 

    ping = st.results.ping

    print("\n" + "="*40)
    print(f"Download: {download_speed:.2f} Mbps")
    print(f"Upload:   {upload_speed:.2f} Mbps")
    print(f"Ping:     {ping:.2f} ms")
    print("="*40)

    if share:
        print("Generating result image...")
        st.results.share()
        results = st.results.dict()
        print(f"Share URL: {results['share']}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Internet Speed Tester")
    parser.add_argument("--share", action="store_true", help="Generate a shareable image URL")

    args = parser.parse_args()

    test_speed(args.share)

Usage

# Basic test
python speed_test.py

# Test and generate a shareable link (image)
python speed_test.py --share

programming/python/python