How to check if there exists a process with a given pid in Python?

后端 未结 13 1222
名媛妹妹
名媛妹妹 2020-11-27 11:48

Is there a way to check to see if a pid corresponds to a valid process? I\'m getting a pid from a different source other than from os.getpid() and I need to che

13条回答
  •  温柔的废话
    2020-11-27 12:04

    Combining Giampaolo Rodolà's answer for POSIX and mine for Windows I got this:

    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
    

提交回复
热议问题