Python 100 project #11: Speedtest.net every 10 minutes

Previously, I made a code just to get the speedtest. But the speed and the latency differs time to time. In order to get the actual trend of the internet speed, it is important to get the periodical result.

This time, I wrote a code to execute this speedtest against 5 servers in Australia, Japan, UK, US, SouthAfrica every 10 minutes.

 

Output Example:

13679_dwn,13679_up,13679_ping,16353_dwn,16353_up,16353_ping,6405_dwn,6405_up,6405_ping,4153_dwn,4153_up,4153_ping,9534_dwn,9534_up,9534_ping,
24829864.10652871,1707157.1503819267,249.779,26321525.54602719,1434679.5474092711,2510.318,15082092.34654852,1859949.1741871992,441.537,7097773.494183322,1313939.3246479654,1189.239,7283515.202758691,1785215.3085554347,357.394,
25011001.420472134,1459346.587797224,2088.319,26271892.134433586,1297744.0367208389,985.909,15809963.828078559,1404914.5219215665,421.25,7668181.077999457,1403380.8684583649,1329.662,7316070.486894957,1398703.2077226944,426.233,

This is just raw data file, and this result only doesn’t mean any important thing. In the later project, I use pandas and matplotlib to visualize the result.

 

Here is the code:

import time

import speedtest


def get_result(id=None):
    servers = []
    if id:
        servers.append(id)

    s = speedtest.Speedtest()
    s.get_servers(servers)
    s.get_best_server()
    s.download()
    s.upload()

    results_dict = s.results.dict()

    return results_dict['download'], results_dict['upload'], results_dict['ping']


if __name__ == '__main__':

    s = speedtest.Speedtest()
    server_list = s.get_servers()

    countries = ["United States", "United Kingdom", "Australia", "Japan", "South Africa"]

    test_servers = []
    for id, val in server_list.items():
        if val[0]['country'] in countries:
            test_servers.append(val[0]['id'])
            countries.remove(val[0]['country'])
        if len(countries) == 0:
            break

    # initialize a csv file with headers
    with open("speedtest_result.csv", "a") as f:
        for server in test_servers:
            for score in ['_dwn', '_up', '_ping']:
                f.write(server + score + ",")
        f.write("\n")

    print("CSV file is initialized.")

    interval = 600

    while True:

        start_time = time.time()

        for server in test_servers:
            print("id: {} is being measured...".format(server))
            download, upload, latency = get_result(id=server)

            with open("speedtest_result.csv", "a") as f:
                f.write("{},{},{},".format(download, upload, latency))

        with open("speedtest_result.csv", "a") as f:
            f.write("\n")

        end_time = time.time()
        elapsed_time = end_time - start_time

        time.sleep(interval - elapsed_time)