Monitor Process in Python?

前端 未结 3 845
遥遥无期
遥遥无期 2020-12-17 03:35

I think this is a pretty basic question, but here it is anyway.

I need to write a python script that checks to make sure a process, say notepad.exe, is running. If t

3条回答
  •  醉酒成梦
    2020-12-17 03:37

    The process creation functions of the os module are apparently deprecated in Python 2.6 and later, with the subprocess module being the module of choice now, so...

    if 'notepad.exe' not in subprocess.Popen('tasklist', stdout=subprocess.PIPE).communicate()[0]:
        subprocess.Popen('notepad.exe')
    

    Note that in Python 3, the string being checked will need to be a bytes object, so it'd be

    if b'notepad.exe' not in [blah]:
        subprocess.Popen('notepad.exe')
    

    (The name of the file/process to start does not need to be a bytes object.)

提交回复
热议问题