I’m new to python and I need to calculate the ‘average speed’ of my network interface(like the tool nload) on a linux machine. The below code is telling me how much bytes have been sent and received. I would appreciate if someone could help me print the average speed of my network interface.
def main():
rx_bytes, tx_bytes = get_network_bytes('eth0')
print '%i bytes received' % rx_bytes
print '%i bytes sent' % tx_bytes
def get_network_bytes(interface):
for line in open('/proc/net/dev', 'r'):
if interface in line:
data = line.split('%s:' % interface)[1].split()
rx_bytes, tx_bytes = (data[0], data[8])
return (int(rx_bytes), int(tx_bytes))
if __name__ == '__main__':
main()
Take your main() and get_network_bytes() and wrap them in a python process:
Then run with “python myscript.py start” or stop or restart, the process ID will be printed on the screen. With this running in the background you’ll need to import that script as part of your other program to query it, or you can always have your result print to a temp file each time it loops and then have your other program(s) query that temp file. “There’s a number of different ways to do this”
Edit:
Start with something like this and customize, this is really only one way to go about it, I would suggest another library like psutil rather then messy parsing of ifconfig which only works in linux:
“Make sure to change the interface, I’m using WLAN0 you may be using something different”
The following script will print out to the screen every 60 seconds the average TX and RX rates for that last minute.
Again this works with: “python myscript.py start” and stop and restart. You’ll want to add some file open and write rather then print to the screen. I would also suggest that you open your files for writing with gzip.open() to save some space as they will grow large quickly.
Edit:
Here’s the same daemon this time writing to a file /tmp/netstats_counter.log which is a csv containing “tx rate in KB/s over 1 minute intervals, average rx rate in KB/s over 1 minute intervals, unix timestamp”