简体   繁体   English

如果在大量搜索之前打开,则找不到进程

[英]Process is not found if opened until a lot of searches

import psutil

name = "notepad.exe"

for proc in psutil.process_iter():
    if proc.name().lower() == name.lower():
        print("found")
    elif proc.name().lower() != name.lower():
        print("not found")

output:输出:

not found
not found
not found
found
not found
not found

"notepad.exe" was open from the start and until the end of the script. “notepad.exe”从开始到脚本结束都是打开的。

It seems to me you could use any() rather than using a for loop:在我看来,您可以使用any()而不是使用for循环:

if any(proc.name().lower() == name.lower() for proc in psutil.process_iter()):
    print("found")
else
    print("not found")

psutil.process_iter() gives you an generator of all running processes. psutil.process_iter() 为您提供了所有正在运行的进程的生成器。

Hi whytfnotworking .为什么不工作 Your code behaves as it should.您的代码按应有的方式运行。 Remember than, as the psutil.process_iter documentation says, it will iterates over all the running processes.请记住,正如 psutil.process_iter 文档所说,它将遍历所有正在运行的进程。 In a typical machine you can have hundreds of them (I have at least 238 running right now).在一台典型的机器中,您可以拥有数百个(我现在至少有 238 个在运行)。 So, if you want to just get the one your'e interested in, you could simply remove the last two lines:所以,如果你只想得到你感兴趣的,你可以简单地删除最后两行:

import psutil

name = "notepad.exe"

for proc in psutil.process_iter():
    if proc.name().lower() == name.lower():
        print("found")
        break #This is for stop the iteration once found

Edit:编辑:

If you want to see when it's not found, then you could make use of an powerful, yet non popular feature of python loops: the else (yes, else in loops... python is amazing).如果您想查看何时找不到它,那么您可以利用 python 循环的一个强大但不流行的特性: else (是的,else in loops ...... python 很棒)。

import psutil

name = "notepad.exe"

for proc in psutil.process_iter():
    if proc.name().lower() == name.lower():
        print("found")
        break #This is for stop the iteration once found
else:
    print("not found") #It will get executed when the loop ends normally (not breaked)

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

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