简体   繁体   English

尝试查找进程是否在Python中仍然存在

[英]Trying to find if a process is alive in Python

I'm using psutil in order to know when a process is running. 我使用psutil来了解进程何时运行。

So far I have this code: 到目前为止,我有以下代码:

PROCESS_NAME = 'python.exe'
for p in psutil.process_iter():
  if p.name == PROCESS_NAME:
    print("It's alive!")
    break

However, it doesn't seem to work. 但是,它似乎不起作用。

I've looked around on google and here but every post suggests that the code above would be correct. 我在google和这里四处查看,但每篇文章都表明上面的代码是正确的。

Unless I'm clearly misunderstanding how process_iter() works.... 除非我明显误会了process_iter()的工作原理。

Bad Python Syntax: 错误的Python语法:

This line is wrong: 这行是错误的:

if p.name == "PROCESS_NAME":    # BAD

It looks for a process whose name is, literally, «PROCESS_NAME». 它会寻找名称为“ PROCESS_NAME»的进程。 Instead, you want to look for a process whose name is the same as the name referred to by the variable PROCESS_NAME, like so: 相反,您要查找名称与变量PROCESS_NAME引用的名称相同的进程,如下所示:

if p.name == PROCESS_NAME:      # GOOD

The right-hand-side of the first line is a string literal. 第一行的右侧是字符串文字。 The right-hand-side of the second is the name of a variable. 第二个的右侧是变量的名称。

Of course, if you are always going to look for the same name, you can put that name in a string literal: 当然,如果您总是要寻找相同的名称,则可以将该名称放入字符串文字中:

if p.name == "python.exe":     # ALSO GOOD

New PSUTIL API: 新的PSUTIL API:

Between version 1.2.1 and version 2 of psutil , they changed the api. psutil 1.2.1版和2版之间,他们更改了api。 In version 1, p.name is the name of the process. 在版本1中, p.name是进程的名称。 In version 2, p.name is a function which returns a string which is the name of the process. 在版本2中, p.name是一个函数,它返回一个字符串,该字符串是进程的名称。

So, try this: 因此,请尝试以下操作:

if p.name() == PROCESS_NAME:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM