I have this:
def get_process():
pids = []
process = None
for i in os.listdir('/proc'):
if i.isdigit():
pids.append(i)
for pid in pids:
proc = open(os.path.join('/proc', pid, 'cmdline'), 'r').readline()
if proc == "Something":
process = pid
return process
def is_running(pid):
return os.path.exists("/proc/%s" % str(pid))
Then i do this:
process = get_process()
if process == None:
#do something
else:
#Wait until the process end
while is_running(process):
pass
I think this is not the best way to wait for the process to terminate, there must be some function wait or something, but i can't find it.
Disclaimer: The process is not a child process
import time
, then usetime.sleep(#)
:I also have that exact same function in several of my scrips to read through
/proc/#/cmdline
to check for a PID.I'm not really a Python programmer, but apparently Python does have
os.waitpid()
. That should consume less CPU time and provide a much faster response than, say, trying to kill the process at quarter-second intervals.Addendum: As Niko points out,
os.waitpid()
may not work if the process is not a child of the current process. In that case, usingos.kill(pid, 0)
may indeed be the best solution. Note that, in general, there are three likely outcomes of callingos.kill()
on a process:OSError
with theerrno
attribute set toerrno.EPERM
.OSError
with theerrno
attribute set toerrno.ESRCH
.Thus, to reliably check whether a process exists, you should do something like
Since that method would only work on linux, for linux/osx support, you could do:
Edit - Per tMc's comment about excessive processes
Referencing: How to check if there exists a process with a given pid in Python?
Wouldn't this use less resources (I havent tested), than listing on the filesystem and opening FDs to all the results?
A simple and reliable way of doing this with Python is by getting a list of PIDs with psutil, and then checking if your PID is in that list of running PIDs:
To use it, just run it in a simple while loop.
Or you could just put all that into one function...
and use like