如果您需要立即知道传输速率,则应创建一个连续执行计算的线程.我不是这方面的专家,但我尝试编写一个简单的程序来完成你需要的东西:
import threading
from collections import deque
import time
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)
Run Code Online (Sandbox Code Playgroud)
在这里你应该将dt参数设置为适合你的任何接缝.我试着用3秒,这是捉迷藏的同时在线我的输出SPEEDTEST:
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
Run Code Online (Sandbox Code Playgroud)
这些值似乎是合理的,因为我的速度测试结果是DL: 1258 kB/s和UL: 111 kB/s.