pythonunixkillpsprocesslist

how do I get the process list in Python?


How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes.


Solution

  • On linux, the easiest solution is probably to use the external ps command:

    >>> import os
    >>> data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \
    ...        for x in os.popen('ps h -eo pid:1,command')]]
    

    On other systems you might have to change the options to ps.

    Still, you might want to run man on pgrep and pkill.