Is it possible to terminate a loop, if items within a given iterable (list/tuple) isn't updated after looping for given x times?

Viewed 29
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)

I am trying to iterate through a list of running processes on my system to generate a traceback of child/parent processes chain i.e:

python.exe < powershell.exe < Code.exe < Code.exe < Code.exe < explorer.exe 

My problem is after looping for sometime the traceback finishes or doesn't return anything & it keeps on looping, basically I have no idea how to terminate the parent while loop.

I even tried to compare the initial and final length of a traceback tuple, that seemed to work but limited the range of the traceback.

1 Answers

You wrote:

while True:
    for process in Win32_Process:

Simply get rid of the while loop, as the for loop suffices.


That said, the order of processes matters, so you might want to sort them by .ProcessID before you start looping over them.

Or throw them all into a dict and iterate over that. Or consider using one of the various graph packages, such as https://pypi.org/project/networkx , to help you navigate through the parent-child relationships of the process tree, and display them.

Related