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
AD

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

  • Result:50points,
  • Rating points-4
m

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

  • Result:80points,
  • Rating points4
m

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

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 12:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 6:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 5:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 1:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks