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

后端 未结 13 1166
名媛妹妹
名媛妹妹 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:17

    In Python 3.3+, you could use exception names instead of errno constants. Posix version:

    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
    
    0 讨论(0)
提交回复
热议问题