Search code examples
pythonprocesspidpsutil

How to get the pid of process using python


I have a task list file which is having firefox , atom , gnome-shell

My code

import psutil
with open('tasklist', 'r') as task:
    x = task.read()
    print (x)

print ([p.info for p in psutil.process_iter(attrs=['pid', 'name']) if x in p.info['name']])

Desired out

[{'pid': 413, 'name': 'firefox'}]
[{'pid': 8416, 'name': 'atom'}]
[{'pid': 2322, 'name': 'gnome-shell'}]

Solution

  • similar to the answers above, but from the question it seems you are only interested in a subset of all running tasks (e.g. firefox, atom and gnome-shell)

    you can put the tasks you are interested in into a list..then loop through all of the processes, only appending the ones matching your list to the final output, like so:

    import psutil
    
    tasklist=['firefox','atom','gnome-shell']
    out=[]
    
    for proc in psutil.process_iter():
        if any(task in proc.name() for task in tasklist):
            out.append([{'pid' : proc.pid, 'name' : proc.name()}])
    

    this will give you your desired output of a list of lists, where each list has a dictionary with the pid and name keys...you can tweak the output to be whatever format you like however

    the exact output you requested can be obtained by:

    for o in out[:]:
        print(o)