How to get a list of processes running windows in python?

Asked

Viewed 2,422 times

3

I would like to know how to get the processes running from windows and store them in a list in python.

from os import system
system('tasklist')

I know that the code above shows the processes, but I would like to have how to put them in a list, even if another library is used.

2 answers

4


For a solution cross-Platform, use the package psutil.

1 - Install it from github or (easier) with Pip:

pip install psutil

2 - Run the following example program:

import psutil as ps

print('Lista de processos em execução:')
for proc in ps.process_iter():
    info = proc.as_dict(attrs=['pid', 'name'])
    print('Processo: {} (PID: {})'.format(info['pid'], info['name']))

It lists the data (name and pid) of the processes one by one, obtained through a dictionary. But if you want to build a list with just the names, for example, just do:

processos = [proc.name() for proc in ps.process_iter()]

The list with the methods of accessing the process information you can use (in the variable proc, illustrated in the above code) is in the class documentation Process.

2

I found out here a possible solution:

import wmi
c = wmi.WMI ()

for process in c.Win32_Process():
    print(process.ProcessId, process.Name)

Reference

I did not test because I do not have windows, but if it does not work I withdraw the answer without problem

  • To the letter, only the first one worked, @miguel.

  • @Benedito still helped. You tried them all right? I will eliminate the others, because as I did not test I will take to have no wrong alternatives

Browser other questions tagged

You are not signed in. Login or sign up in order to post.