用Python监控进程?

发布于 2024-09-08 16:48:29 字数 156 浏览 3 评论 0原文

我认为这是一个非常基本的问题,但无论如何。

我需要编写一个 python 脚本来检查以确保进程(例如 notepad.exe)正在运行。如果该进程正在运行,则不执行任何操作。如果没有,请启动它。这将如何完成。

我在 Windows XP 上使用 Python 2.6

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

樱花细雨 2024-09-15 16:48:29

os 模块的进程创建函数在 Python 2.6 及更高版本中显然已被弃用,其中 subprocess 模块现在是选择的模块,所以...

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

请注意,在 Python 3 中,被检查的字符串需要是一个 bytes 对象,所以它是

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

(要启动的文件/进程的名称不需要是字节对象。)

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

自我难过 2024-09-15 16:48:29

有几个选项,

1:更粗略但明显的是对以下内容进行一些文本处理:

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

2:更复杂的选项是使用 pywin32 并研究 win32 API 以找出正在运行的进程。

3:WMI(我刚刚发现了这个),以及这里是一个 vbscript 示例,说明如何通过 WMI 查询计算机的进程。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文