Said Py
Said PyDec. 26, 2021, 12:22 p.m.

Python: How to Test Internet Speed

Probably, you have used the speedtest website before, but did you know that speedtest has a python library.
In this tutorial, We will learn to use the speedtest library to test your internet Speed. We'll also learn how to use speedtest command lines.

Let's get started.


Speedtest instalation

To install speedtest via pip, follow this command:

pip install speedtest-cli

Test internet speed (script)

After installing the speedtest package. Now, let's see how to use it with the code.

In the following code, I'll test my internet download speed.

import speedtest

# Speed test
st = speedtest.Speedtest()

# Download Speed
ds = st.download()

print(ds)

let me explain.
First, we import the speedtest package. Then, called Speedtest() class. Next, test my download speed using the download() method. Finally, print the result.

Output:

3422459.073187817

As you can see, the internet speed is in Bytes . To make it readable, we'll use the following function.

def humansize(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])

#Readable
print(humansize(ds))


Output:

3.56 MB

Now, let's test our upload speed using the upload() method.

import speedtest

# Speed test
st = speedtest.Speedtest()

# Upload speed
us = st.upload()

print(us)

#Readable
print(humansize(us))

Output:

386382.6586620888
301.51 KB

Speedtest command lines

Speedtest also provides the command lines for testing our internet speed.

Usage:

Help command:

speedtest-cli -h

Output:

usage: speedtest-cli [-h] [--no-download] [--no-upload] [--single] [--bytes]
                     [--share] [--simple] [--csv]
                     [--csv-delimiter CSV_DELIMITER] [--csv-header] [--json]
                     [--list] [--server SERVER] [--exclude EXCLUDE]
                     [--mini MINI] [--source SOURCE] [--timeout TIMEOUT]
                     [--secure] [--no-pre-allocate] [--version]

Command line interface for testing internet bandwidth using speedtest.net.

Test Internet Speed:

speedtest-cli

Output:

Retrieving speedtest.net configuration...
Testing from xxx Telecom (196.89.30.99)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by xxx Telecom (xxx) [394.57 km]: 29.1 ms
Testing download speed................................................................................
Download: 8.30 Mbit/s
Testing upload speed......................................................................................................
Upload: 10.33 Mbit/s

This command above tests ping , download speed, and upload speed.

Test Internet Speed: with the share link:

speedtest-cli --share

Output:

Retrieving speedtest.net configuration...
Testing from xxx Telecom (196.89.30.99)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by xxx Telecom (xxx) [394.57 km]: 28.131 ms
Testing download speed................................................................................
Download: 3.74 Mbit/s
Testing upload speed......................................................................................................
Upload: 0.39 Mbit/s
Share results: http://www.speedtest.net/result/12339819892.png

As you can see, we've got a URL of the results. Let's open it in the browser.

Result:

Speed Test Result

We hope this is easy to understand. See you later.


References:

https://pypi.org/project/speedtest-cli/
speedtest example (PyOnlyCode)
Speedtest-cli Example (PyOnlyCode)

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 2:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 2:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 2:35 p.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
BlinCT
BlinCTMay 5, 2024, 3:46 p.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
BlinCT
BlinCTMay 5, 2024, 3:44 p.m.
добавить qlineseries в функции Давно я не работал с виджетами и с формами, на мой взгляд уже пережитов, и в управлении не очень удобное это все. Н оя у вас не увидел в коде где вы QCharts растягиваете на область парента.…
PS
Peter SonMay 4, 2024, 3:57 a.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 3, 2024, 12:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 2:22 p.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks