Created
February 10, 2021 11:25
-
-
Save mohammedi-haroune/89581f5b2d449bb088f00eb31bca02ad to your computer and use it in GitHub Desktop.
Measure internet speed using speedtest.net Python API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/python3 | |
import csv | |
import os | |
import typing | |
from pathlib import Path | |
import speedtest | |
PathLike = typing.Union[str, bytes, os.PathLike] | |
HOME = Path.home() | |
def measure( | |
download: bool = True, | |
upload: bool = False | |
) -> speedtest.Speedtest: | |
servers = [] | |
# If you want to test against a specific server | |
# servers = [1234] | |
threads = None | |
# If you want to use a single threaded test | |
# threads = 1 | |
s = speedtest.Speedtest() | |
s.get_servers(servers) | |
s.get_best_server() | |
if download: | |
s.download(threads=threads) | |
if upload: | |
s.upload(threads=threads) | |
return s | |
def parse_speed(speed: speedtest.Speedtest) -> dict: | |
results_dict = speed.results.dict() | |
return results_dict | |
def is_empty(path: PathLike) -> bool: | |
if not os.path.exists(path): | |
return True | |
with open(path, 'r') as f: | |
if f.read() == '': | |
return True | |
return False | |
FIELDS = ['timestamp', 'download', 'ping'] | |
def save_speed_csv(speed_dict: dict, path: PathLike, fields: list = None) -> dict: | |
if fields is None: | |
fields = FIELDS | |
row = {field: speed_dict[field] for field in fields} | |
# Write csv header only if the file is empty | |
writeheader = is_empty(path) | |
with open(path, 'a') as f: | |
writer = csv.DictWriter(f, fieldnames=fields) | |
if writeheader: | |
writer.writeheader() | |
writer.writerow(row) | |
return row | |
def print_speed(speed_dict: dict): | |
mbps = round(speed_dict['download'] / 10e5, 2) | |
format = f'Download: {mbps} Mbps' | |
print(format.format(mbps=mbps)) | |
def save_speed_graph(csv_path, graph_path): | |
pass | |
def main( | |
download: bool = True, | |
upload: bool = False, | |
csv_path: PathLike = HOME / 'speedtest.csv', | |
graph_path: PathLike = HOME / 'speedtest.png' | |
): | |
speed = measure(download, upload) | |
speed_dict = parse_speed(speed) | |
print_speed(speed_dict) | |
save_speed_csv(speed_dict, csv_path) | |
save_speed_graph(csv_path, graph_path) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment