How to check if a process is still running using Python on Linux?

96,259

Solution 1

Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable:

 >>> import os.path
 >>> os.path.exists("/proc/0")
 False
 >>> os.path.exists("/proc/12")
 True

Solution 2

on linux, you can look in the directory /proc/$PID to get information about that process. In fact, if the directory exists, the process is running.

Solution 3

It should work on any POSIX system (although looking at the /proc filesystem, as others have suggested, is easier if you know it's going to be there).

However: os.kill may also fail if you don't have permission to signal the process. You would need to do something like:

import sys
import os
import errno

try:
    os.kill(int(sys.argv[1]), 0)
except OSError, err:
    if err.errno == errno.ESRCH:
        print "Not running"
    elif err.errno == errno.EPERM:
        print "No permission to signal this process!"
    else:
        print "Unknown error"
else:
    print "Running"

Solution 4

I use this to get the processes, and the count of the process of the specified name

import os

processname = 'somprocessname'
tmp = os.popen("ps -Af").read()
proccount = tmp.count(processname)

if proccount > 0:
    print(proccount, ' processes running of ', processname, 'type')

Solution 5

Here's the solution that solved it for me:

import os
import subprocess
import re

def findThisProcess( process_name ):
  ps     = subprocess.Popen("ps -eaf | grep "+process_name, shell=True, stdout=subprocess.PIPE)
  output = ps.stdout.read()
  ps.stdout.close()
  ps.wait()

  return output

# This is the function you can use  
def isThisRunning( process_name ):
  output = findThisProcess( process_name )

  if re.search('path/of/process'+process_name, output) is None:
    return False
  else:
    return True

# Example of how to use
if isThisRunning('some_process') == False:
  print("Not running")
else:
  print("Running!")

I'm a Python + Linux newbie, so this might not be optimal. It solved my problem, and hopefully will help other people as well.

Share:
96,259
peller
Author by

peller

Updated on September 19, 2020

Comments

  • peller
    peller over 3 years

    The only nice way I've found is:

    import sys
    import os
    
    try:
            os.kill(int(sys.argv[1]), 0)
            print "Running"
    except:
            print "Not running"
    

    (Source)
    But is this reliable? Does it work with every process and every distribution?

  • Phyo Arkar Lwin
    Phyo Arkar Lwin about 13 years
    This will fail so much when the process have multiple childs.
  • Vicky T
    Vicky T over 12 years
    If you are running some versions of Linux, the number of unique PIDs is 32768 or whatever is in /proc/sys/kernel/pid_max which makes a reused PID unlikely for short running programs.
  • 8znr
    8znr over 3 years
    Nice, just be aware that this counts defunct processes too
  • user7082181
    user7082181 about 3 years
    how are you supposed to figure the number ? I dont get it
  • John Smith
    John Smith over 2 years
    This solution will give wrong results if one tries to search a process only by name, without full path 'path/of/process', because "ps -eaf | grep" will also include the grep process itself, thus always providing non-empty output.