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

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

    This will work for Linux, for example if you want to check if banshee is running... (banshee is a music player)

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

提交回复
热议问题