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
Exponentials in Python: X**Y VS Math.Pow(X, Y)
Prepend a Level to a Pandas Multiindex
Importerror: No Module Named 'Django.Core.Urlresolvers'
Class Variables Is Shared Across All Instances in Python
Use Scipy.Integrate.Quad to Integrate Complex Numbers
Python Time to Age, Part 2: Timezones
Python Replace String Pattern with Output of Function
Why Isn't the Regular Expression's "Non-Capturing" Group Working
Can You List the Keyword Arguments a Function Receives
Tkinter: Mouse Drag a Window Without Borders, Eg. Overridedirect(1)
Making a Python User-Defined Class Sortable, Hashable
Transform "List of Tuples" into a Flat List or a Matrix
Concat Dataframe Reindexing Only Valid with Uniquely Valued Index Objects
How Does Python's "Super" Do the Right Thing
Error When Loading Cookies into a Python Request Session
How to Format Axis Number Format to Thousands with a Comma in Matplotlib
Pyeval_Initthreads in Python 3: How/When to Call It? (The Saga Continues Ad Nauseam)