Python проверка скорости интернета

Speedtest your connection in Python

Today we’ll be building our speed testing service in Python. We have Speedtest websites like this to test our ping, upload, and download speed for those who don’t know.

For today’s article, I was looking to automate this since I check it regularly.

I choose Python as the language, seeing I’m trying that out a bit.

Before we can use this package, we have to install it to become available for us to use.

Use the following command to install it:

Now open your python file and start by importing the speed test module.

Then we create a new speed test. In my case, I’m assigning it to the st variable.

Note: be aware running the speed test takes a while, so be patient 🙈

Now let’s try our download speed and print it out:

When we run this, we get a long number like this:

I’ll be showing you how to get this data and format it nicely.

Starting with the ping, for this to work, we need to define a server to ping. In our case let’s choose the best one.

After this, we can get the ping to this server by using the following:

print(f"Your ping is: st.results.ping> ms")

Let’s go on to download. We have already seen we can get this by calling the download() function, but it’s unformatted. Below I’ll show you how to format it to Mbit/s .

print(f"Your download speed: (st.download() / 1000 / 1000, 1)> Mbit/s")

We can make the same approach for the upload but use the upload() function.

print(f"Your upload speed: (st.upload() / 1000 / 1000, 1)> Mbit/s")

The full script will look like this:

import speedtest st = speedtest.Speedtest() st.get_best_server() print(f"Your ping is: st.results.ping> ms") print(f"Your download speed: (st.download() / 1000 / 1000, 1)> Mbit/s") print(f"Your upload speed: (st.upload() / 1000 / 1000, 1)> Mbit/s")

And when we run this, it outputs:

Your ping is: 30.97 ms Your download speed: 64.4 Mbit/s Your upload speed: 29.2 Mbit/s

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Источник

Библиотека проверки скорости интернета — Speedtest

Python — широко используемый высокоуровневый язык программирования общего назначения. Он используется для веб-разработки, машинного обучения и даже приложений с графическим интерфейсом. Его же можно использовать для проверки скорости интернета. Для этого в Python есть несколько библиотек. Одна из таких — speedtest-cli.

Speedtest-cli — это интерфейс командной строки для проверки скорости с помощью сервиса speedtest.net.

Установка

Модуль не является предустановленным в Python. Для его установки нужно ввести следующую команду в терминале:

Читайте также:  Билайн домашний интернет колл центр костанай

После установки библиотеки можно проверить корректность и версию пакета. Для этого используется такая команда:

& speedtest-cli --version speedtest-cli 2.1.2 Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)]

Возможности speedtest-cli

Что делает Speedtest-CLI?
Speedtest-cli — это модуль, используемый в интерфейсе командной строки для проверки пропускной способности с помощью speedtest.net. Для получения скорости в мегабитах введите команду: speedtest-cli .

получения скорости в мегабитах

Это команда даст результат скорости в мегабитах. Для получения результата в байтах нужно добавить один аргумент к команде.

$ speedtest-cli --bytes Retrieving speedtest.net configuration. Testing from ******** (******). Retrieving speedtest.net server list. Selecting best server based on ping. Hosted by ******** (***) [1.85 km]: 3.433 ms Testing download speed. Download: 22.98 Mbyte/s Testing upload speed. Upload: 18.57 Mbyte/s

Также с помощью модуля можно получить графическую версию результата тестирования. Для этого есть такой параметр:

$ speedtest-cli --share Retrieving speedtest.net configuration. Testing from ***** (****). Retrieving speedtest.net server list. Selecting best server based on ping. Hosted by ***** (***) [1.85 km]: 3.155 ms Testing download speed. Download: 164.22 Mbit/s Testing upload speed. Upload: 167.82 Mbit/s Share results: http://www.speedtest.net/result/11111111111.png

Команда вернет ссылку, по которой можно перейти в браузере:

графическая версия результата тестирования

Для вывода более простой версии результатов теста, в которой будут только сведения о пинге, скорости скачивания и загрузки используйте параметр —simple .

$ speedtest-cli --simple Ping: 3.259 ms Download: 182.49 Mbit/s Upload: 172.16 Mbit/s

Использование speedtest в Python

Рассмотрим пример программы Python для тестирования скорости интернета:

 
import speedtest st = speedtest.Speedtest() option = int(input(''' Выбери тип проверки: 1 - Скорость скачивания 2 - Скорость загрузки 3 - Пинг Твой выбор: ''')) if option == 1: print(st.download()) elif option == 2: print(st.upload()) elif option == 3: servernames =[] st.get_servers(servernames) print(st.results.ping) else: print("Пожалуйста, введите цифру от 1 до 3!")

Результат выполнения этой простой программы будет такой:

Выбери тип проверки: 1 - Скорость скачивания 2 - Скорость загрузки 3 - Пинг Твой выбор: 2 136433948.59785312

Дополнение

Что бы погрузится в библиотеку speedtest-cli используйте команду --help , что бы получить список всех доступных параметров:

speedtest-cli --help # или speedtest-cli -h

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Command line interface for testing internet bandwidth using speedtest.net

License

sivel/speedtest-cli

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.rst

Command line interface for testing internet bandwidth using speedtest.net

speedtest-cli works with Python 2.4-3.7

easy_install speedtest-cli
pip install git+https://github.com/sivel/speedtest-cli.git
git clone https://github.com/sivel/speedtest-cli.git cd speedtest-cli python setup.py install

Just download (Like the way it used to be)

wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py chmod +x speedtest-cli
curl -Lo speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py chmod +x speedtest-cli
$ speedtest-cli -h 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. -------------------------------------------------------------------------- https://github.com/sivel/speedtest-cli optional arguments: -h, --help show this help message and exit --no-download Do not perform download test --no-upload Do not perform upload test --single Only use a single connection instead of multiple. This simulates a typical file transfer. --bytes Display values in bytes instead of bits. Does not affect the image generated by --share, nor output from --json or --csv --share Generate and provide a URL to the speedtest.net share results image, not displayed with --csv --simple Suppress verbose output, only show basic information --csv Suppress verbose output, only show basic information in CSV format. Speeds listed in bit/s and not affected by --bytes --csv-delimiter CSV_DELIMITER Single character delimiter to use in CSV output. Default "," --csv-header Print CSV headers --json Suppress verbose output, only show basic information in JSON format. Speeds listed in bit/s and not affected by --bytes --list Display a list of speedtest.net servers sorted by distance --server SERVER Specify a server ID to test against. Can be supplied multiple times --exclude EXCLUDE Exclude a server from selection. Can be supplied multiple times --mini MINI URL of the Speedtest Mini server --source SOURCE Source IP address to bind to --timeout TIMEOUT HTTP timeout in seconds. Default 10 --secure Use HTTPS instead of HTTP when communicating with speedtest.net operated servers --no-pre-allocate Do not pre allocate upload data. Pre allocation is enabled by default to improve upload performance. To support systems with insufficient memory, use this option to avoid a MemoryError --version Show the version number and exit

It is not a goal of this application to be a reliable latency reporting tool.

Latency reported by this tool should not be relied on as a value indicative of ICMP style latency. It is a relative value used for determining the lowest latency server for performing the actual speed test against.

There is the potential for this tool to report results inconsistent with Speedtest.net. There are several concepts to be aware of that factor into the potential inconsistency:

  1. Speedtest.net has migrated to using pure socket tests instead of HTTP based tests
  2. This application is written in Python
  3. Different versions of Python will execute certain parts of the code faster than others
  4. CPU and Memory capacity and speed will play a large part in inconsistency between Speedtest.net and even other machines on the same network

Issues relating to inconsistencies will be closed as wontfix and without additional reason or context.

About

Command line interface for testing internet bandwidth using speedtest.net

Источник

Проверка скорости интернета библиотекой Requests в мультипроцессинге

Сегодня речь пойдет о том, как из идеи по замеру скорости, был создан скрипт для загрузки файла изображения и отправки его же обратно на сервер, с расчетом времени выполнения каждой из функций и вычисления скорости.

Начну со списка используемых библиотек:

  • import os
  • from multiprocessing import Pool
  • import time
  • import pandas as pd
  • import requests
def download(id, path): start = time.time() file_name = str(id) + str(path.split('/')[-1]) try: r = requests.get(path, stream=True, timeout=5) except: return 0 size = int(r.headers.get('Content-Length', 0)) with open(file_name, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) end = time.time() duration = end - start sp = (((size * 8) / 1024) / 1024) / duration return sp

Теперь подробнее о том, что происходит.

В функции есть время старта и время окончания(в секундах), из которых в дальнейшем мы получаем время жизни. В имя файла записываем id сервера и название изображения(сделано для того, чтобы не возникало конфликтов при загрузке из множества источников). Далее делаем GET запрос, получаем размер файла(в байтах) и сохраняем его на диск. Переводим байты в биты, еще немного магии с формулами и на выходе имеем скорость в MBit/s.

Следующая функция — отдача файла на сервер:

def upload(id, path): start = time.time() file_name = str(id) + 'random7000x7000.jpg' with open(file_name, 'rb') as f: files = try: requests.post(path, files=files) except: return 0 size = os.path.getsize(file_name) end = time.time() duration = end - start sp = (((size * 8) / 1024) / 1024) / duration return sp

Здесь принцип тот же, только мы берем файл из локальной папки и POST запросом отправляем.

Наша следующая задача получить данные из двух предыдущих функций. Пишем еще одну функцию:

def test_f(conn, server): speed_download = download(server['server_id'], server['download']) speed_upload = upload(server['server_id'], server['upload']) return server['server_id'], speed_download, speed_upload 

Осталось дело за малым, прикрутить мультипроцессинг с пулом и параллельной функцией map:

def main(): pool = Pool() data = pool.map(test_f, server_list) df = pd.DataFrame(data, columns=['Server', 'Download', 'Upload']) print(df) pool.close() pool.join()
if __name__ == '__main__': main() 

Скрипт готов к использованию, для удобства вывода я использовал библиотеку pandas. Так же вывод можно поместить в базу и собирать статистику для анализа.

UPD: Поправил исключения, внес правки в работу мультипроцессинга(заменил цикл на параллельную функцию), добавил таймаут для GET запроса

Источник

Оцените статью
Adblock
detector