简体   繁体   中英

How can I check with pywin or win32com.client in python if a certain task is running in task manager?

I have to say for example the task firefox.exe running in the task manager. With python`s win32com.client I want to check if firefox is open give a message and if its not open give another message or open it or something else

I tried printing all the processes and then searching for 'firefox.exe' in the processes in process.Name but it doesnt work

import wmi
import win32com.client

if win32com.client.GetActiveObject("firefox.application")
print("Running firefox !!!")
else:
print("No Firefox!!!")

This is what I have tried now but it doesnt work

I would like the python script to search for a process in the task manager and if it is not open to open it or do something else.

Thank you

GetActiveObject is for obtaining a reference to a COM object instance that has been registered with a global Running Object table. It is not really what you need here. You can use the COM interface to the Windows Management Interface to get the list of processes quite simply though.

import win32com
wmi = win32com.client.GetObject('winmgmts:')
pids = [p.ProcessId for p in wmi.InstancesOf('win32_process') if p.Name == 'firefox.exe']

So we can get a list of processes using the WMI Win32_Process class and filter that for our executable name and get the process id or another property from the process object.

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