检查进程是否在Python中运行(在Linux / Unix中)[重复]

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

This question already has an answer here:

这个问题在这里已有答案:

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.

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

11 个解决方案

#1


41  

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.

如果进程存在,则应该成功(并且不执行任何操作),或者如果进程不存在则抛出异常(可以捕获)。

#2


11  

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

我认为最简单的答案(albiet可能不太理想),就是改变你的想法

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”。

#3


9  

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.

这有点像kludge,但在* 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.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.

编辑:请注意,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,请告诉我们,因为在这种情况下,这些解决方案都不可接受。

#4


6  

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

您可以检查文件夹/ p​​roc / [process_id]是否存在。

 >>> 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?

请参阅此SO:如果进程仍在运行,如何使用Python检查Linux?

#5


5  

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更容易使用,仅用于查找正在运行的进程。

#6


4  

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 $3 }'" ).read().strip().split( '\n' ) ) > 1:
        raise SystemExit(0)
 except Exception, e:
        raise e

#7


3  

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.

如果该进程属于同一用户的检查过程,您可以尝试杀死它。如果您使用信号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的方法。

#8


2  

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

#9


2  

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.

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

#10


0  

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'

#11


-2  

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 True then this is actually running !!

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

#1


41  

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.

如果进程存在,则应该成功(并且不执行任何操作),或者如果进程不存在则抛出异常(可以捕获)。

#2


11  

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

我认为最简单的答案(albiet可能不太理想),就是改变你的想法

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”。

#3


9  

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.

这有点像kludge,但在* 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.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.

编辑:请注意,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,请告诉我们,因为在这种情况下,这些解决方案都不可接受。

#4


6  

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

您可以检查文件夹/ p​​roc / [process_id]是否存在。

 >>> 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?

请参阅此SO:如果进程仍在运行,如何使用Python检查Linux?

#5


5  

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更容易使用,仅用于查找正在运行的进程。

#6


4  

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 $3 }'" ).read().strip().split( '\n' ) ) > 1:
        raise SystemExit(0)
 except Exception, e:
        raise e

#7


3  

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.

如果该进程属于同一用户的检查过程,您可以尝试杀死它。如果您使用信号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的方法。

#8


2  

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

#9


2  

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.

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

#10


0  

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'

#11


-2  

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 True then this is actually running !!

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