I want to get the pid by passing in the user name. For example, in the picture of a macOS activity monitor, the user name is ‘root’, and I want something that can return all running processes under user name ‘root’.
Advertisement
Answer
Use psutil.process_iter() to get all running processes, and then filter them by matching psutil.Process.username() with the desired username.
The following code shows a function that produces a list of psutil.Process objects.
JavaScript
x
7
1
import psutil
2
3
def pids_for_user(username: str) -> list[psutil.Process]:
4
return [p for p in psutil.process_iter() if p.username() == username]
5
6
print(pids_for_user("root"))
7
Make note of all the exceptions that may be raised when you work with processes.