简体   繁体   中英

How can I check if a process is running in python

In C#, I have:

Process.GetProcessesByName

I'm looking for something like that in Python?

You can use psutil module:

It currently supports Linux, Windows, OSX, FreeBSD, Sun Solaris both 32-bit and 64-bit with Python versions from 2.4 to 3.3 by using a single code base .

First install it:

pip install psutil

Then do similar what Process.GetProcessesByName method do:

Creates an array of new Process components and associates them with all the process resources on the local computer that share the specified process name.

Code:

import psutil

def get_processes_by_name(name):
    return [process for process in psutil.process_iter() if process.name == name]


print(get_processes_by_name('python'))

Output:

[<psutil.Process(pid=10217, name='python') at 44007184>, 
 <psutil.Process(pid=10223, name='python') at 44007312>
]

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