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

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

    The following code works on both Linux and Windows, and not depending on external modules

    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}")
    

    It can be easily enhanced in case you need

    1. other platforms
    2. other language

提交回复
热议问题