开发者

Check if a process is running using Python on Linux [duplicate]

This question already has answers here: How to check if there exists a process with a given pid in Python? (15 answers) Closed 8 years ago.

I am trying to find if the process is run开发者_StackOverflow中文版ning based on process id. The code is as follows based on one of the post on the forum. I cannot consider process name as there are more than one process running with the same name.

def findProcess( processId ):
    ps= subprocess.Popen("ps -ef | grep "+processId, shell=True, stdout=subprocess.PIPE)
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()
    return output
def isProcessRunning( processId):
    output = findProcess( processId )
    if re.search(processId, output) is None:
        return true
    else:
        return False

Output :

1111 72312 72311   0   0:00.00 ttys000    0:00.00 /bin/sh -c ps -ef | grep 71676
1111 72314 72312   0   0:00.00 ttys000    0:00.00 grep 71676

It always return true as it can find the process id in the output string.

Any suggestions? Thanks for any help.


Try:

os.kill(pid, 0)

Should succeed (and do nothing) if the process exists, or throw an exception (that you can catch) if the process doesn't exist.


The simplest answer in my opinion (albiet maybe not ideal), would be to change your

ps -ef | grep <pid>

To:

ps -ef | grep <pid> | grep -v grep

This will ignore the process listing for the grep search containing the PID of the process you are trying to find.

It seems user9876's answer is far more "pythonic" however.


You could check if the folder /proc/[process_id] exists.

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

See this SO: How do you check in Linux with Python if a process is still running?


This is a bit of a kludge, but on *nix you can use os.getpgid(pid) or os.kill(pid, sig) to test the existence of the process ID.

import os

def is_process_running(process_id):
    try:
        os.kill(process_id, 0)
        return True
    except OSError:
        return False

EDIT: Note that os.kill works on Windows (as of Python 2.7), while os.getpgid won't. But the Windows version calls TerminateProcess(), which will "unconditionally cause a process to exit", so I predict that it won't safely return the information you want without actually killing the process if it does exist.

If you're using Windows, please let us know, because none of these solutions are acceptable in that scenario.


I know this is old, but I've used this and it seems to work; you can do a quick adaptation to convert from process name to process id:

 try:
    if len( os.popen( "ps -aef | grep -i 'myprocess' | grep -v 'grep' | awk '{ print $3 }'" ).read().strip().split( '\n' ) ) > 1:
        raise SystemExit(0)
 except Exception, e:
        raise e


If you don't mind using external module I'd suggest psutil. It is cross-platform and easier to use than spawning subshell only for purpose of finding a running process.


If that process belongs to the same user the checking process, you can just try to kill it. If you use signal 0, kill will not send anything but still allow you to tell if the process is available.

From kill(2):

If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID.

This should propagate appropriately to python's methods.


On Windows another option is to use tasklist.exe:

Syntax: tasklist.exe /NH /FI "PID eq processID"

def IsProcessRunning( processId ):
    ps= subprocess.Popen(r'tasklist.exe /NH /FI "PID eq %d"' % (processId), shell=True, stdout=subprocess.PIPE)
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()
    if processId in output:
       return True
    return False


On Windows, you can use WMI.

from win32com.client import GetObject
GetObject('winmgmts:').ExecQuery("Select * from Win32_Process where ProcessId = " + str(pid)).count

You can also use other filters. For example, I'm much more likely to just want to tell if a process is running by name and take action. For example, if DbgView isn't running, then start it.

if not GetObject('winmgmts:').ExecQuery("Select * from Win32_Process where Name = 'dbgview.exe'").count:
    subprocess.Popen(r"C:\U\dbgview.exe", shell=False)

You can also iterate and do other interesting things. Complete list of fields is here.


Recently I had to list the running processes and did so:

def check_process(process):
  import re
  import subprocess

  returnprocess = False
  s = subprocess.Popen(["ps", "ax"],stdout=subprocess.PIPE)
  for x in s.stdout:
      if re.search(process, x):
          returnprocess = True

  if returnprocess == False:        
      print 'no process executing'
  if returnprocess == True:
      print 'process executing'


You have to find it twice..

Like this :

ps -ef | grep 71676 | sed 's/71676//' | grep 71676

If this returns True then this is actually running !!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜