Skip to content
Advertisement

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

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

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

Advertisement