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

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

    Have a look at the psutil module:

    psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python. [...] It currently supports Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.4 (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.

    It has a function called pid_exists() that you can use to check whether a process with the given pid exists.

    Here's an example:

    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)
    

    For reference:

    • https://pypi.python.org/pypi/psutil
    • https://github.com/giampaolo/psutil
    • http://pythonhosted.org/psutil/#psutil.pid_exists

提交回复
热议问题