Monitor Process in Python?

怎甘沉沦 提交于 2019-11-30 07:39:44

问题


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 the process is running, do nothing. If it is not, start it. How would this be done.

I am using Python 2.6 on Windows XP


回答1:


There are a couple of options,

1: the more crude but obvious would be to do some text processing against:

os.popen('tasklist').read()

2: A more involved option would be to use pywin32 and research the win32 APIs to figure out what processes are running.

3: WMI (I found this just now), and here is a vbscript example of how to query the machine for processes through WMI.




回答2:


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




回答3:


Python library for Linux process management



来源:https://stackoverflow.com/questions/3215262/monitor-process-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!