我正在使用名为psutil的库来获取系统/网络统计信息,但我只能在我的脚本上获取上传/下载的总字节数。
使用Python本地获取网络速度的方法是什么?
答案 0 :(得分:7)
如果您需要立即知道传输速率,则应创建一个连续执行计算的线程。我不是这方面的专家,但我尝试编写一个能够满足您需求的简单程序:
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)
在这里,您应该将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
这些值似乎合理,因为我的速度测试结果是DL: 1258 kB/s
和UL: 111 kB/s
。
答案 1 :(得分:2)
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()
简单易行;)
答案 2 :(得分:2)
如果您想在树莓派上对其进行测试,我为此代码添加了一个LCD mod,但是您需要在项目代码中添加psutil
和lcddriver
!!
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()
答案 3 :(得分:1)
(有效)网络速度只是在给定时间间隔内传输的字节数除以间隔的长度。显然,有不同的方法来聚合/平均时间,它们会给你不同的“量度”......但这一切基本上归结为分裂。
答案 4 :(得分:0)
另一个更简单的解决方案(尽管仍然基于@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()
答案 5 :(得分:-1)
界面中的第一个答案应该更改为所需的网络适配器。要在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'