I want to monitor on my computer the upload and download speeds. A program called conky already does it with the following in conky conf:
Connection quality: $alignr ${wireless_link_qual_perc wlan0}%
${downspeedgraph wlan0}
DLS:${downspeed wlan0} kb/s $alignr total: ${totaldown wlan0}
and it shows me the speeds in almost real time while I browse. I want to be able to access the same information using python.
I would look into the psutil module for Python.
Here is a short snippet which prints out the number of bytes sent since you booted your machine:
import psutil
iostat = psutil.net_io_counters(pernic=False)
print iostat[0] #upload only
You could easily expand this to grab the value at a constant interval and diff the two values to determine the number of bytes sent and/or received over that period of time.
You can calculate the speed yourself based on the rx_bytes and tx_bytes for the device and polling those values over an interval
Here is a very simplistic solution I hacked together using Python 3
#!/usr/bin/python3
import time
def get_bytes(t, iface='wlan0'):
    with open('/sys/class/net/' + iface + '/statistics/' + t + '_bytes', 'r') as f:
        data = f.read();
    return int(data)
if __name__ == '__main__':
    (tx_prev, rx_prev) = (0, 0)
    while(True):
        tx = get_bytes('tx')
        rx = get_bytes('rx')
        if tx_prev > 0:
            tx_speed = tx - tx_prev
            print('TX: ', tx_speed, 'bps')
        if rx_prev > 0:
            rx_speed = rx - rx_prev
            print('RX: ', rx_speed, 'bps')
        time.sleep(1)
        tx_prev = tx
        rx_prev = rx
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With