Answers:
您可以使用psutil.net_io_counters()来计算一段时间内的带宽。您将在0秒拍摄快照,在300秒拍摄快照。
def get_bandwidth():
# Get net in/out
net1_out = psutil.net_io_counters().bytes_sent
net1_in = psutil.net_io_counters().bytes_recv
time.sleep(300) # Not best way to handle getting a value 300 seconds later
# Get new net in/out
net2_out = psutil.net_io_counters().bytes_sent
net2_in = psutil.net_io_counters().bytes_recv
# Compare and get current speed
if net1_in > net2_in:
current_in = 0
else:
current_in = net2_in - net1_in
if net1_out > net2_out:
current_out = 0
else:
current_out = net2_out - net1_out
network = {"traffic_in": current_in, "traffic_out": current_out}
# Return data in bytes
return network