【问题标题】:python script to calc internet upload and download and jitterpython脚本来计算互联网上传和下载和抖动
【发布时间】:2022-01-11 14:51:29
【问题描述】:

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

如何在 Python 中发生这种情况而不会对 Internet 产生重大影响,从而不会导致 Internet 速度变慢

`
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

`

【问题讨论】:

    标签: python sockets


    【解决方案1】:

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

    这是来自官方页面的sn-p。

    >>> 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 模块的更多详细信息

    【讨论】:

    • 感谢您的回复speedtestpyspeedtest他们不允许我添加专用 IP 地址,而且速度很慢,我会环顾套接字
    • 另外你可以在 python 中探索 requests 模块。更新了一些示例和参考答案。
    • 我会尝试调整,直到我得到我想要的正确。但这很有用。谢谢
    • 这非常有用。我会迟到的。 In give you the best answer for more 有用的答案 tahnk you
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 2011-04-28
    • 1970-01-01
    • 2014-03-23
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多