Search code examples
pythonpsutil

Getting MacOS process id from user using python


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'.

enter image description here


Solution

  • 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.

    import psutil
    
    def pids_for_user(username: str) -> list[psutil.Process]:
        return [p for p in psutil.process_iter() if p.username() == username]
    
    print(pids_for_user("root"))
    

    Make note of all the exceptions that may be raised when you work with processes.