user1464878
user1464878

Reputation:

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'}]

Upvotes: 0

Views: 660

Answers (2)

Derek Eden
Derek Eden

Reputation: 4618

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)

Upvotes: 1

Kostas Charitidis
Kostas Charitidis

Reputation: 3103

import wmi  # pip install wmi

c = wmi.WMI()
tasklist = []

for process in c.Win32_Process():
    tasklist.append({'pid': process.ProcessId, 'name': process.Name})
print(tasklist)

For Unix:

import psutil

tasklist = []

for proc in psutil.process_iter():
    try:
        tasklist.append({'pid': proc.name(), 'name': proc.pid})
    except:
        pass
print(tasklist)

Upvotes: 0

Related Questions