如果一个进程仍在运行,如何使用Python来检入Linux ?(复制)

时间:2022-07-03 16:24:31

This question already has an answer here:

这个问题已经有了答案:

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?

(来源)但这可靠吗?它是否适用于每个流程和每个发行版?

9 个解决方案

#1


50  

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:

Mark的答案是,毕竟,这就是/proc文件系统存在的原因。对于更多的拷贝/可粘贴的东西:

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

#2


27  

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.

在linux上,您可以在目录/proc/$PID中查找,以获得关于该进程的信息。实际上,如果该目录存在,则进程正在运行。

#3


11  

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).

它应该适用于任何POSIX系统(尽管正如其他人所建议的,查看/proc文件系统更容易,如果您知道它将在那里)。

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

然而:操作系统。如果您没有授权通知进程,则kill也可能失败。你需要做一些类似的事情:

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"

#4


6  

// But is this reliable? Does it work with every process and every distribution?

//但这可靠吗?它是否适用于每个流程和每个发行版?

Yes, it should work on any Linux distribution. Be aware that /proc is not easily available on Unix based systems, though (FreeBSD, OSX).

是的,它应该适用于任何Linux发行版。请注意,在基于Unix的系统上(FreeBSD, OSX)并不容易使用proc。

#5


6  

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.

我是Python + Linux新手,所以这可能不是最佳选择。它解决了我的问题,也希望能帮助其他人。

#6


5  

Seems to me a PID-based solution is too vulnerable. If the process you're trying to check the status of has been terminated, its PID can be reused by a new process. So, IMO ShaChris23 the Python + Linux newbie gave the best solution to the problem. Even it only works if the process in question is uniquely identifiable by its command string, or you are sure there would be only one running at a time.

在我看来,基于pid的解决方案过于脆弱。如果要检查的进程已经终止,则可以使用新进程重用它的PID。所以,IMO ShaChris23 Python + Linux新手给出了最好的解决方案。甚至只有当所讨论的进程被它的命令字符串惟一地标识时,或者您确定一次只运行一个进程时,它才会工作。

#7


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')

#8


3  

i had problems with the versions above (for example the function found also part of the string and such things...) so i wrote my own, modified version of Maksym Kozlenko's:

我对上面的版本有问题(例如,函数也被发现是字符串的一部分等等),所以我写了我自己的修改版的Maksym Kozlenko:

#proc    -> name/id of the process
#id = 1  -> search for pid
#id = 0  -> search for name (default)

def process_exists(proc, id = 0):
   ps = subprocess.Popen("ps -A", shell=True, stdout=subprocess.PIPE)
   ps_pid = ps.pid
   output = ps.stdout.read()
   ps.stdout.close()
   ps.wait()

   for line in output.split("\n"):
      if line != "" and line != None:
        fields = line.split()
        pid = fields[0]
        pname = fields[3]

        if(id == 0):
            if(pname == proc):
                return True
        else:
            if(pid == proc):
                return True
return False

I think it's more reliable, easier to read and you have the option to check for process ids or names.

我认为它更可靠、更容易阅读,您可以选择检查进程id或名称。

#9


0  

Sligtly modified version of ShaChris23 script. Checks if proc_name value is found within process args string (for example Python script executed with python ):

ShaChris23脚本的修改版本。检查在进程args字符串中是否找到proc_name值(例如用Python执行的Python脚本):

def process_exists(proc_name):
    ps = subprocess.Popen("ps ax -o pid= -o args= ", shell=True, stdout=subprocess.PIPE)
    ps_pid = ps.pid
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()

    for line in output.split("\n"):
        res = re.findall("(\d+) (.*)", line)
        if res:
            pid = int(res[0][0])
            if proc_name in res[0][1] and pid != os.getpid() and pid != ps_pid:
                return True
    return False

#1


50  

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:

Mark的答案是,毕竟,这就是/proc文件系统存在的原因。对于更多的拷贝/可粘贴的东西:

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

#2


27  

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.

在linux上,您可以在目录/proc/$PID中查找,以获得关于该进程的信息。实际上,如果该目录存在,则进程正在运行。

#3


11  

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).

它应该适用于任何POSIX系统(尽管正如其他人所建议的,查看/proc文件系统更容易,如果您知道它将在那里)。

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

然而:操作系统。如果您没有授权通知进程,则kill也可能失败。你需要做一些类似的事情:

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"

#4


6  

// But is this reliable? Does it work with every process and every distribution?

//但这可靠吗?它是否适用于每个流程和每个发行版?

Yes, it should work on any Linux distribution. Be aware that /proc is not easily available on Unix based systems, though (FreeBSD, OSX).

是的,它应该适用于任何Linux发行版。请注意,在基于Unix的系统上(FreeBSD, OSX)并不容易使用proc。

#5


6  

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.

我是Python + Linux新手,所以这可能不是最佳选择。它解决了我的问题,也希望能帮助其他人。

#6


5  

Seems to me a PID-based solution is too vulnerable. If the process you're trying to check the status of has been terminated, its PID can be reused by a new process. So, IMO ShaChris23 the Python + Linux newbie gave the best solution to the problem. Even it only works if the process in question is uniquely identifiable by its command string, or you are sure there would be only one running at a time.

在我看来,基于pid的解决方案过于脆弱。如果要检查的进程已经终止,则可以使用新进程重用它的PID。所以,IMO ShaChris23 Python + Linux新手给出了最好的解决方案。甚至只有当所讨论的进程被它的命令字符串惟一地标识时,或者您确定一次只运行一个进程时,它才会工作。

#7


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')

#8


3  

i had problems with the versions above (for example the function found also part of the string and such things...) so i wrote my own, modified version of Maksym Kozlenko's:

我对上面的版本有问题(例如,函数也被发现是字符串的一部分等等),所以我写了我自己的修改版的Maksym Kozlenko:

#proc    -> name/id of the process
#id = 1  -> search for pid
#id = 0  -> search for name (default)

def process_exists(proc, id = 0):
   ps = subprocess.Popen("ps -A", shell=True, stdout=subprocess.PIPE)
   ps_pid = ps.pid
   output = ps.stdout.read()
   ps.stdout.close()
   ps.wait()

   for line in output.split("\n"):
      if line != "" and line != None:
        fields = line.split()
        pid = fields[0]
        pname = fields[3]

        if(id == 0):
            if(pname == proc):
                return True
        else:
            if(pid == proc):
                return True
return False

I think it's more reliable, easier to read and you have the option to check for process ids or names.

我认为它更可靠、更容易阅读,您可以选择检查进程id或名称。

#9


0  

Sligtly modified version of ShaChris23 script. Checks if proc_name value is found within process args string (for example Python script executed with python ):

ShaChris23脚本的修改版本。检查在进程args字符串中是否找到proc_name值(例如用Python执行的Python脚本):

def process_exists(proc_name):
    ps = subprocess.Popen("ps ax -o pid= -o args= ", shell=True, stdout=subprocess.PIPE)
    ps_pid = ps.pid
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()

    for line in output.split("\n"):
        res = re.findall("(\d+) (.*)", line)
        if res:
            pid = int(res[0][0])
            if proc_name in res[0][1] and pid != os.getpid() and pid != ps_pid:
                return True
    return False