Как найти процесс python

Is there a way to check to see if a pid corresponds to a valid process? I’m getting a pid from a different source other than from os.getpid() and I need to check to see if a process with that pid doesn’t exist on the machine.

I need it to be available in Unix and Windows. I’m also checking to see if the PID is NOT in use.

Omer Dagan's user avatar

Omer Dagan

14.6k16 gold badges43 silver badges60 bronze badges

asked Feb 20, 2009 at 4:22

Evan Fosmark's user avatar

Evan FosmarkEvan Fosmark

98.2k36 gold badges105 silver badges117 bronze badges

6

Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise.

import os

def check_pid(pid):        
    """ Check For the existence of a unix pid. """
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    else:
        return True

Brandon Rhodes's user avatar

answered Feb 20, 2009 at 4:31

mluebke's user avatar

13

Have a look at the psutil module:

psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python. […] It currently supports Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.4 (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.

It has a function called pid_exists() that you can use to check whether a process with the given pid exists.

Here’s an example:

import psutil
pid = 12345
if psutil.pid_exists(pid):
    print("a process with pid %d exists" % pid)
else:
    print("a process with pid %d does not exist" % pid)

For reference:

  • https://pypi.python.org/pypi/psutil
  • https://github.com/giampaolo/psutil
  • http://pythonhosted.org/psutil/#psutil.pid_exists

Community's user avatar

answered Jul 12, 2013 at 19:16

moooeeeep's user avatar

moooeeeepmoooeeeep

31.3k22 gold badges97 silver badges183 bronze badges

2

mluebke code is not 100% correct; kill() can also raise EPERM (access denied) in which case that obviously means a process exists. This is supposed to work:

(edited as per Jason R. Coombs comments)

import errno
import os

def pid_exists(pid):
    """Check whether pid exists in the current process table.
    UNIX only.
    """
    if pid < 0:
        return False
    if pid == 0:
        # According to "man 2 kill" PID 0 refers to every process
        # in the process group of the calling process.
        # On certain systems 0 is a valid PID but we have no way
        # to know that in a portable fashion.
        raise ValueError('invalid PID 0')
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH)
            raise
    else:
        return True

You can’t do this on Windows unless you use pywin32, ctypes or a C extension module.
If you’re OK with depending from an external lib you can use psutil:

>>> import psutil
>>> psutil.pid_exists(2353)
True

user3758232's user avatar

answered Aug 4, 2011 at 11:08

Giampaolo Rodolà's user avatar

Giampaolo RodolàGiampaolo Rodolà

12.4k6 gold badges68 silver badges60 bronze badges

8

The answers involving sending ‘signal 0’ to the process will work only if the process in question is owned by the user running the test. Otherwise you will get an OSError due to permissions, even if the pid exists in the system.

In order to bypass this limitation you can check if /proc/<pid> exists:

import os

def is_running(pid):
    if os.path.isdir('/proc/{}'.format(pid)):
        return True
    return False

This applies to linux based systems only, obviously.

answered Jan 25, 2017 at 12:33

Omer Dagan's user avatar

Omer DaganOmer Dagan

14.6k16 gold badges43 silver badges60 bronze badges

4

In Python 3.3+, you could use exception names instead of errno constants. Posix version:

import os

def pid_exists(pid): 
    if pid < 0: return False #NOTE: pid == 0 returns True
    try:
        os.kill(pid, 0) 
    except ProcessLookupError: # errno.ESRCH
        return False # No such process
    except PermissionError: # errno.EPERM
        return True # Operation not permitted (i.e., process exists)
    else:
        return True # no error, we can send a signal to the process

answered Nov 25, 2013 at 7:05

jfs's user avatar

jfsjfs

396k192 gold badges976 silver badges1667 bronze badges

Look here for windows-specific way of getting full list of running processes with their IDs. It would be something like

from win32com.client import GetObject
def get_proclist():
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    return [process.Properties_('ProcessID').Value for process in processes]

You can then verify pid you get against this list. I have no idea about performance cost, so you’d better check this if you’re going to do pid verification often.

For *NIx, just use mluebke’s solution.

answered Feb 20, 2009 at 7:20

Alexander Lebedev's user avatar

1

Building upon ntrrgc’s I’ve beefed up the windows version so it checks the process exit code and checks for permissions:

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if os.name == 'posix':
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
    else:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        HANDLE = ctypes.c_void_p
        DWORD = ctypes.c_ulong
        LPDWORD = ctypes.POINTER(DWORD)
        class ExitCodeProcess(ctypes.Structure):
            _fields_ = [ ('hProcess', HANDLE),
                ('lpExitCode', LPDWORD)]

        SYNCHRONIZE = 0x100000
        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if not process:
            return False

        ec = ExitCodeProcess()
        out = kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
        if not out:
            err = kernel32.GetLastError()
            if kernel32.GetLastError() == 5:
                # Access is denied.
                logging.warning("Access is denied to get pid info.")
            kernel32.CloseHandle(process)
            return False
        elif bool(ec.lpExitCode):
            # print ec.lpExitCode.contents
            # There is an exist code, it quit
            kernel32.CloseHandle(process)
            return False
        # No exit code, it's running.
        kernel32.CloseHandle(process)
        return True

answered May 1, 2014 at 14:06

speedplane's user avatar

speedplanespeedplane

15.6k16 gold badges85 silver badges138 bronze badges

3

Combining Giampaolo Rodolà’s answer for POSIX and mine for Windows I got this:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False

Community's user avatar

answered Jul 15, 2013 at 0:24

Alicia's user avatar

AliciaAlicia

1,1321 gold badge14 silver badges28 bronze badges

2

In Windows, you can do it in this way:

import ctypes
PROCESS_QUERY_INFROMATION = 0x1000
def checkPid(pid):
    processHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0,pid)
    if processHandle == 0:
        return False
    else:
        ctypes.windll.kernel32.CloseHandle(processHandle)
    return True

First of all, in this code you try to get a handle for process with pid given. If the handle is valid, then close the handle for process and return True; otherwise, you return False. Documentation for OpenProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx

answered Jan 21, 2015 at 11:19

Andrei's user avatar

0

This will work for Linux, for example if you want to check if banshee is running… (banshee is a music player)

import subprocess

def running_process(process):
    "check if process is running. < process > is the name of the process."

    proc = subprocess.Popen(["if pgrep " + process + " >/dev/null 2>&1; then echo 'True'; else echo 'False'; fi"], stdout=subprocess.PIPE, shell=True)

    (Process_Existance, err) = proc.communicate()
    return Process_Existance

# use the function
print running_process("banshee")

L3viathan's user avatar

L3viathan

26.5k2 gold badges57 silver badges80 bronze badges

answered May 26, 2014 at 23:00

BARSPIN's user avatar

1

The following code works on both Linux and Windows, and not depending on external modules

import os
import subprocess
import platform
import re

def pid_alive(pid:int):
    """ Check For whether a pid is alive """


    system = platform.uname().system
    if re.search('Linux', system, re.IGNORECASE):
        try:
            os.kill(pid, 0)
        except OSError:
            return False
        else:
            return True
    elif re.search('Windows', system, re.IGNORECASE):
        out = subprocess.check_output(["tasklist","/fi",f"PID eq {pid}"]).strip()
        # b'INFO: No tasks are running which match the specified criteria.'

        if re.search(b'No tasks', out, re.IGNORECASE):
            return False
        else:
            return True
    else:
        raise RuntimeError(f"unsupported system={system}")

It can be easily enhanced in case you need

  1. other platforms
  2. other language

answered Aug 20, 2020 at 1:56

oldpride's user avatar

oldprideoldpride

7027 silver badges13 bronze badges

I found that this solution seems to work well in both windows and linux. I used psutil to check.

import psutil
import subprocess
import os
p = subprocess.Popen(['python', self.evaluation_script],stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 

pid = p.pid

def __check_process_running__(self,p):
    if p is not None:
        poll = p.poll()
        if poll == None:
            return True
    return False
    
def __check_PID_running__(self,pid):
    """
        Checks if a pid is still running (UNIX works, windows we'll see)
        Inputs:
            pid - process id
        returns:
            True if running, False if not
    """
    if (platform.system() == 'Linux'):
        try:
            os.kill(pid, 0)
            if pid<0:               # In case code terminates
                return False
        except OSError:
            return False 
        else:
            return True
    elif (platform.system() == 'Windows'):
        return pid in (p.pid for p in psutil.process_iter())

answered Oct 14, 2020 at 1:50

Pat's user avatar

PatPat

5971 gold badge8 silver badges23 bronze badges

Another option for Windows is through the pywin32 package:

pid in win32process.EnumProcesses()

The win32process.EnumProcesses() returns PIDs for currently running processes.

answered Mar 11, 2021 at 0:10

ROJI's user avatar

ROJIROJI

1311 silver badge5 bronze badges

After trying different solutions, relying on psutil was the best OS agnostic way to accurately say if a PID exists. As suggested above, psutil.pid_exists(pid) works as intended but the downside is, it includes stale process IDs and processes that were terminated recently.

Solution: Check if process ID exists and if it is actively running.

import psutil

def process_active(pid: int or str) -> bool:
    try:
        process = psutil.Process(pid)
    except psutil.Error as error:  # includes NoSuchProcess error
        return False
    if psutil.pid_exists(pid) and process.status() == psutil.STATUS_RUNNING:
        return True

answered Dec 7, 2022 at 17:06

Vignesh Rao's user avatar

I’d say use the PID for whatever purpose you’re obtaining it and handle the errors gracefully. Otherwise, it’s a classic race (the PID may be valid when you check it’s valid, but go away an instant later)

answered Feb 20, 2009 at 7:39

Damien_The_Unbeliever's user avatar

3

There are two different python programs running in this VM

one is a background job who monitors a folder and then ‘does stuff’ (with several workers)

10835 ?        Sl     0:03 python main.py
10844 ?        Sl    34:02 python main.py
10845 ?        S     33:43 python main.py

the second one is started via script

20056 pts/1    S+     0:00 /bin/bash ./exp.sh
20069 pts/1    S+     0:00 /bin/bash ./exp.sh
20087 pts/1    S+     0:10 python /home/path/second.py

i have tried numerous things to find a way to kill only the main program (i want to build a cron watchdog), but non succeded

first one i want to find only the hanging ‘python main.py’ process (accompanied by [defunct]), but i cant even find just this process alone.

the upper ones are from ps -ax (so they both are running currently)
pgrep ‘python’ returns all PIDs, also from second.py which i dont want: (not usefull, so is pkill therefore)

pgrep 'python'
10835
10844
10845
20087

pgrep ‘python main.py’ always returns empty, so does pgrep ‘main.py;

the only thing which works

ps ax | grep 'python main.py'

but this one also returns its own PID, grepping ‘ps’ isn’t a prefered solution afair. when main.py hangs, it shows «python main.py [defunct]». a

ps ax | grep 'python main.py [defunct]'

is useless as test as it always returns true. pgrep for anything more than ‘python’ also returns always false. i am a bit clueless.

Функции для работы с запущенными процессами в Python.

Материал содержит описание функций модуля psutil с примерами, которые возвращают список текущих запущенных процессов PID, а также удобные функции проверки существования процесса и ожидания завершения списка экземпляров процесса.

Содержание:

  • psutil.pids() список текущих запущенных PID,
  • psutil.process_iter() итератор всех запущенных процессов,
  • psutil.pid_exists() проверяет, существует ли данный PID,
  • psutil.wait_procs() вызывается, когда один из ожидающих процессов завершается,
  • Пример поиска процесса по имени,
  • Примеры фильтрации и сортировки процессов:
    • Процессы, принадлежащие пользователю,
    • Вывод всех запущенных/активных процессов,
    • Процессы, использующие лог-файлы,
    • Процессы, потребляющие более 500 МБ памяти,
    • Топ-3 процесса, потребляющих больше всего процессорного времени.

psutil.pids():

Функция psutil.pids() возвращает отсортированный список текущих запущенных PID. Чтобы перебрать все процессы и избежать условий гонки, следует предпочесть функцию psutil.process_iter().

Пример использования psutil.pids():

>>> import psutil
>>> psutil.pids()
# [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498]

psutil.process_iter(attrs=None, ad_value=None):

Функция psutil.process_iter() возвращает итератор, возвращающий экземпляр класса psutil.Process() для всех запущенных процессов на локальном компьютере. Это должно быть предпочтительнее, чем psutil.pids() для перебора процессов, т.к. это безопасно от состояния гонки.

Каждый экземпляр psutil.Process() создается только один раз, а затем кэшируется для следующего вызова psutil.process_iter() (если PID еще жив). Также это гарантирует, что PID процессов не будут использоваться повторно.

Аргументы attrs и ad_value имеют то же значение, что и в Process.as_dict(). Если attrs указан, то результат Process.as_dict() будет сохранен как информационный атрибут, прикрепленный к возвращенным экземплярам процесса. Если attrs является пустым списком, то он медленно будет получать всю информацию о процессе.

Порядок сортировки, в котором возвращаются процессы, основан на их PID.

Пример использования psutil.process_iter():

>>> import psutil
>>> for proc in psutil.process_iter(['pid', 'name', 'username']):
...     print(proc.info)

# {'name': 'systemd', 'pid': 1, 'username': 'root'}
# {'name': 'kthreadd', 'pid': 2, 'username': 'root'}
# {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'}
# ...

Пример использования выражения генератора словаря для создания структуры данных {pid: info, ...}:

>>> import psutil, pprint
>>> procs = {p.pid: p.info for p in psutil.process_iter(['name', 'username'])}
>>> pprint.pprint(prosc)
# {
#    1: {'name': 'systemd', 'username': 'root'},
#    2: {'name': 'kthreadd', 'username': 'root'},
#    3: {'name': 'ksoftirqd/0', 'username': 'root'},
#  ...
# }

psutil.pid_exists(pid):

Функция psutil.pid_exists() проверяет, существует ли данный PID в текущем списке процессов. Это быстрее, чем выполнение выражения pid in psutil.pids() и должно быть предпочтительным.

psutil.wait_procs(procs, timeout=None, callback=None):

Удобная функция psutil.wait_procs(), ожидающая завершения списка экземпляров процесса. Возвращает кортеж (gone, live), указывающий, какие процессы завершились, а какие еще живы. У завершенных будет новый атрибут returncode, указывающий статус завершения процесса, возвращаемый Process.wait().

Аргумент callback — это функция, которая вызывается, когда один из ожидающих процессов завершается и экземпляр Process передается в качестве аргумента обратного вызова (экземпляр также будет иметь установленный атрибут returncode). Эта функция возвращает результат, как только все процессы завершатся или когда завершиться timeout (в секундах). В отличие от Process.wait(), если завершиться тайм-аут, то функция не будет вызывать исключение TimeoutExpired.

Типичным вариантом использования может быть:

  • отправить SIGTERM в список процессов;
  • дать какое-то время процессам для их корректного завершения;
  • отправить SIGKILL тем процессам, которые еще живы.

Пример, который завершает и ожидает всех дочерних элементов этого процесса:

import psutil

def on_terminate(proc):
    print(f"Процесс {proc} завершается с кодом {proc.returncode}")

procs = psutil.Process().children()
for p in procs:
    p.terminate()
gone, alive = psutil.wait_procs(procs, timeout=3, callback=on_terminate)
for p in alive:
    p.kill()

Пример поиска процесса по имени.

Для поиска процесса сервера по имени необходимо проверить строку с именем на Process.info['name']. Из документации видно, что функция psutil.process_iter() возвращает объект Process, следовательно функция поиска процесса по имени может быть следующая:

import psutil

def find_procs_by_name(name):
    "Возвращает список процессов, соответствующих 'name'."
    ls = []
    for p in psutil.process_iter(['name']):
        if p.info['name'] == name:
            ls.append(p)
    return ls

Более продвинутая функция поиска процесса по имени может быть с дополнительными проверками на Process.name(), Process.exe() и Process.cmdline():

import os
import psutil

def find_procs_by_name(name):
    "Return a list of processes matching 'name'."
    ls = []
    for p in psutil.process_iter(["name", "exe", "cmdline"]):
        if name == p.info['name'] or 
                p.info['exe'] and os.path.basename(p.info['exe']) == name or 
                p.info['cmdline'] and p.info['cmdline'][0] == name:
            ls.append(p)
    return ls

Примеры фильтрации и сортировки процессов.

Коллекция примеров кода, показывающих, как использовать psutil.process_iter() для фильтрации процессов и их сортировки.

Процессы, принадлежащие пользователю:

>>> import psutil
>>> from pprint import pprint as pp
>>> import getpass
>>> pp([
...     (p.pid, p.info['name']) 
...     for p in psutil.process_iter(['name', 'username']) 
...     if p.info['username'] == getpass.getuser()
...    ])

# (16832, 'bash'),
# (19772, 'ssh'),
# (20492, 'python')]

Вывод всех запущенных/активных процессов:

>>> import psutil
>>> from pprint import pprint as pp
>>> pp([
...     (p.pid, p.info) 
...     for p in psutil.process_iter(['name', 'status']) 
...     if p.info['status'] == psutil.STATUS_RUNNING
...    ])

# [
#   (1150, {'name': 'Xorg', 'status': 'running'}),
#   (1776, {'name': 'unity-panel-service', 'status': 'running'}),
#   (20492, {'name': 'python', 'status': 'running'})
# ]

Процессы, использующие лог-файлы:

>>> import psutil
>>> from pprint import pprint as pp
>>> for p in psutil.process_iter(['name', 'open_files']):
...      for file in p.info['open_files'] or []:
...          if file.path.endswith('.log'):
...               print("%-5s %-10s %s" % (p.pid, p.info['name'][:10], file.path))

# 1510  upstart    ~/.cache/upstart/unity-settings-daemon.log
# 2174  nautilus   ~/.local/share/gvfs-metadata/home-ce08efac.log
# 2650  chrome     ~/.config/google-chrome/Default/data_reduction_proxy_leveldb/000003.log

Процессы, потребляющие более 500 МБ памяти:

>>> import psutil
>>> from pprint import pprint as pp
>>> pp([
...     (p.pid, p.info['name'], p.info['memory_info'].rss) 
...     for p in psutil.process_iter(['name', 'memory_info']) 
...     if p.info['memory_info'].rss > 500 * 1024 * 1024
...    ])

# [
#   (2650, 'chrome', 532324352),
#   (3038, 'chrome', 1120088064),
#   (21915, 'sublime_text', 615407616)
# ]

Топ-3 процесса, потребляющих больше всего процессорного времени:

>>> import psutil
>>> from pprint import pprint as pp
>>> pp([
...     (p.pid, p.info['name'], sum(p.info['cpu_times'])) 
...     for p in sorted(psutil.process_iter(['name', 'cpu_times']), 
...                     key=lambda p: sum(p.info['cpu_times'][:2]))
...    ][-3:])

# [
#   (2721, 'chrome', 10219.73),
#   (1150, 'Xorg', 11116.989999999998),
#   (2650, 'chrome', 18451.97)
# ]

Check if process is running: Do you want to determine whether a process is running or not by name and find its Process ID as well? Then, this is the right place as this article will shed light on you completely on how to check if a process is running or not using Name. We have provided enough examples for finding the Process ID PID by Name for better understanding. You can visit our site online to seek guidance or simply copy-paste the code from our portal and try to apply this knowledge and write a code on your own.

  • How to Check if there exists a Process running by Name and find its Process ID (PID)?
  • Determine if Process is Running or Not
  • Finding the Process ID(PID) by Name?

Python : get running processes: In this article, we will discuss finding a running process PIDs by name using psutil.

psutil library can be installed by using

pip install psutil

Determine if Process is Running or Not

Follow the simple guidelines for checking if a process is running or not. They are as such

  • def findProcessIdByName(processName):
  • for proc in psutil. process_iter():
  • pinfo = proc. as_dict(attrs=[‘pid’, ‘name’, ‘create_time’])
  • if processName. lower() in pinfo[‘name’]. lower() :
  • except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :

To check if a process is running or not we will iterate over all the running processes using psutil.process_iter() and during iteration match the process name.

So let’s see this example to check chrome process is running or not.

  • MVC Interview Questions in .NET
  • Rotate an Image by an Angle in Python
  • MYSQL Interview Questions for Freshers
import psutil
def checkProcessRunning(processName):
    # Checking if there is any running process that contains the given name processName.
    #Iterate over the all the running process
    for proc in psutil.process_iter():
        try:
            # Check if process name contains the given name string.
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;

# Checking if any chrome process is running or not.
if checkProcessRunning('chrome'):
    print('Yes chrome process was running')
else:
    print('No chrome process was running')

How to Check if a Process is Running or Not

Output:

No chrome process was running

As in my system chrome instances are not running it will return False.

Finding the Process ID(PID) by Name?

In the above program, we checked any chrome instances were running or not. But in this example, we will see how to get the Process ID of a running ‘chrome.exe’ process. For that we will iterate over all the running processes and during iteration for each process whose name contains the given string, we will keep its information in a list. The following code helps you find the PID of a running process by Name.

import psutil
def findProcessIdByName(processName):
    # Here is the list of all the PIDs of a all the running process 
    # whose name contains the given string processName
    listOfProcessObjects = []
    #Iterating over the all the running process
    for proc in psutil.process_iter():
       try:
           pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
           # Checking if process name contains the given name string.
           if processName.lower() in pinfo['name'].lower() :
               listOfProcessObjects.append(pinfo)
       except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :
           pass
    return listOfProcessObjects;

# Finding PIDs od all the running instances of process 
# which contains 'chrome' in it's name
listOfProcessIds = findProcessIdByName('chrome')
if len(listOfProcessIds) > 0:
   print('Process Exists | PID and other details are')
   for elem in listOfProcessIds:
       processID = elem['pid']
       processName = elem['name']
       processCreationTime =  time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time']))
       print((processID ,processName,processCreationTime ))
else :
   print('No Running Process found with this text')

Finding Process ID by Name

Now, the contents of the list

(2604, 'chrome.exe', '2018-11-10 19:12:13')
(4276, 'chrome.exe', '2018-11-10 19:12:14')
(9136, 'chrome.exe', '2018-11-10 19:12:14')
(9616, 'chrome.exe', '2018-11-10 19:43:41')
(12904, 'chrome.exe', '2018-11-10 19:12:13')
(13476, 'chrome.exe', '2018-11-10 20:03:04')
(15520, 'chrome.exe', '2018-11-10 20:02:22')

This can also be done using a single line using list comprehension  i.e

# Finding the PIDs of all the running instances of process that contains 'chrome' in it's name
procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ]

And the same output will come like

psutil.Process(pid=2604, name='chrome.exe', started='19:12:13')
psutil.Process(pid=4276, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9136, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9616, name='chrome.exe', started='19:43:41')
psutil.Process(pid=12904, name='chrome.exe', started='19:12:13')
psutil.Process(pid=13476, name='chrome.exe', started='20:03:04')
psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')

Answer these:

  1. How To Check If A Process Is Running In Python?
  2. Check If Process Is Running Python?
  3. Check If A Process Is Running Python?
  4. Check If Process Is Alive Python?
  5. How To Check If Python Process Is Running?

Related Programs:

  • Python Program to Map Two Lists into a Dictionary
  • Python Program to Remove Adjacent Duplicate Characters from a String
  • Python Check if Two Lists are Equal
  • Python Program to Merge two Lists and Sort it
  • Python Program for Multiplication of Two Matrices

Conclusion

I hope you may like the content or information in this article, by following this flow of content, more applications will come. And the flow like this, Psutil check if process is running by following this you have to check the python psutil check if process is running, python check if process is running, python script to check if process is running linux, Python check if process is running by pid, then python check if process is running by name, python check running processes, python get pid, python check if pid is running, Python check if Program is running, Python process check if running, Python find process by name, Python get process name, Python get process id.

In this article we will discuss a cross platform way to find a running process PIDs by name using psutil.

To install python’s psutil library use,

Advertisements

pip install psutil

To check if process is running or not, let’s iterate over all the running process using psutil.process_iter() and match the process name i.e.

import psutil

def checkIfProcessRunning(processName):
    '''
    Check if there is any running process that contains the given name processName.
    '''
    #Iterate over the all the running process
    for proc in psutil.process_iter():
        try:
            # Check if process name contains the given name string.
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;

Let’s use this function to check if any process with ‘chrome’ substring in name is running or not i.e.

Frequently Asked:

  • Execute a program or call a system command in Python
  • Python : Get List of all running processes and sort by highest memory usage
  • Python : Check if a process is running by name and find it’s Process ID (PID)
# Check if any chrome process was running or not.
if checkIfProcessRunning('chrome'):
    print('Yes a chrome process was running')
else:
    print('No chrome process was running')

Output:

Yes a chrome process was running

As in my system many chrome instances are running. So it will return True. But how to get the process ID of all the running ‘chrome.exe’ process ?

Find PID (Process ID) of a running process by Name

As there may be many running instances of a given process. So, we will iterate over all the running process and for each process whose name contains the given string, we will keep it’s info in a list i.e.

import psutil

def findProcessIdByName(processName):
    '''
    Get a list of all the PIDs of a all the running process whose name contains
    the given string processName
    '''

    listOfProcessObjects = []

    #Iterate over the all the running process
    for proc in psutil.process_iter():
       try:
           pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
           # Check if process name contains the given name string.
           if processName.lower() in pinfo['name'].lower() :
               listOfProcessObjects.append(pinfo)
       except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :
           pass

    return listOfProcessObjects;

Let’s call this function to get the PIDs of all the running chrome.exe process

# Find PIDs od all the running instances of process that contains 'chrome' in it's name
listOfProcessIds = findProcessIdByName('chrome')

if len(listOfProcessIds) > 0:
   print('Process Exists | PID and other details are')
   for elem in listOfProcessIds:
       processID = elem['pid']
       processName = elem['name']
       processCreationTime =  time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time']))
       print((processID ,processName,processCreationTime ))
else :
   print('No Running Process found with given text')

Contents of the list will be,

(2604, 'chrome.exe', '2018-11-10 19:12:13')
(4276, 'chrome.exe', '2018-11-10 19:12:14')
(9136, 'chrome.exe', '2018-11-10 19:12:14')
(9616, 'chrome.exe', '2018-11-10 19:43:41')
(12904, 'chrome.exe', '2018-11-10 19:12:13')
(13476, 'chrome.exe', '2018-11-10 20:03:04')
(15520, 'chrome.exe', '2018-11-10 20:02:22')

We can do the same in a single line using list comprehension i.e.

# Find PIDs od all the running instances of process that contains 'chrome' in it's name
procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ]

procObjList is a list of Process class objects. Let’s iterate over it and print them i.e.

for elem in procObjList:
   print (elem)

Output will be,

psutil.Process(pid=2604, name='chrome.exe', started='19:12:13')
psutil.Process(pid=4276, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9136, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9616, name='chrome.exe', started='19:43:41')
psutil.Process(pid=12904, name='chrome.exe', started='19:12:13')
psutil.Process(pid=13476, name='chrome.exe', started='20:03:04')
psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')

Complete example is as follows,

import psutil
import time

def checkIfProcessRunning(processName):
    '''
    Check if there is any running process that contains the given name processName.
    '''
    #Iterate over the all the running process
    for proc in psutil.process_iter():
        try:
            # Check if process name contains the given name string.
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;

def findProcessIdByName(processName):
    '''
    Get a list of all the PIDs of a all the running process whose name contains
    the given string processName
    '''

    listOfProcessObjects = []

    #Iterate over the all the running process
    for proc in psutil.process_iter():
       try:
           pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
           # Check if process name contains the given name string.
           if processName.lower() in pinfo['name'].lower() :
               listOfProcessObjects.append(pinfo)
       except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :
           pass

    return listOfProcessObjects;

def main():

    print("*** Check if a process is running or not ***")

    # Check if any chrome process was running or not.
    if checkIfProcessRunning('chrome'):
        print('Yes a chrome process was running')
    else:
        print('No chrome process was running')



    print("*** Find PIDs of a running process by Name ***")

    # Find PIDs od all the running instances of process that contains 'chrome' in it's name
    listOfProcessIds = findProcessIdByName('chrome')

    if len(listOfProcessIds) > 0:
       print('Process Exists | PID and other details are')
       for elem in listOfProcessIds:
           processID = elem['pid']
           processName = elem['name']
           processCreationTime =  time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time']))
           print((processID ,processName,processCreationTime ))
    else :
       print('No Running Process found with given text')


    print('** Find running process by name using List comprehension **')

    # Find PIDs od all the running instances of process that contains 'chrome' in it's name
    procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ]

    for elem in procObjList:
       print (elem)


if __name__ == '__main__':
   main()

Output:

*** Check if a process is running or not ***
Yes a chrome process was running
*** Find PIDs of a running process by Name ***
Process Exists | PID and other details are
(2604, 'chrome.exe', '2018-11-10 19:12:13')
(4276, 'chrome.exe', '2018-11-10 19:12:14')
(9136, 'chrome.exe', '2018-11-10 19:12:14')
(9616, 'chrome.exe', '2018-11-10 19:43:41')
(12904, 'chrome.exe', '2018-11-10 19:12:13')
(13476, 'chrome.exe', '2018-11-10 20:03:04')
(15520, 'chrome.exe', '2018-11-10 20:02:22')
** Find running process by name using List comprehension **
psutil.Process(pid=2604, name='chrome.exe', started='19:12:13')
psutil.Process(pid=4276, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9136, name='chrome.exe', started='19:12:14')
psutil.Process(pid=9616, name='chrome.exe', started='19:43:41')
psutil.Process(pid=12904, name='chrome.exe', started='19:12:13')
psutil.Process(pid=13476, name='chrome.exe', started='20:03:04')
psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')

Понравилась статья? Поделить с друзьями:
  • Скорость преследования как найти
  • Как найти фамилию в списке ворд
  • Как найти семена конопляные
  • Как найти где установлен антивирус
  • Как правильно составить тех план дома