简体   繁体   中英

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

similar to the answers above, but from the question it seems you are only interested in a subset of all running tasks (eg 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM