#!/usr/bin/python3

import psutil

def getListOfProcessSortedByMemory():

    '''
    Get list of running process sorted by Memory Usage
    '''
    listOfProcObjects = []
    # Iterate over the list
    for proc in psutil.process_iter():
        try:
            # Fetch process details as dict
            pinfo = proc.as_dict(attrs=['pid', 'name', 'username'])
            #pinfo['vms'] = proc.memory_info().vms / (1024 * 1024)
            pinfo['network'] = proc.connections()
            #pinfo['network'] = psutil.Process(pinfo['pid']).connections()
            # Append dict to list
            listOfProcObjects.append(pinfo);
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    # Sort list of dict by key vms i.e. memory usage
    listOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['network'], reverse=True)
    return listOfProcObjects
def process_list():
    listOfRunningProcess = getListOfProcessSortedByMemory()
    #time.sleep(3)
    #secound_check = psutil.net_io_counters(pernic=True, nowrap=True)['enp7s0'].bytes_recv
    #network_usage = []
    for elem in listOfRunningProcess[:3]:
    #    elem['network_in'] = secound_check - elem['network_in']
    #    network_usage.append(elem)
        print(len(elem['network']))
        print(elem['network'])
    #for elem in self.listOfRunningProcess[:5] :
    #for elem in network_usage[:5]:
    #    elem['network_in'] = secound_check - elem['network_in']
    #    print(f"name: {elem['name']} pid: {elem['pid']} network_in: {elem['network_in']}")

process_list()
