当程序不是 运行 时,为什么我的访问被拒绝?
Why am I getting access denied when program is not running?
我有一段简单的代码,主要取自此 answer,并进行了一些调整:
import psutil
try:
if "firefox.exe" in (p.name() for p in psutil.process_iter()):
print('Firefox is running')
else:
print('Firefox is not running')
except Exception as e:
print(e)
如果当我 运行 这段代码时 Firefox 正在 运行ning,它会打印预期的 Firefox is running
。但是如果 Firefox 不是 运行ning,我会得到 psutil.AccessDenied (pid=9092)
而不是预期的 Firefox is not running
.
我还注意到,如果 firefox.exe
拼写错误,我会再次收到 AccessDenied
错误。我可以在 except
块中 print('Firefox is not running')
,但这似乎不太聪明。
有人知道为什么会这样吗?
因为这个 (p.name() for p in psutil.process_iter())
是一个生成器,当在用户进程中没有发现该进程时,它会尝试列出系统进程。考虑用 print('Firefox is not running by current user')
之类的警告来抑制此异常
I get psutil.AccessDenied (pid=9092)
其他可能的原因是在迭代器获得要检索的 pid 后进程终止。由于您无法确定当您的 python 进程被 OS 调度程序暂停时该进程不会消失,无知似乎是一个合法的解决方案。
UPD:aa 就是这样(产生了死进程)
https://github.com/giampaolo/psutil/blob/c3e63b4dd59f1724a7fa29371e53dfa7f46cbcd3/psutil/__init__.py#L1453-L1465
当您尝试访问进程名称(未缓存)时,它已经死了。所以我会跳过它而不是表现得像 运行.
process_iter()
允许您指定应该 returned 的属性。所以告诉它只 return 名字,然后比较它们。
if any(p.info['name'] == "firefox.exe" for p in psutil.process_iter(['name'])):
从文档中得到:
我有一段简单的代码,主要取自此 answer,并进行了一些调整:
import psutil
try:
if "firefox.exe" in (p.name() for p in psutil.process_iter()):
print('Firefox is running')
else:
print('Firefox is not running')
except Exception as e:
print(e)
如果当我 运行 这段代码时 Firefox 正在 运行ning,它会打印预期的 Firefox is running
。但是如果 Firefox 不是 运行ning,我会得到 psutil.AccessDenied (pid=9092)
而不是预期的 Firefox is not running
.
我还注意到,如果 firefox.exe
拼写错误,我会再次收到 AccessDenied
错误。我可以在 except
块中 print('Firefox is not running')
,但这似乎不太聪明。
有人知道为什么会这样吗?
因为这个 (p.name() for p in psutil.process_iter())
是一个生成器,当在用户进程中没有发现该进程时,它会尝试列出系统进程。考虑用 print('Firefox is not running by current user')
I get psutil.AccessDenied (pid=9092)
其他可能的原因是在迭代器获得要检索的 pid 后进程终止。由于您无法确定当您的 python 进程被 OS 调度程序暂停时该进程不会消失,无知似乎是一个合法的解决方案。
UPD:aa 就是这样(产生了死进程) https://github.com/giampaolo/psutil/blob/c3e63b4dd59f1724a7fa29371e53dfa7f46cbcd3/psutil/__init__.py#L1453-L1465
当您尝试访问进程名称(未缓存)时,它已经死了。所以我会跳过它而不是表现得像 运行.
process_iter()
允许您指定应该 returned 的属性。所以告诉它只 return 名字,然后比较它们。
if any(p.info['name'] == "firefox.exe" for p in psutil.process_iter(['name'])):
从文档中得到: