import re import time # A regular expression which separates the interesting fields and saves them in named groups regexp = r""" \s* # a interface line starts with none, one or more whitespaces (?P\w+):\s+ # the name of the interface followed by a colon and spaces (?P\d+)\s+ # the number of received bytes and one or more whitespaces (?P\d+)\s+ # the number of received packets and one or more whitespaces (?P\d+)\s+ # the number of receive errors and one or more whitespaces (?P\d+)\s+ # the number of dropped rx packets and ... (?P\d+)\s+ # rx fifo (?P\d+)\s+ # rx frame (?P\d+)\s+ # rx compressed (?P\d+)\s+ # rx multicast (?P\d+)\s+ # the number of transmitted bytes and one or more whitespaces (?P\d+)\s+ # the number of transmitted packets and one or more whitespaces (?P\d+)\s+ # the number of transmit errors and one or more whitespaces (?P\d+)\s+ # the number of dropped tx packets and ... (?P\d+)\s+ # tx fifo (?P\d+)\s+ # tx frame (?P\d+)\s+ # tx compressed (?P\d+)\s* # tx multicast """ pattern = re.compile(regexp, re.VERBOSE) def get_bytes(interface_name): '''returns tuple of (rx_bytes, tx_bytes) ''' with open('/proc/net/dev', 'r') as f: a = f.readline() while(a): m = pattern.search(a) # the regexp matched # look for the needed interface and return the rx_bytes and tx_bytes if m: if m.group('interface') == interface_name: return (m.group('rx_bytes'),m.group('tx_bytes')) a = f.readline() while True: last_time = time.time() last_bytes = get_bytes('wlxa4db303b745e') time.sleep(1) now_bytes = get_bytes('wlxa4db303b745e') print("rx: {} B/s, tx {} B/s".format(int(now_bytes[0]) - int(last_bytes[0]), int(now_bytes[1]) - int(last_bytes[1])))