API Reference

Exceptions

psutil.NoSuchProcess(pid, name=None, msg=None)

Raised when no process with the given PID is found in the current process list or when a process no longer exists (zombie).

psutil.AccessDenied(pid=None, name=None, msg=None)

Raised when permission to perform an action is denied.

psutil.TimeoutExpired(pid=None, name=None)

Raised on Process.wait(timeout) if timeout expires and process is still alive.

New in 0.2.1

Classes

psutil.Process(pid)

A class which represents an OS process.
  • pid
    The process pid.
  • ppid
    The process parent pid.
  • parent
    Return the parent process as a Process object. If no ppid is known then return None.
  • name
    The process name.
  • exe
    The process executable as an absolute path name.
  • cmdline
    The command line process has been called with.
  • create_time
    The process creation time as a floating point number expressed in seconds since the epoch, in UTC.
  • >>> import os, psutil, datetime
    >>> p = psutil.Process(os.getpid())
    >>> p.create_time
    1307289803.47
    >>> datetime.datetime.fromtimestamp(p.create_time).strftime("%Y-%M-%d %H:%M")
    '2011-03-05 18:03'
  • uids
    The real, effective and saved user ids of the current process as a nameduple. This is the same as os.getresuid() but per-process.
New in 0.2.1
Availability: UNIX
  • gids
    The real, effective and saved group ids of the current process as a nameduple. This is the same as os.getresgid() but per-process.
New in 0.2.1
Availability: UNIX
  • username
    The name of the user that owns the process. On UNIX this is calculated by using real process uid.
Changed in 2.0: Windows implementation has been rewritten in C for performace and pywin32 extension is no longer required.
  • terminal
    The terminal associated with this process, if any, else None. This is similar to "tty" command but per-process.
New in 0.3.0
Availability: UNIX
  • status
    The current process status. The return value is one of the STATUS_* constants, which is an integer that can be used in conjunction with str() to obtain a human-readable form of the current process status. Example:
  • >>> import psutil, os
    >>> p = psutil.Process(os.getpid())
    >>> p.status
    0
    >>> p.status == psutil.STATUS_RUNNING
    True
    >>> str(p.status)
    'running'
    >>>
New in 2.1
  • nice
    Get or set process niceness (priority). On UNIX this is a number which usually goes from -20 to 20. The higher the nice value, the lower the priority of the process.
  • >>> p = psutil.Process(os.getpid())
    >>> p.nice
    0
    >>> p.nice = 10  # set/change process priority
    >>> p.nice
    10
On Windows this is available as well by using GetPriorityClass and SetPriorityClass. psutil.*_PRIORITY_CLASS constants (explained here) can be used in conjunction. Example which increases process priority:
>> p.nice = psutil.HIGH_PRIORITY_CLASS
New in 2.1
  • getcwd()
    Return a string representing the process current working directory.
Availability: Windows, Linux
  • get_io_counters()
    Return process I/O statistics as a namedtuple including the number of read and write operations performed by the process and the amount of bytes read and written. For linux refer to /proc filesysem documentation. On BSD there's apparently no way to retrieve bytes counters, hence -1 is returned for read_bytes and write_bytes fields. OSX is not supported.
  • >>> p.get_io_counters()
    io(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0)
New in 2.1
Availability: Linux, Windows, FreeBSD
  • get_ionice()
    Return process I/O niceness (priority) as a namedtuple including priority class and priority data. See set_ionice below for more information.
New in 2.1
Availability: Linux
  • set_ionice(ioclass, value=None)
    Change process I/O niceness (priority). ioclass is one of the IOPRIO_CLASS_* constants. value is a number which goes from 0 to 7. The higher value value, the lower the I/O priority of the process. For further information refer to ionice command line utility or ioprio_set system call. The example below sets IDLE priority class for the current process, meaning it will only get I/O time when no other process needs the disk:
  • >>> import psutil, os
    >>> p = psutil.Process(os.getpid())
    >>> p.set_ionice(psutil.IOPRIO_CLASS_IDLE)
    >>>
New in 2.1
Availability: Linux
  • get_num_threads()
    Return the number of threads used by this process.
  • get_threads()
    Return threads opened by process as a list of namedtuples including thread id and thread CPU times (user/system).
New in 0.2.1
  • get_cpu_times()
    Return a tuple whose values are process CPU user and system times which means the amount of time expressed in seconds that a process has spent in user/system mode.
  • get_cpu_percent(interval=0.1)
    Return a float representing the process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls.
Changed in 0.2.0: interval parameter was added
  • get_memory_info()
    Return a tuple representing RSS (Resident Set Size) and VMS (Virtual Memory Size) in bytes.
    On UNIX RSS and VMS are the same values shown by ps. On Windows RSS and VMS refer to "Mem Usage" and "VM Size" columns of taskmgr.exe.
  • get_memory_percent()
    Compare physical system memory to process resident memory and calculate process memory utilization as a percentage.
  • get_children()
    Return the children of this process as a list of Process objects.
  • get_open_files()
    Return files opened by process as a list of namedtuples including file absolute path name and file descriptor. On FreeBSD this is done by parsing lsof command output. If lsof is not installed on the system NotImplementedError exception is raised. Example:
  • >>> import psutil, os
    >>> f = open('file.ext', 'w')
    >>> p = psutil.Process(os.getpid())
    >>> p.get_open_files()
    [openfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3)]
Changed in 0.2.1: OSX implementation rewritten in C; no longer requiring lsof.
  • get_connections()
    Return all TCP and UPD connections opened by process as a list of namedtuples. Every namedtuple provides 6 attributes:

    • fd: the socket file descriptor. This can be passed to socket.fromfd to obtain a usable socket object. This is only available on UNIX; on Windows -1 is always returned.
    • family: the address family, either AF_INET or AF_INET6
    • type: the address type, either SOCK_STREAM or SOCK_DGRAM
    • local_address: the local address as a (ip, port) tuple.
    • remote_address: the remote address as a (ip, port) tuple. When the remote endpoint is not connected the tuple is empty.
    • status: a string representing the TCP connections status. String values are supposed to match Linux's tcp_states.h header file across all platforms. For UDP sockets this is always going to be an empty string.
Example:
>>> p = psutil.Process(1694)
>>> p.name
'firefox'
>>> p.get_connections()
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776), remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
 connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761), remote_address=('72.14.234.100', 80), status='CLOSING'),
 connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759), remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
 connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314), remote_address=('72.14.234.83', 443), status='SYN_SENT')]
On FreeBSD this is implemented by parsing lsof command output. If lsof is not installed on the system NotImplementedError exception is raised and for third party processes (different than os.getpid()) results can differ depending on user privileges.
Changed in 0.2.1: OSX implementation rewritten in C; no longer requiring lsof.
  • is_running()
    Return whether the current process is running in the current process list.
  • send_signal(signal)
    Send a signal to process (see signal module constants). On Windows only SIGTERM is valid and is treated as an alias for kill().
  • suspend()
    Suspend process execution with SIGSTOP signal. On Windows this is done by suspending all process threads execution.
  • resume()
    Resume process execution with SIGCONT signal. On Windows this is done by resuming all process threads execution.
  • terminate()
    Terminate the process with SIGTERM signal. On Windows this is an alias for kill().
  • kill()
    Kill the current process by using SIGKILL signal.
Changed in 0.2.0: no longer accepts sig keyword argument - use send_signal() instead.
  • wait(timeout=None)
    Wait for process termination and if the process is a children of the current one also return the exit code, else None. On Windows there's no such limitation (exit code is always returned). If the process is already terminated does not raise NoSuchProcess exception but just return None immediately. If timeout is specified and process is still alive raises TimeoutExpired exception.
New in 0.2.1



psutil.Popen(*args, **kwargs)

A more convenient interface to stdlib subprocess.Popen. It starts a sub process and deals with it exactly as when using subprocess.Popen class but in addition also provides all the properties and methods of psutil.Process class in a unique interface. For method names common to both classes such as kill() and terminate(), psutil.Process implementation takes precedence. For a complete documentation refers to subprocess module documentation.
>>> import psutil
>>> from subprocess import PIPE
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print 'hi'"], stdout=PIPE)
>>> p.name
'python'
>>> p.uids
user(real=1000, effective=1000, saved=1000)
>>> p.username
'giampaolo'
>>> p.communicate()
('hi\n', None)
>>> p.wait(timeout=2)
0
>>>
New in 0.2.1

Functions

psutil.get_pid_list()

Return a list of current running PIDs.

psutil.pid_exists(pid)

Check whether the given PID exists in the current process list. This is faster than doing pid in psutil.get_pid_list() and should be preferred.

psutil.process_iter()

Return an iterator yielding a Process class instances for all running processes on the local machine. This should be preferred over doing for pid in psutil.get_pid_list(): psutil.Process(pid) as it safe from race conditions.


System related functions

CPU

psutil.cpu_percent(interval=0.1, percpu=False)

Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls.
When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.

>>> # blocking, system-wide
>>> psutil.cpu_percent(interval=1)
2.0
>>>
>>> # blocking, per-cpu
>>> psutil.cpu_percent(interval=1, percpu=True)
[2.0, 1.0]
>>>
>>> # non-blocking (percentage since last call)
>>> psutil.cpu_percent(interval=0)
2.9
>>>
Changed in 0.2.0: interval parameter was added
Changed in 0.3.0: percpu parameter was added

psutil.cpu_times(percpu=False)

Return system CPU times as a namedtuple. Every attribute represents the time CPU has spent in the given mode.
The attributes availability varies depending on the platform. Here follows a list of all available attributes:
- user
- system
- idle
- nice (UNIX)
- iowait (Linux)
- irq (Linux, FreeBSD)
- softirq (Linux)

When percpu is True return a list of nameduples for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.
Changed in 0.3.0: percpu parameter was added

Memory

psutil.phymem_usage()

Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage.

>>> psutil.phymem_usage()
usage(total=4153868288, used=2854199296, free=1299668992, percent=34.6)
New in 0.3.0

psutil.virtmem_usage()

Return the amount of total, used and free virtual memory on the system in bytes plus the percentage usage.
On Linux they match the values returned by free command line utility. On OS X and FreeBSD they represent the same values as returned by sysctl vm.vmtotal. On Windows they are determined by reading the *PageFile values of MEMORYSTATUSEX structure.

>>> psutil.virtmem_usage()
usage(total=2097147904, used=4096, free=2097143808, percent=0.0)
New in 0.3.0

psutil.cached_phymem()
psutil.phymem_buffers()

Return the amount of cached memory and physical memory buffers on the system, in bytes. Thet reflects the "cached" and "buffers" columns of free command line utility on Linux.

Availability: Linux

psutil.avail_phymem()
psutil.used_phymem()
psutil.total_virtmem()
psutil.avail_virtmem()
psutil.used_virtmem()

These functions are deprecated by psutil.phymem_usage() and psutil.virtmem_usage(). Use them instead.

Deprecated in 0.3.0

Disk

psutil.disk_partitions(all=False)

Return all mounted disk partitions as a list of namedtuples including device, mount point and filesystem type, similarly to "df" command on posix.
If all parameter is False return physical devices only (e.g. hard disks, cd-rom drives, USB keys) and ignore all others (e.g. memory partitions such as /dev/shm).
Namedtuple's 'fstype' field is a string which varies depending on the platform.
On Linux it can be one of the values found in /proc/filesystems (e.g. 'ext3' for an ext3 hard drive o 'iso9660' for the CD-ROM drive).
On Windows it is determined via GetDriveType and can be either "removable", "fixed", "remote", "cdrom", "unmounted" or "ramdisk".
On OSX and FreeBSD it is retrieved via getfsstat(2).
See examples/disk_usage.py script providing an example usage.

>>> psutil.get_partitions()
[partition(device='/dev/sda3', mountpoint='/', fstype='ext4'),
 partition(device='/dev/sda7', mountpoint='/home', fstype='ext4')]
>>>
New in 0.3.0

psutil.disk_usage(path)

Return disk usage statistics about the given path as a namedtuple including total, used and free space expressed in bytes plus the percentage usage. OSError is raised if path does not exist. See examples/disk_usage.py script providing an example usage.

>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
New in 0.3.0

Constants

psutil.TOTAL_PHYMEM

The amount of total physical memory on the system, in bytes.

psutil.NUM_CPUS

The number of CPUs on the system. This is preferable than using os.environ['NUMBER_OF_PROCESSORS'] as it is more accurate and always available.

psutil.BOOT_TIME

A number indicating the system boot time expressed in seconds since the epoch.

New in 0.2.1

psutil.ABOVE_NORMAL_PRIORITY_CLASS
psutil.BELOW_NORMAL_PRIORITY_CLASS
psutil.HIGH_PRIORITY_CLASS
psutil.IDLE_PRIORITY_CLASS
psutil.NORMAL_PRIORITY_CLASS
psutil.REALTIME_PRIORITY_CLASS

A set of integers representing the priority of a process on Windows (see MSDN documentation). They can be used in conjunction with psutil.Process.nice to get or set process priority.

New in 0.2.1
Availability: Windows

psutil.IOPRIO_CLASS_NONE
psutil.IOPRIO_CLASS_RT
psutil.IOPRIO_CLASS_BE
psutil.IOPRIO_CLASS_IDLE

A set of integers representing the I/O priority of a process on Linux. They can be used in conjunction with psutil.Process.get_ionice() and psutil.Process.set_ionice() to get or set process I/O priority. For further information refer to ionice command line utility or ioprio_get system call.

New in 0.2.1
Availability: Linux

psutil.STATUS_RUNNING
psutil.STATUS_SLEEPING
psutil.STATUS_DISK_SLEEP
psutil.STATUS_STOPPED
psutil.STATUS_TRACING_STOP
psutil.STATUS_ZOMBIE
psutil.STATUS_DEAD
psutil.STATUS_WAKE_KILL
psutil.STATUS_WAKING
psutil.STATUS_IDLE
psutil.STATUS_LOCKED
psutil.STATUS_WAITING

A set of integers representing the status of a process. To be used in conjunction with psutil.Process.status property. If used with str() return a human-readable status string.

New in 0.2.1