How to Check If There Exists a Process with a Given Pid in Python

How to check if there exists a process with a given pid in Python?

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

Check if PID exists on Windows with Python without requiring libraries

This is solved with a little cup of WINAPI.

def pid_running(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

Check if a process is running or not on Windows?

You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. psutil is an excellent cross-platform python module cable of enumerating all the running programs on a system.

import psutil    
"someProgram" in (p.name() for p in psutil.process_iter())

Fastest way to detect if a process is running

Using pidof should be faster than pgrep

def process_up(self):
try:
call = subprocess.check_output("pidof '{}'".format(self.processName), shell=True)
return True
except subprocess.CalledProcessError:
return False

How to check if a new process started in windows?

This was what I was looking for

import wmi

c = wmi.WMI()
process_watcher = c.Win32_Process.watch_for("creation")
while True:
new_process = process_watcher()
print(new_process.Caption,process.ProcessId)

Thank you. I didnt know about WMI.

Fast way to determine if a PID exists on (Windows)?

OpenProcess could tell you w/o enumerating all. I have no idea how fast.

EDIT: note that you also need GetExitCodeProcess to verify the state of the process even if you get a handle from OpenProcess.



Related Topics



Leave a reply



Submit