我认为这是一个非常基本的问题,但无论如何它都在这里。
我需要编写一个 python 脚本来检查以确保某个进程(比如 notepad.exe)正在运行。如果该进程正在运行,则什么也不做。如果不是,请启动它。这将如何完成。
我在 Windows XP 上使用 Python 2.6
最佳答案
os
模块的进程创建函数显然在 Python 2.6 及更高版本中已弃用,subprocess
模块现在是首选模块,所以...
if 'notepad.exe' not in subprocess.Popen('tasklist', stdout=subprocess.PIPE).communicate()[0]:
subprocess.Popen('notepad.exe')
请注意,在 Python 3 中,被检查的字符串需要是一个字节对象,所以它是
if b'notepad.exe' not in [blah]:
subprocess.Popen('notepad.exe')
(要启动的文件/进程的名称不需要是字节对象。)
关于python - 在 Python 中监控进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3215262/