如何在Python中检查是否存在具有给定pid的进程?

2020/11/30 18:32 · python ·  · 0评论

有没有办法检查pid是否对应有效的进程?我从其他来源获得pid os.getpid(),我需要检查计算机上是否不存在具有该pid的进程。

我需要它在Unix和Windows中可用。我也在检查PID是否未使用。

如果pid没有运行,则向pid发送信号0将引发OSError异常,否则不执行任何操作。

import os

def check_pid(pid):        
    """ Check For the existence of a unix pid. """
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    else:
        return True

看一下psutil模块:

psutil(Python系统和进程实用程序)是一个跨平台的库,用于检索有关Python中正在运行的进程系统利用率(CPU,内存,磁盘,网络)的信息。[...]它目前支持32位64位体系结构的LinuxWindowsOSXFreeBSDSun SolarisPython版本从2.6到3.4(Python 2.4和2.5的用户可以使用2.1.3版本) 。PyPy也可以工作。

它具有一个称为的函数pid_exists(),可用于检查具有给定pid的进程是否存在。

这是一个例子:

import psutil
pid = 12345
if psutil.pid_exists(pid):
    print("a process with pid %d exists" % pid)
else:
    print("a process with pid %d does not exist" % pid)

以供参考:

mluebke代码不是100%正确;kill()还可以引发EPERM(访问被拒绝),在这种情况下,这显然意味着一个进程存在。这应该工作:

(根据Jason R. Coombs评论编辑)

import errno
import os

def pid_exists(pid):
    """Check whether pid exists in the current process table.
    UNIX only.
    """
    if pid < 0:
        return False
    if pid == 0:
        # According to "man 2 kill" PID 0 refers to every process
        # in the process group of the calling process.
        # On certain systems 0 is a valid PID but we have no way
        # to know that in a portable fashion.
        raise ValueError('invalid PID 0')
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH)
            raise
    else:
        return True

除非使用pywin32,ctypes或C扩展模块,否则您无法在Windows上执行此操作。如果可以从外部库中获取依赖,则可以使用psutil

>>> import psutil
>>> psutil.pid_exists(2353)
True

仅当所讨论的进程归运行测试的用户所有时,涉及向进程发送“信号0”的答案才有效否则,即使pid存在于系统中,您也将OSError由于权限而获得权限

为了绕过此限制,您可以检查是否/proc/<pid>存在:

import os

def is_running(pid):
    if os.path.isdir('/proc/{}'.format(pid)):
        return True
    return False

显然,这仅适用于基于linux的系统。

在Python 3.3+中,可以使用异常名称代替errno常量。Posix版本

import os

def pid_exists(pid): 
    if pid < 0: return False #NOTE: pid == 0 returns True
    try:
        os.kill(pid, 0) 
    except ProcessLookupError: # errno.ESRCH
        return False # No such process
    except PermissionError: # errno.EPERM
        return True # Operation not permitted (i.e., process exists)
    else:
        return True # no error, we can send a signal to the process

在此处查找特定于Windows的方式,以获取运行进程及其ID的完整列表。就像

from win32com.client import GetObject
def get_proclist():
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    return [process.Properties_('ProcessID').Value for process in processes]

然后,您可以根据此列表验证pid。我对性能成本一无所知,因此,如果您要经常进行pid验证,则最好检查一下。

对于* NIx,只需使用mluebke的解决方案。

在ntrrgc的基础上,我增强了Windows版本,因此它检查进程退出代码并检查权限:

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if os.name == 'posix':
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
    else:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        HANDLE = ctypes.c_void_p
        DWORD = ctypes.c_ulong
        LPDWORD = ctypes.POINTER(DWORD)
        class ExitCodeProcess(ctypes.Structure):
            _fields_ = [ ('hProcess', HANDLE),
                ('lpExitCode', LPDWORD)]

        SYNCHRONIZE = 0x100000
        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if not process:
            return False

        ec = ExitCodeProcess()
        out = kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
        if not out:
            err = kernel32.GetLastError()
            if kernel32.GetLastError() == 5:
                # Access is denied.
                logging.warning("Access is denied to get pid info.")
            kernel32.CloseHandle(process)
            return False
        elif bool(ec.lpExitCode):
            # print ec.lpExitCode.contents
            # There is an exist code, it quit
            kernel32.CloseHandle(process)
            return False
        # No exit code, it's running.
        kernel32.CloseHandle(process)
        return True

结合GiampaoloRodolà对POSIX的回答我对Windows的回答,我得到了:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False

在Windows中,您可以通过以下方式进行操作:

import ctypes
PROCESS_QUERY_INFROMATION = 0x1000
def checkPid(pid):
    processHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0,pid)
    if processHandle == 0:
        return False
    else:
        ctypes.windll.kernel32.CloseHandle(processHandle)
    return True

首先,在这段代码中,您尝试获取给定pid的进程的句柄。如果该句柄有效,则关闭该句柄以进行处理并返回True;否则,返回true。否则,您返回False。OpenProcess文档:https : //msdn.microsoft.com/zh-cn/library/windows/desktop/ms684320%28v=vs.85%29.aspx

例如,如果您要检查banshee是否正在运行,该功能将在Linux上运行(banshee是音乐播放器)

import subprocess

def running_process(process):
    "check if process is running. < process > is the name of the process."

    proc = subprocess.Popen(["if pgrep " + process + " >/dev/null 2>&1; then echo 'True'; else echo 'False'; fi"], stdout=subprocess.PIPE, shell=True)

    (Process_Existance, err) = proc.communicate()
    return Process_Existance

# use the function
print running_process("banshee")

以下代码可在Linux和Windows上运行,而不取决于外部模块

import os
import subprocess
import platform
import re

def pid_alive(pid:int):
    """ Check For whether a pid is alive """


    system = platform.uname().system
    if re.search('Linux', system, re.IGNORECASE):
        try:
            os.kill(pid, 0)
        except OSError:
            return False
        else:
            return True
    elif re.search('Windows', system, re.IGNORECASE):
        out = subprocess.check_output(["tasklist","/fi",f"PID eq {pid}"]).strip()
        # b'INFO: No tasks are running which match the specified criteria.'

        if re.search(b'No tasks', out, re.IGNORECASE):
            return False
        else:
            return True
    else:
        raise RuntimeError(f"unsupported system={system}")

如果需要,可以轻松进行增强

  1. 其他平台
  2. 其他语言

我发现此解决方案似乎在Windows和Linux中都可以很好地工作。我用psutil检查。

import psutil
import subprocess
import os
p = subprocess.Popen(['python', self.evaluation_script],stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 

pid = p.pid

def __check_process_running__(self,p):
    if p is not None:
        poll = p.poll()
        if poll == None:
            return True
    return False
    
def __check_PID_running__(self,pid):
    """
        Checks if a pid is still running (UNIX works, windows we'll see)
        Inputs:
            pid - process id
        returns:
            True if running, False if not
    """
    if (platform.system() == 'Linux'):
        try:
            os.kill(pid, 0)
            if pid<0:               # In case code terminates
                return False
        except OSError:
            return False 
        else:
            return True
    elif (platform.system() == 'Windows'):
        return pid in (p.pid for p in psutil.process_iter())

我想将PID用于获得它的任何目的并优雅地处理错误。否则,这将是经典竞赛(当您检查PID有效时,PID可能有效,但稍后消失)

本文地址:http://python.askforanswer.com/ruhezaipythonzhongjianchashifoucunzaijuyougeidingpiddejincheng.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!