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
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

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

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
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
AC
Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 7:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 3:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 5:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks