Wednesday, October 31, 2012

psutil, Python tool to get process info and more


By Vasudev Ram

psutil is a versatile and cross-platform Python module for getting process and related information from the operating system.

Though the name psutil indicates that it works like the UNIX ps command (for process status), it does a lot more, and works on other platforms too.

IIRC, I had come across it earlier, but thought it was only for UNIX-like systems. I recently tried out psutil on Windows.

For certain Windows system processes, it may not give some info, due to those processes being privileged, according to one of the psutil authors, Giampaolo Rodola, who I emailed about it. He said: "On Windows you can't access all information about processes owned by NT AUTHORITY SYSTEM user. In those cases psutil will raise AccessDenied exception."

psutil can provide some information on:

- CPU time
- virtual memory
- swap memory (sic)
- disk partitions
- disk usage
- disk and network I/O
- users
- processes: name, executable name, working directory, command line, user name, user ids and group ids, threads, connections, file descriptors.

Here is a simple psutil test program which shows just a few features - output not well formatted, but readable. Try it on Windows or UNIX/Linux:

# test_psutil_00.py

import psutil

for pid in psutil.get_pid_list():
        p = psutil.Process(pid)
        p_name = p.name
        print "p_name:", p.name
        try:
                p_exe = p.exe
        except Exception, e:
                p_exe = "Can't access p.exe"
        print "p_exe:", p_exe
        try:
                p_cwd = p.getcwd()
        except Exception, e:
                p_cwd = "Can't access p.cwd()"
        print "p.getcwd():", p_cwd
        try:
                p_cmdline = p.cmdline
        except Exception, e:
                p_cmdline = "Can't access p.cmdline"
        print "p.cmdline:", p_cmdline

- Vasudev Ram

No comments: