首页 / 知识

如何在Linux上使用Python检查进程是否仍在运行?

2023-04-13 20:12:00

如何在Linux上使用Python检查进程是否仍在运行?

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

本问题已经有最佳答案,请猛点这里访问。

我发现的唯一好方法是:

1
2
3
4
5
6
7
8
import sys
import os

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

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


毕竟,Mark的答案就是解决之道,这就是/ proc文件系统在那里的原因。对于一些复制/粘贴的东西:

1
2
3
4
5
 >>> import os.path
 >>> os.path.exists("/proc/0")
 False
 >>> os.path.exists("/proc/12")
 True

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


它可以在任何POSIX系统上运行(尽管正如其他人所建议的那样,查看/proc文件系统,如果您知道它将存在的话,会更容易)。

但是:如果您没有权限发信号通知os.kill,则它也可能会失败。您将需要执行以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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"

这是为我解决的解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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!")

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


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

是的,它可以在任何Linux发行版上使用。注意/ proc在基于Unix的系统上不容易使用(FreeBSD,OSX)。


我用它来获取进程,以及指定名称的进程数

1
2
3
4
5
6
7
8
import os

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

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

在我看来,基于PID的解决方案太脆弱了。如果您要检查状态的进程已终止,则其PID可被新进程重用。因此,IMO ShaChris23 Python + Linux新手为该问题提供了最佳解决方案。即使只有通过该命令的字符串可以唯一识别所涉及的进程,或者您确定一次仅运行一个进程,该进程也才有效。


我在上述版本中遇到了问题(例如,该函数还发现了字符串的一部分,诸如此类...)
所以我写了我自己的马克西姆·科兹连科的修改版:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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("\
"
):
      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

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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("\
"
):
        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


进程检查运行方法

最新内容

相关内容

热门文章

推荐文章

标签云

猜你喜欢