如果给定的可迭代(列表/元组)中的项目在循环给定 x 次后没有更新,是否可以终止循环?
from wmi import WMI
from os import getpid
pid = getpid()
Win32_Process = WMI().Win32_Process()
while True:
for process in Win32_Process:
if process.ProcessID == pid:
pid = process.ParentProcessId
print(process.name)
我正在尝试遍历系统上正在运行的进程列表以生成子/父进程链的回溯,即:
python.exe < powershell.exe < Code.exe < Code.exe < Code.exe < explorer.exe
我的问题是在循环一段时间后回溯完成或不返回任何内容并且它继续循环,基本上我不知道如何终止父while
循环。
我什至尝试比较回溯元组的初始长度和最终长度,这似乎有效,但限制了回溯的范围。
-
你写了:
while True: for process in Win32_Process:
只需摆脱
while
循环,for
循环就足够了。
也就是说,进程的顺序很重要,因此您可能希望
.ProcessID
在开始循环之前对它们进行排序。或者将它们全部放入 a
dict
并对其进行迭代。或者考虑使用各种图形包之一,例如https://pypi.org/project/networkx来帮助您浏览流程树的父子关系并显示它们。