Reputation: 227
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?
Upvotes: 4
Views: 8026
Reputation: 186
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
Upvotes: 2
Reputation: 414207
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:
_process.is_running()
is true, pid
and status
are meaningfulpsutil.NoSuchProcess
exception) or outdated (if cached)_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.
Upvotes: 1