A Process is a program that is being executed (processed). A process may not have to be one run explicitly by the user, it could be a system process spawned by the operating system. Any applications that execute on an operating system firstly creates a process of its own in order to execute. In a typical OS installation, most processes are os services and background applications, that are run to maintain the operating system, software and hardware.
In this article, we will take a look at different ways of obtaining the list of running processes of a Windows OS, through Python. Firstly, we would describe a python method in order to achieve the result and then would look at a command found in the Windows Command Processor for the same.
Method 1:
We would be using the wmi library for getting the list of running processes on Windows OS. In order the install the module, execute the following command in the command interpreter of your operating system:-
pip install wmi
COde:
Python3
import
wmi
f
=
wmi.WMI()
print
(
"pid Process name"
)
for
process
in
f.Win32_Process():
print
(f
"{process.ProcessId:<10} {process.Name}"
)
Output:
3196 RuntimeBroker.exe 3524 ShellExperienceHost.exe 3548 SearchIndexer.exe 3796 SearchUI.exe 4136 IDMan.exe 4368 IEMonitor.exe 4488 notepad.exe 2616 SettingSyncHost.exe 4212 dasHost.exe 4664 AdaptiveSleepService.exe 4716 svchost.exe 5412 chrome.exe 1376 chrome.exe 1280 cmd.exe 4928 conhost.exe 5596 py.exe 5060 python.exe 1508 WmiPrvSE.exe
Explanation:
Firstly, we initialize the WMI() function of wmi library. This allows us to use the functions found inside it such as WMI.Win32_Service, WMI.Win32_Process, WMI.Win32_Printjob which are designed to perform different tasks. We would be using the WMI.Win32_Process function in order to get the list of running processes on the system. Then we called the function WMI.Win32_Process() to get the running processes, iterated through each process and stored in variable process. Then we obtained the ProcessID (pid) and ProcessName (name) of the process using the associated attributes. We used F-strings for the output in order to add padding to the output to align it properly.
Method 2:
In this method, we would be using a command found inside the Windows Command Processor (cmd.exe) under the name WMIC ( Windows Management Instrumentation Command line) in order to get the desired result. WMIC is a commandline utility that allows users to performs Windows Management Instrumentation (WMI) operations with a command prompt. For the purpose of getting running processes, we would be executing the command:
wmic process get description, processid
Code:
Python3
import
os
output
=
os.popen(
'wmic process get description, processid'
).read()
print
(output)
Output:
Description ProcessId System Idle Process 0 System 4 smss.exe 340 csrss.exe 460 wininit.exe 604 csrss.exe 624 winlogon.exe 692 services.exe 736 lsass.exe 756 svchost.exe 844 svchost.exe 904 dwm.exe 1012 svchost.exe 80 svchost.exe 420 atiesrxx.exe 1076 svchost.exe 1992 svchost.exe 2032 MsMpEng.exe 2052 NisSrv.exe 2852 sihost.exe 3032 taskhostw.exe 2148 GoogleCrashHandler.exe 2712 GoogleCrashHandler64.exe 2704 explorer.exe 2892 RuntimeBroker.exe 3196 ShellExperienceHost.exe 3524 SearchIndexer.exe 3548 chrome.exe 1340 chrome.exe 2216
Note: It is not mandatory to use the os library for the purpose. The user could pick any other alternatives (Subprocess, shutil etc) which allows for commandline command execution.
Explanation:
We used the function popen() found inside the os module, in order to execute the command in the command processor. Then we passed the output of the above command to read() in order to get data in readable form out of os._wrap_close object. In the end, we displayed the output.
Method 3:
We will use the subprocess module to interact with cmd and to retrieve information into your python ide. we can read the cmd command through the subprocess module.
Let’s see this logic, if we run this wmic process list brief code into our terminal then we got like this:
Approach:
- import module
- Get the output for the command “wmic process list brief ” using subprocess.check_output()
- Now get the Split the string and arrange your data with your own needs.
Code:
Python3
import
subprocess
Data
=
subprocess.check_output([
'wmic'
,
'process'
,
'list'
,
'brief'
])
a
=
str
(Data)
try
:
for
i
in
range
(
len
(a)):
print
(a.split(
"\\r\\r\\n"
)[i])
except
IndexError as e:
print
(
"All Done"
)
Output:
b'HandleCount Name Priority ProcessId ThreadCount WorkingSetSize 0 System Idle Process 0 0 8 8192 5649 System 8 4 222 1835008 0 Registry 8 120 4 33910784 89 smss.exe 11 516 2 532480 815 csrss.exe 13 652 13 2019328 217 wininit.exe 13 740 1 3239936 781 services.exe 9 812 8 8294400 1843 lsass.exe 9 832 7 14864384 86 svchost.exe 8 1020 1 1351680 32 fontdrvhost.exe 8 308 5 196608 1526 svchost.exe 8 8 12 38608896 270 WUDFHost.exe 8 592 5 2097152 1479 svchost.exe 8 1056 11 16363520 541 svchost.exe 8 1104 15 4509696 279 svchost.exe 8 1260 3 2584576 146 svchost.exe 8 1284 1 6389760 214 svchost.exe 8 1300 3 3452928 327 svchost.exe 8 1308 6 5795840 345 svchost.exe 8 1332 13 10571776 395 svchost.exe 8 1452 7 5079040 261 svchost.exe 8 1460 5 5914624 161 svchost.exe 8 1472 2 4902912 390 svchost.exe 8 1580 11 9826304 348 WUDFHost.exe 13 1652 12 11526144 225 svchost.exe 8 1736 2 10473472 205 svchost.exe 8 1744 1 2093056 278 svchost.exe 8 1752 2 4444160 174 svchost.exe 8 1824 4 4063232 224 svchost.exe 8 1832 6 3821568 593 svchost.exe 8 2024 5 7610368 186 svchost.exe 8 1424 2 5058560 168 igfxCUIService.exe 8 2120 2 3579904 435 svchost.exe 8 2188 6 12341248 279 svchost.exe 8 2220 10 5017600 227 svchost.exe 8 2296 3 7024640 221 svchost.exe 8 2308 3 1908736 384 svchost.exe 8 2396 7 8499200 0 Memory Compression 8 2424 54 298409984 240 svchost.exe 8 2440 2 4845568 179 svchost.exe 8 2476 5 3567616 239 svchost.exe 8 2660 8 5775360 3352 svchost.exe 8 2684 9 6230016 225 svchost.exe 8 2816 2 4804608 487 svchost.exe 8 2872 7 9641984 473 svchost.exe 8 2912 4 13836288 142 svchost.exe 8 3032 4 2727936 633 svchost.exe 8 3048 3 16154624 555 svchost.exe 8 2072 14 12455936 267 svchost.exe 8 2936 4 7462912 465 spoolsv.exe 8 3168 7 4685824 420 svchost.exe 8 3200 10 8019968 187 svchost.exe 8 3324 6 2433024 174 svchost.exe 8 3572 2 2650112 416 svchost.exe 8 3584 5 13344768 540 svchost.exe 8 3592 10 24936448 161 IntelCpHDCPSvc.exe 8 3604 3 2052096 406 svchost.exe 8 3612 19 25100288
Last Updated :
29 Dec, 2020
Like Article
Save Article
I amm writing a little python script that will grab information from VMs of Windows that I am running.
At the moment I can list the processes on a 32bit XP machine with the following method:
http://code.activestate.com/recipes/305279/
Is it possible to somehow detect the version of windows running and excute a different method for getting the processes on a 64bit machine, I am trying to get the processes from a 64Bit Vista and 64bit Windows 7.
Any ideas?
tshepang
12.1k21 gold badges91 silver badges136 bronze badges
asked Oct 27, 2009 at 16:55
There is another recipe on activestate that does a similar thing, but uses the Performance Data Helper library (PDH) instead.
I have tested this on my Windows 7 64bit machine and it works there — so presumably the same function will work on both 32bit and 64 bit windows.
You can find the recipe here: http://code.activestate.com/recipes/303339/
Another method is using WMI, there is an example here in Python using the wmi module:
http://timgolden.me.uk/python/wmi/cookbook.html
import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
print process.ProcessId, process.Name
answered Oct 27, 2009 at 17:06
Andre MillerAndre Miller
15.3k6 gold badges55 silver badges53 bronze badges
6
The cleanest way I found to solve this was to use the psutil library as recommended by Robert Lujo:
psutil.process_iter()
Note that it returns a generator object, issuing a process object at a time. For example if you need the list of process names, you can do something like:
[p.name() for p in psutil.process_iter()]
Mathias711
6,5784 gold badges42 silver badges58 bronze badges
answered Apr 27, 2017 at 19:29
1
For similar purposes I have used psutil library. Some hints:
- list processes with
psutil.pids()
(reference) - inspect process information with
process = psutil.Process(pid)
(reference) - do
process.kill
orprocess.terminate()
Installation on windows — pip
will do installation from the source (which means compiling), so you probably want to download binary installation from https://pypi.python.org/pypi/psutil/#downloads.
answered May 13, 2013 at 10:14
Robert LujoRobert Lujo
15.4k5 gold badges56 silver badges73 bronze badges
1
The other day, I was tasked with finding a way to get a list of all running processes on a Windows XP virtual machine. I was also supposed to include information about how much CPU and memory each process used. Fortunately, this didn’t have to be a remote script, but one that could be run on the client. After a fair bit of Googling here and there, I finally found a solution. In this article, we’ll look at some of the rejects as well as the eventual solution, which happens to work cross-platform.
One of the first scripts I found was this one back from March of 2006:
# http://mail.python.org/pipermail/python-win32/2006-March/004340.html import win32com.client wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): print p.Name, p.Properties_('ProcessId'), \ int(p.Properties_('UserModeTime').Value)+int(p.Properties_('KernelModeTime').Value) children=wmi.ExecQuery('Select * from win32_process where ParentProcessId=%s' %p.Properties_('ProcessId')) for child in children: print '\t',child.Name,child.Properties_('ProcessId'), \ int(child.Properties_('UserModeTime').Value)+int(child.Properties_('KernelModeTime').Value)
This script requires the PyWin32 package to work. However, while it’s a handy little script, it doesn’t show anything that I want except the ProcessId. I don’t really care about the user or kernel mode times (i.e. the total CPU time by user or kernel). Also I don’t really like working with the black magic of COM, so I ended up rejecting this one out of hand.
Next up was an ActiveState recipe. It looked promising:
# http://code.activestate.com/recipes/303339-getting-process-information-on-windows/ import win32pdh, string, win32api def procids(): #each instance is a process, you can have multiple processes w/same name junk, instances = win32pdh.EnumObjectItems(None,None,'process', win32pdh.PERF_DETAIL_WIZARD) proc_ids=[] proc_dict={} for instance in instances: if instance in proc_dict: proc_dict[instance] = proc_dict[instance] + 1 else: proc_dict[instance]=0 for instance, max_instances in proc_dict.items(): for inum in xrange(max_instances+1): hq = win32pdh.OpenQuery() # initializes the query handle path = win32pdh.MakeCounterPath( (None,'process',instance, None, inum,'ID Process') ) counter_handle=win32pdh.AddCounter(hq, path) win32pdh.CollectQueryData(hq) #collects data for the counter type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG) proc_ids.append((instance,str(val))) win32pdh.CloseQuery(hq) proc_ids.sort() return proc_ids print procids()
Alas, while this also got me a list of processes from my Windows box (along with the PID), it didn’t give me any information on the CPU and memory utilization. I think this one could work if I used different counter names. I’m guessing if you wanted, you could figure out that information using MSDN. I didn’t want to mess with that, so I continued digging.
That recipe led me to the following one based on ctypes:
# http://code.activestate.com/recipes/305279/ """ Enumerates active processes as seen under windows Task Manager on Win NT/2k/XP using PSAPI.dll (new api for processes) and using ctypes.Use it as you please. Based on information from http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q175030&ID=KB;EN-US;Q175030 By Eric Koome email ekoome@yahoo.com license GPL """ from ctypes import * #PSAPI.DLL psapi = windll.psapi #Kernel32.DLL kernel = windll.kernel32 def EnumProcesses(): arr = c_ulong * 256 lpidProcess= arr() cb = sizeof(lpidProcess) cbNeeded = c_ulong() hModule = c_ulong() count = c_ulong() modname = c_buffer(30) PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_VM_READ = 0x0010 #Call Enumprocesses to get hold of process id's psapi.EnumProcesses(byref(lpidProcess), cb, byref(cbNeeded)) #Number of processes returned nReturned = cbNeeded.value/sizeof(c_ulong()) pidProcess = [i for i in lpidProcess][:nReturned] for pid in pidProcess: #Get handle to the process based on PID hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid) if hProcess: psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count)) psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname)) print "".join([ i for i in modname if i != '\x00']) #-- Clean up for i in range(modname._length_): modname[i]='\x00' kernel.CloseHandle(hProcess) if __name__ == '__main__': EnumProcesses()
This is pretty clever looking, but I’m pretty bad at parsing ctypes. It’s something I want to learn, but I had a deadline, doggone it! Plus this one only showed a list of running processes but no information about them. Fortunately, the author included a reference, but I decided to keep looking.
Next I found a thread about using Tim Golden’s handy WMI module to do this sort of thing (below is copied right from the thread):
# http://mail.python.org/pipermail/python-win32/2003-December/001482.html >>> processes = WMI.InstancesOf('Win32_Process') >>> len(processes) 41 >>> [process.Properties_('Name').Value for process in processes] # get the process names [u'System Idle Process', u'System', u'SMSS.EXE', u'CSRSS.EXE', u'WINLOGON.EXE', u'SERVICES.EXE', u'LSASS.EXE', u'SVCHOST.EXE', u'SVCHOST.EXE', u'SVCHOST.EXE', u'SVCHOST.EXE', u'SPOOLSV.EXE', u'ati2evxx.exe', u'BAsfIpM.exe', u'defwatch.exe', u'inetinfo.exe', u'mdm.exe', u'rtvscan.exe', u'SCARDSVR.EXE', u'WLTRYSVC.EXE', u'BCMWLTRY.EXE', u'EXPLORER.EXE', u'Apoint.exe', u'carpserv.exe', u'atiptaxx.exe', u'quickset.exe', u'DSentry.exe', u'Directcd.exe', u'vptray.exe', u'ApntEx.exe', u'FaxCtrl.exe', u'digstream.exe', u'CTFMON.EXE', u'wuauclt.exe', u'IEXPLORE.EXE', u'Pythonwin.exe', u'MMC.EXE', u'OUTLOOK.EXE', u'LineMgr.exe', u'SAPISVR.EXE', u'WMIPRVSE.EXE'] Here is how to get a single process and get its PID. >>> p = WMI.ExecQuery('select * from Win32_Process where Name="Pythonwin.exe"') >>> [prop.Name for prop in p[0].Properties_] # let's look at all the process property names [u'Caption', u'CommandLine', u'CreationClassName', u'CreationDate', u'CSCreationClassName', u'CSName', u'Description', u'ExecutablePath', u'ExecutionState', u'Handle', u'HandleCount', u'InstallDate', u'KernelModeTime', u'MaximumWorkingSetSize', u'MinimumWorkingSetSize', u'Name', u'OSCreationClassName', u'OSName', u'OtherOperationCount', u'OtherTransferCount', u'PageFaults', u'PageFileUsage', u'ParentProcessId', u'PeakPageFileUsage', u'PeakVirtualSize', u'PeakWorkingSetSize', u'Priority', u'PrivatePageCount', u'ProcessId', u'QuotaNonPagedPoolUsage', u'QuotaPagedPoolUsage', u'QuotaPeakNonPagedPoolUsage', u'QuotaPeakPagedPoolUsage', u'ReadOperationCount', u'ReadTransferCount', u'SessionId', u'Status', u'TerminationDate', u'ThreadCount', u'UserModeTime', u'VirtualSize', u'WindowsVersion', u'WorkingSetSize', u'WriteOperationCount', u'WriteTransferCount'] >>> p[0].Properties_('ProcessId').Value # get our ProcessId 928
This is some cool stuff and I use Golden’s modules in some of my other code. However, I was still uncertain as to which counters to use to get to my information. I thought most of this stuff would just be coded for me or something! Well, it turned out that there is a package out there that does exactly what I needed AND it works on all the three of the major platforms! Amazing!
The Cross-Platform Solution!
The package’s name is psutil and it was what I decided to use. Here’s what I ended up with:
import os import psutil import time logPath = r'some\path\proclogs' if not os.path.exists(logPath): os.mkdir(logPath) separator = "-" * 80 format = "%7s %7s %12s %12s %30s, %s" format2 = "%7.4f %7.2f %12s %12s %30s, %s" while 1: procs = psutil.get_process_list() procs = sorted(procs, key=lambda proc: proc.name) logPath = r'some\path\proclogs\procLog%i.log' % int(time.time()) f = open(logPath, 'w') f.write(separator + "\n") f.write(time.ctime() + "\n") f.write(format % ("%CPU", "%MEM", "VMS", "RSS", "NAME", "PATH")) f.write("\n") for proc in procs: cpu_percent = proc.get_cpu_percent() mem_percent = proc.get_memory_percent() rss, vms = proc.get_memory_info() rss = str(rss) vms = str(vms) name = proc.name path = proc.path f.write(format2 % (cpu_percent, mem_percent, vms, rss, name, path)) f.write("\n\n") f.close() print "Finished log update!" time.sleep(300) print "writing new log data!"
Yes, it’s an infinite loop and yes, that’s usually a very bad thing to do (except in GUI programming). However, for my purpose, I needed a way to check the user’s processes every 5 minutes or so to see what was causing the machine to act so weird. Thus, the script needs to run forever and log the results to uniquely named files. That’s all this script does, along with a little formatting magic. Feel free to use it or not as you see fit.
I hope you found this collection of material helpful. Hopefully it will save you all the digging I went through!
Note: While this last script appears to work just fine on Windows XP, on Windows 7 32 and 64-bit, you will get an “Access Denied” traceback, I suspect this is caused by Window 7’s increased security, but I will try to find a workaround.
UPDATE (10/09/2010) – The psutil folks don’t know why it doesn’t work, but one of their developers has confirmed the issue. You can follow along on their Google Groups list.
Question:
I would like to know how to get the running windows processes 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 a way to put them in a list, even if another library is used.
Answer:
For a cross-platform solution, use the psutil package.
1 – Install it from github or (easier) with pip:
pip install psutil
2 – Run the following sample 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 just with the names, for example, just do:
processos = [proc.name() for proc in ps.process_iter()]
The list of process information access methods you can use (in the proc
variable, illustrated in the code above) is in the documentation for the Process
class .
Post Views: 2
In a Python program, it may be necessary to monitor and display the list of running processes on a system. There are various ways to accomplish this task and retrieve the process information in Python. This article lists the methods to display the list of running processes in Python.
Method 1: psutil
To display a list of running processes in Python, you can use the «psutil» library. Here’s how you can do it:
- Install psutil by running the following command in your terminal:
- Import the psutil library by adding the following line to your Python code:
- To get a list of all running processes, you can use the «psutil.process_iter()» method. This method returns an iterator that yields a «psutil.Process» object for each running process. Here’s an example of how to use it:
for process in psutil.process_iter():
print(process.name())
- You can also get more information about each process by calling various methods on the «psutil.Process» object. For example, you can get the process ID, memory usage, CPU usage, and more. Here are some examples:
for process in psutil.process_iter():
print("Process name:", process.name())
print("Process ID:", process.pid)
print("Memory usage (in bytes):", process.memory_info().rss)
print("CPU usage:", process.cpu_percent(interval=1.0))
- Additionally, you can filter the list of processes by various criteria. For example, you can get a list of all processes that are running under a specific user account:
username = "myusername"
for process in psutil.process_iter(attrs=["username"]):
if process.info["username"] == username:
print(process.name())
That’s it! With these examples, you should be able to display a list of running processes in Python using the «psutil» library.
Method 2: subprocess
To display a list of running processes in Python using the subprocess
module, you can use the subprocess.run()
function to run the ps
command on a Unix-based system. Here’s how to do it:
import subprocess
result = subprocess.run(['ps', '-A'], stdout=subprocess.PIPE)
output = result.stdout.decode()
lines = output.split('\n')
for line in lines:
print(line)
Let’s break down what’s happening in this code:
- We import the
subprocess
module. - We use the
subprocess.run()
function to run theps
command with the-A
flag, which lists all processes on the system. We capture the output of this command in asubprocess.CompletedProcess
object. - We decode the output of the command using the
stdout.decode()
method, which converts the bytes returned by the command to a string. - We split the output into lines using the
str.split()
method. - We loop through each line of the output and print it to the console.
This code should work on any Unix-based system that has the ps
command installed. If you’re on Windows, you can use the tasklist
command instead of ps
. Here’s an example:
import subprocess
result = subprocess.run(['tasklist'], stdout=subprocess.PIPE)
output = result.stdout.decode()
lines = output.split('\n')
for line in lines:
print(line)
Again, let’s break down what’s happening:
- We import the
subprocess
module. - We use the
subprocess.run()
function to run thetasklist
command, which lists all running processes on Windows. We capture the output of this command in asubprocess.CompletedProcess
object. - We decode the output of the command using the
stdout.decode()
method, which converts the bytes returned by the command to a string. - We split the output into lines using the
str.split()
method. - We loop through each line of the output and print it to the console.
That’s it! With these examples, you should be able to display a list of running processes in Python using the subprocess
module.
Method 3: os
To display a list of running processes in Python using the os
module, follow these steps:
- Import the
os
module:
- Use the
os.popen
function to execute theps
command, which lists all running processes:
processes = os.popen('ps -A').readlines()
- Loop through the list of processes and print out each process:
for process in processes:
print(process)
Here is the complete code:
import os
processes = os.popen('ps -A').readlines()
for process in processes:
print(process)
This code will output a list of running processes, including their process ID (PID), user, CPU usage, and memory usage. Note that the output format may vary depending on the operating system and version of the ps
command.
Another way to get a list of running processes using os
is to use the os.listdir
function to list the contents of the /proc
directory, which contains information about running processes on Linux systems:
import os
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
# Read the process status file to get information about the process
with open(os.path.join('/proc', pid, 'status'), 'r') as f:
status = f.readlines()
print(status[0])
except IOError:
# Ignore processes that have terminated since we got the list of PIDs
continue
This code will output a list of running processes, including their process ID (PID), name, and status. Note that this method only works on Linux systems and may require elevated privileges to access certain process information.