python 计算互联网上传下载和抖动的脚本

python script to calc internet upload and download and jitter

我有一个 Python 脚本,每 30 秒通过 ping 运行一次以确定互联网速度,以查看用户是否可以通过互联网接听电话,ping 通常不足以知道这一点,所以我想了解更多下载速度和网络上传速度等信息。

如何在Python发生这种情况而不会对互联网造成重大影响,从而不会导致互联网变慢

`
def check_ping(host):
    """
    Returns formated min / avg / max / mdev if there is a vaild host
    Return None if host is not vaild
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower() == 'windows' else '-c'

    # Building the command. Ex: "ping -c 1 $host"
    command = ['ping', param, '3', host]

    # ask system to make ping and return output
    ping = subprocess.Popen(command, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    out, error = ping.communicate()
    matcher = re.compile(
        "(\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
    # rtt min/avg/max/mdev =
    ping_list = r"Minimum = (\d+)ms, Maximum = (\d+)ms, Average = (\d+)ms"

    try:
        if(not error):
            if(platform.system().lower() == 'windows'):
                response = re.findall(ping_list, out.decode())[0]
                return response
            else:
                response = matcher.search(out.decode()).group().split('/')
                return response
    except Exception as e:
        logging.error(e)
        return None

`

pyspeedtest 为您提供您想要的功能。

这是官方页面的一个片段。

>>> import pyspeedtest
>>> st = pyspeedtest.SpeedTest()
>>> st.ping()
9.306252002716064
>>> st.download()
42762976.92544772
>>> st.upload()
19425388.307319913

还有speedtest-cli,但这不是我亲自尝试过的。

如果您正在寻找更多的东西,那么您必须根据 sockets

提出自己的实施方案

编辑: 这是一个基于使用 requests

的实现
#!/usr/bin/env python3
import requests, os, sys, time

def test_connection(type):
  nullFile = os.devnull
  with open(nullFile, "wb") as f:
    start = time.clock()
    if type == 'download':
       r = requests.get('https://httpbin.org/get', stream=True)
    elif type == 'upload':
       r = requests.post('https://httpbin.org/post', data={'key': 'value'})
    else:
       print("unknown operation")
       raise

    total_length = r.headers.get('content-length')
    dl = 0

    for chunk in r.iter_content(1024):
        dl += len(chunk)
        f.write(chunk)
        done = int(30 * dl / int(total_length))
        sys.stdout.write("\r%s: [%s%s] %s Mbps" % (type, '=' * done, ' ' * (30-done), dl//(time.clock() - start) / 100000))
        print('')

# Example usage
test_connection("download")
test_connection("upload")

输出:

download: [==============================] 0.13171 Mbps
upload: [==============================] 0.20217 Mbps

您或许可以修改此函数以接受 url/IP 作为参数。 此外,您可以在 official page

上找到有关 requests 模块的更多详细信息