检查进程是否在 Linux 上使用 Python 运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7647167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:29:10  来源:igfitidea点击:

Check if a process is running using Python on Linux

pythonlinux

提问by shash

I am trying to find if the process is running 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.

我试图根据进程 ID 查找进程是否正在运行。代码如下基于论坛上的一篇帖子。我不能考虑进程名称,因为有多个进程使用相同的名称运行。

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.

它总是返回 true,因为它可以在输出字符串中找到进程 ID。

Any suggestions? Thanks for any help.

有什么建议?谢谢你的帮助。

回答by user9876

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.

如果进程存在,则应该成功(并且什么都不做),或者如果进程不存在则抛出异常(您可以捕获)。

回答by viraptor

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

如果该进程与检查进程属于同一用户,您可以尝试kill一下。如果您使用信号 0,kill 将不会发送任何内容,但仍允许您判断该进程是否可用。

From kill(2):

来自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.

如果 sig 为 0,则不发送信号,但仍进行错误检查;这可用于检查进程 ID 或进程组 ID 是否存在。

This should propagate appropriately to python's methods.

这应该适当地传播到 python 的方法。

回答by rplnt

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.

如果您不介意使用外部模块,我建议您使用psutil。它是跨平台的,并且比仅为了查找正在运行的进程而生成子 shell 更易于使用。

回答by Cody Hess

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.

这有点麻烦,但在 *nix 上,您可以使用os.getpgid(pid)os.kill(pid, sig)来测试进程 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.killworks on Windows (as of Python 2.7), while os.getpgidwon't. Butthe 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.

编辑:请注意,它os.kill适用于 Windows(从 Python 2.7 开始),os.getpgid而不适用于. 但是Windows 版本调用TerminateProcess(),这将“无条件地导致进程退出”,所以我预测如果它确实存在,它不会安全地返回您想要的信息而不实际杀死进程。

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

如果您使用的是 Windows,请告诉我们,因为在这种情况下这些解决方案都不可接受。

回答by dicato

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.

这将忽略包含您尝试查找的进程的 PID 的 grep 搜索的进程列表。

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

然而,似乎 user9876 的答案更像是“pythonic”。

回答by Yugal Jindle

You have to find it twice..

你必须找到它两次..

Like this :

像这样 :

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

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

If this returns Truethen this is actually running !!

如果返回,True则这实际上正在运行!

回答by Carlos Gomes

On Windows another option is to use tasklist.exe:

在 Windows 上,另一个选择是使用 tasklist.exe:

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

语法: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

回答by Wade Hatler

On Windows, you can use WMI.

在 Windows 上,您可以使用 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.

您也可以使用其他过滤器。例如,我更有可能只想知道进程是否按名称运行并采取行动。例如,如果 DbgView 未运行,则启动它。

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.

您还可以迭代并做其他有趣的事情。完整的字段列表在这里

回答by sadmicrowave

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:

我知道这是旧的,但我已经使用过它并且它似乎有效;您可以进行快速调整以将进程名称转换为进程 ID:

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

回答by Diogo Leal

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'