Tracking the resource usage of a process of interest

from subprocess import Popen, PIPE from time import sleep import re track_process_name = 'Xorg' p = Popen('top', stdout=PIPE) spaces = re.compile(r'\s+') resource_usage = [('cpu', 1), ('mem', 1)] position_indices = [('cpu', -5), ('mem', -4)] refresh_frequency_s = 3 print(track_process_name + ' process resource usage:') while True : for line in p.stdout: decoded = line.decode('utf-8') features = spaces.split(decoded.split('\n')[0]) row = '|'.join(features) if track_process_name in row: print(' | '.join([ "%s: %s" % ( param_to_track.upper(), features[position_indices[i][1]].replace(',', '.') ) for i, (param_to_track, on) in enumerate(resource_usage) if on ])) break sleep(refresh_frequency_s) # To stop script execition, press Ctrl + Z in the console """ Xorg process resource usage: CPU: 1.7 | MEM: 1.2 CPU: 3.3 | MEM: 1.2 CPU: 6.3 | MEM: 1.2 CPU: 5.3 | MEM: 1.2 CPU: 6.0 | MEM: 1.2 CPU: 10.6 | MEM: 1.2 CPU: 4.3 | MEM: 1.2 CPU: 9.5 | MEM: 1.2 CPU: 1.7 | MEM: 1.2 CPU: 2.3 | MEM: 1.2 CPU: 2.0 | MEM: 1.2 CPU: 1.7 | MEM: 1.2 CPU: 2.0 | MEM: 1.2 CPU: 11.0 | MEM: 1.2 CPU: 7.6 | MEM: 1.2 CPU: 12.3 | MEM: 1.2 """