获取上传/下载 kbps 速度



我正在使用名为 psutil 的库来获取系统/网络统计信息,但我只能在脚本上获取上传/下载的总字节数。

使用Python本地获得网络速度的方法是什么?

如果您需要立即知道传输速率,则应创建一个连续执行计算的线程。我不是这方面的专家,但我尝试编写一个简单的程序来满足您的需求:

import threading
import time
from collections import deque
import psutil

def calc_ul_dl(rate, dt=3, interface="WiFi"):
    t0 = time.time()
    counter = psutil.net_io_counters(pernic=True)[interface]
    tot = (counter.bytes_sent, counter.bytes_recv)
    while True:
        last_tot = tot
        time.sleep(dt)
        counter = psutil.net_io_counters(pernic=True)[interface]
        t1 = time.time()
        tot = (counter.bytes_sent, counter.bytes_recv)
        ul, dl = [
            (now - last) / (t1 - t0) / 1000.0
            for now, last in zip(tot, last_tot)
        ]
        rate.append((ul, dl))
        t0 = time.time()

def print_rate(rate):
    try:
        print("UL: {0:.0f} kB/s / DL: {1:.0f} kB/s".format(*rate[-1]))
    except IndexError:
        "UL: - kB/s/ DL: - kB/s"

# Create the ul/dl thread and a deque of length 1 to hold the ul/dl- values
transfer_rate = deque(maxlen=1)
t = threading.Thread(target=calc_ul_dl, args=(transfer_rate,))
# The program will exit if there are only daemonic threads left.
t.daemon = True
t.start()
# The rest of your program, emulated by me using a while True loop
while True:
    print_rate(transfer_rate)
    time.sleep(5)

在这里,您应该将dt参数设置为对您合理的任何接缝。我尝试使用 3 秒,这是我在运行在线速度测试时的输出:

UL: 2 kB/s / DL: 8 kB/s
UL: 3 kB/s / DL: 45 kB/s
UL: 24 kB/s / DL: 1306 kB/s
UL: 79 kB/s / DL: 4 kB/s
UL: 121 kB/s / DL: 3 kB/s
UL: 116 kB/s / DL: 4 kB/s
UL: 0 kB/s / DL: 0 kB/s

这些值似乎是合理的,因为我的速度测试结果是DL: 1258 kB/sUL: 111 kB/s

Steinar Lima提供的答案是正确的。但它也可以在没有线程的情况下完成:

import time
import psutil
import os
count = 0
qry = ""
ul = 0.00
dl = 0.00
t0 = time.time()
upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
up_down = (upload, download)

while True:
    last_up_down = up_down
    upload = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][0]
    download = psutil.net_io_counters(pernic=True)["Wireless Network Connection"][1]
    t1 = time.time()
    up_down = (upload, download)
    try:
        ul, dl = [
            (now - last) / (t1 - t0) / 1024.0
            for now, last in zip(up_down, last_up_down)
        ]
        t0 = time.time()
    except:
        pass
    if dl > 0.1 or ul >= 0.1:
        time.sleep(0.75)
        os.system("cls")
        print("UL: {:0.2f} kB/s n".format(ul) + "DL: {:0.2f} kB/s".format(dl))
v = input()

简单易用的;)

如果您想在

树莓派上对其进行测试,我为此代码添加了一个 LCD mod,但您需要将psutillcddriver添加到您的项目代码中!!!

import time
import psutil
import os
import lcddriver
count=0
qry=''
ul=0.00
dl=0.00
t0 = time.time()
upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
download=psutil.net_io_counters(pernic=True)['wlan0'][1]
up_down=(upload,download)
display = lcddriver.lcd()
while True:
    last_up_down = up_down
    upload=psutil.net_io_counters(pernic=True)['wlan0'][0]
    download=psutil.net_io_counters(pernic=True)['wlan0'][1]
    t1 = time.time()
    up_down = (upload,download)
    try:
        ul, dl = [(now - last) / (t1 - t0) / 1024.0
                 for now,last in zip(up_down, last_up_down)]             
        t0 = time.time()
        #display.lcd_display_string(str(datetime.datetime.now().time()), 1)
    except:
        pass
        
    if dl>0.1 or ul>=0.1:
       time.sleep(0.75) 
       os.system('cls')
       print('UL: {:0.2f} kB/s n'.format(ul)+'DL:{:0.2f} kB/s'.format(dl))
       display.lcd_display_string(str('DL:{:0.2f} KB/s      '.format(dl)), 1)
       display.lcd_display_string(str('UL:{:0.2f} KB/s      '.format(ul)), 2)
       
    # if KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
    #     print("Cleaning up!")
    #     display.lcd_clear()   
    
v=input()

(有效)网络速度只是在给定时间间隔内传输的字节数除以间隔长度。 显然,有不同的方法来汇总/平均时间,它们为您提供不同的"措施"......但这一切基本上都归结为分裂。

另一个更简单的解决方案(没有线程和队列,尽管仍然基于@Steinar Lima)和更新的python:

import time
import psutil
def on_calculate_speed(self, interface):
    dt = 1 # I find that dt = 1 is good enough
    t0 = time.time()
    try:
        counter = psutil.net_io_counters(pernic=True)[interface]
    except KeyError:
        return []
    tot = (counter.bytes_sent, counter.bytes_recv)
    while True:
        last_tot = tot
        time.sleep(dt)
        try:
            counter = psutil.net_io_counters(pernic=True)[interface]
        except KeyError:
            break
        t1 = time.time()
        tot = (counter.bytes_sent, counter.bytes_recv)
        ul, dl = [
            (now - last) / (t1 - t0) / 1000.0
            for now, last
            in zip(tot, last_tot)
        ]
        return [int(ul), int(dl)]
        t0 = time.time()
while SomeCondition:
   # "wlp2s0" is usually the default wifi interface for linux, but you
   # could use any other interface that you want/have.
   interface = "wlp2s0"
   result_speed = on_calculate_speed(interface)
   if len(result_speed) < 1:
      print("Upload: - kB/s/ Download: - kB/s")
   else:
      ul, dl = result_speed[0], result_speed[1]
      print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))

或者你也可以使用 pyroute2 获取默认接口:

while SomeCondition:
   ip = IPDB()
   interface = ip.interfaces[ip.routes['default']['oif']]["ifname"]
   result_speed = on_calculate_speed(interface)
   if len(result_speed) < 1:
      print("Upload: - kB/s/ Download: - kB/s")
   else:
      ul, dl = result_speed[0], result_speed[1]
      print("Upload: {} kB/s / Download: {} kB/s".format(ul, dl))
   ip.release()
<</div> div class="one_answers">

我找到了这个胎面,对 Python 没有任何想法,我 jst 复制和粘贴代码,现在需要一点帮助,这个脚本,我有 jst 显示发送/接收的总字节数,可以修改以显示实际速度吗?

def network(iface):
stat = psutil.net_io_counters(pernic=True)[iface]
return "%s: Tx%s, Rx%s" % 
       (iface, bytes2human(stat.bytes_sent), bytes2human(stat.bytes_recv))

def stats(device):
# use custom font
font_path = str(Path(__file__).resolve().parent.joinpath('fonts', 'C&C Red Alert [INET].ttf'))
font_path2 = str(Path(__file__).resolve().parent.joinpath('fonts', 'Stockholm.ttf'))
font2 = ImageFont.truetype(font_path, 12)
font3 = ImageFont.truetype(font_path2, 11)
with canvas(device) as draw:
    draw.text((0, 0), cpu_usage(), font=font2, fill="white")
    if device.height >= 32:
        draw.text((0, 14), mem_usage(), font=font2, fill="white")
    if device.height >= 64:
        draw.text((0, 26), "IP: " + getIP("eth0"), font=font2, fill=255)
        try:
            draw.text((0, 38), network('eth0'), font=font2, fill="white")
        except KeyError:
            # no wifi enabled/available
            pass

代码

# pip install speedtest-cli
import speedtest
speed_test = speedtest.Speedtest()
def bytes_to_mb(bytes):
  KB = 1024 # One Kilobyte is 1024 bytes
  MB = KB * 1024 # One MB is 1024 KB
  return int(bytes/MB)
download_speed = bytes_to_mb(speed_test.download())
print("Your Download speed is", download_speed, "MB")
upload_speed = bytes_to_mb(speed_test.upload())
print("Your Upload speed is", upload_speed, "MB")

界面中的第一个答案应该是更改为所需的网络适配器。要在 ubuntu 中查看名称,您可以使用 ifconfig,然后将interface='wifi'更改为设备名称。

对 python3 中的格式进行了一些更改

def print_rate(rate):
    try:
        print(('UL: {0:.0f} kB/s / DL: {1:.0f} kB/s').format(*rate[-1]))
    except IndexError:
        'UL: - kB/s/ DL: - kB/s'

最新更新