-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetwork_usage.py
31 lines (27 loc) · 1.04 KB
/
network_usage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import psutil
import time
UPDATE_DELAY = 1 # in seconds
def get_size(bytes):
"""
Returns size of bytes in a nice format
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P']:
if bytes < 1024:
return f"{bytes:.2f}{unit}B"
bytes /= 1024
io = psutil.net_io_counters()
bytes_sent, bytes_recv = io.bytes_sent, io.bytes_recv
while True:
# sleep for `UPDATE_DELAY` seconds
time.sleep(UPDATE_DELAY)
# get the stats again
io_2 = psutil.net_io_counters()
# new - old stats gets us the speed
us, ds = io_2.bytes_sent - bytes_sent, io_2.bytes_recv - bytes_recv
# print the total download/upload along with current speeds
print(f"Upload usage: {get_size(io_2.bytes_sent)} "
f", Download usage: {get_size(io_2.bytes_recv)} "
f", Upload Speed: {get_size(us / UPDATE_DELAY)}/s "
f", Download Speed: {get_size(ds / UPDATE_DELAY)}/s \n", end="\r")
# update the bytes_sent and bytes_recv for next iteration
bytes_sent, bytes_recv = io_2.bytes_sent, io_2.bytes_recv