Question

What does psutil.process_iter() include? Since, its a cached instance, does it include only processes that are running at the time or it includes everything and leaves their present status to be user verified? My code:

for _process in psutil.process_iter():
    try:
        new_proc = _process.as_dict(attrs=['cpu_times', 'name', 'pid', 'status'])
    except psutil.NoSuchProcess:
        continue

What all status gets filtered here? And what all do I have to verify on my own?

Was it helpful?

Solution 2

The docs for psutil.process_iter() say:

Return an iterator yielding a Process class instance for all running processes on the local machine. Every instance is only created once and then cached into an internal table which is updated every time an element is yielded. emphasize is mine

where "running" is defined by .is_running() method that returns True for zombie processes. .is_running() is safe to use even if the process is gone and its pid is reused.

My understanding is that _process.is_running() is true at the moment psutil.process_iter() yields it. In principle, before _process.as_dict returns with the info, several things may happen:

  1. process may die -- become a zombie: _process.is_running() is true, pid and status are meaningful
  2. it may be reaped -- dead-dead: the process info is unavailable (psutil.NoSuchProcess exception) or outdated (if cached)
  3. its pid may be reused -- some _process methods may return incorrectly the info for the new process. .is_running() uses several process attributes so it should detect the case when pid is reused.

Normally, OS doesn't reuse pid immediately therefore p.3 shouldn't occur frequently.

OTHER TIPS

psutil.process_iter() iterates over all the running processes in the system. ZombieProcess error is mostly observed in MacOS and workaround could be to handle it in the exception with except psutil.ZombieProcess:

for _process in psutil.process_iter():
    try:
        new_proc = _process.as_dict(attrs=['cpu_times', 'name', 'pid', 'status'])
    except psutil.NoSuchProcess:
        continue
    except psutil.ZombieProcess:
        continue
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top