psutil._pslinux

Linux platform implementation.

Module Contents

enum
__extra__all__ = ['PROCFS_PATH', 'IOPRIO_CLASS_NONE', 'IOPRIO_CLASS_RT', 'IOPRIO_CLASS_BE', 'IOPRIO_CLASS_IDLE', 'CONN_ESTABLISHED', 'CONN_SYN_SENT', 'CONN_SYN_RECV', 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_TIME_WAIT', 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_LAST_ACK', 'CONN_LISTEN', 'CONN_CLOSING']
POWER_SUPPLY_PATH = /sys/class/power_supply
HAS_SMAPS
HAS_PRLIMIT
HAS_PROC_IO_PRIORITY
_DEFAULT
CLOCK_TICKS
PAGESIZE
BOOT_TIME
BIGFILE_BUFFERING
LITTLE_ENDIAN
DISK_SECTOR_SIZE = 512
IOPRIO_CLASS_NONE = 0
PROC_STATUSES
TCP_STATUSES
NoSuchProcess
ZombieProcess
AccessDenied
TimeoutExpired
svmem
sdiskio
popenfile
pmem
pfullmem
pmmap_grouped
pmmap_ext
pio
decode(s)
get_procfs_path()

Return updated psutil.PROCFS_PATH constant.

Wrapper around os.readlink().

file_flags_to_mode(flags)

Convert file’s open() flags into a readable string. Used by Process.open_files().

is_storage_device(name)

Return True if the given name refers to a root device (e.g. “sda”, “nvme0n1”) as opposed to a logical partition (e.g. “sda1”, “nvme0n1p1”). If name is a virtual device (e.g. “loop1”, “ram”) return True.

set_scputimes_ntuple(procfs_path)

Set a namedtuple of variable fields depending on the CPU times available on this Linux kernel version which may be: (user, nice, system, idle, iowait, irq, softirq, [steal, [guest,

[guest_nice]]])

Used by cpu_times() function.

cat(fname, fallback=_DEFAULT, binary=True)

Return file content. fallback: the value returned in case the file does not exist or

cannot be read

binary: whether to open the file in binary or text mode.

scputimes
calculate_avail_vmem(mems)

Fallback for kernels < 3.14 where /proc/meminfo does not provide “MemAvailable:” column, see: https://blog.famzah.net/2014/09/24/ This code reimplements the algorithm outlined here: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/

commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

XXX: on recent kernels this calculation differs by ~1.5% than “MemAvailable:” as it’s calculated slightly differently, see: https://gitlab.com/procps-ng/procps/issues/42 https://github.com/famzah/linux-memavailable-procfs/issues/2 It is still way more realistic than doing (free + cached) though.

virtual_memory()

Report virtual memory stats. This implementation matches “free” and “vmstat -s” cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/

24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c

For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04.

Note about “available” memory: up until psutil 4.3 it was calculated as “avail = (free + buffers + cached)”. Now “MemAvailable:” column (kernel 3.14) from /proc/meminfo is used as it’s more accurate. That matches “available” column in newer versions of “free”.

swap_memory()

Return swap memory metrics.

cpu_times()

Return a named tuple representing the following system-wide CPU times: (user, nice, system, idle, iowait, irq, softirq [steal, [guest,

[guest_nice]]])

Last 3 fields may not be available on all Linux kernel versions.

per_cpu_times()

Return a list of namedtuple representing the CPU times for every CPU available on the system.

cpu_count_logical()

Return the number of logical CPUs in the system.

cpu_count_physical()

Return the number of physical cores in the system.

cpu_stats()

Return various CPU stats as a named tuple.

cpu_freq()

Return frequency metrics for all CPUs. Contrarily to other OSes, Linux updates these values in real-time.

net_if_addrs
exception _Ipv6UnsupportedError

Bases:Exception

class Connections

A wrapper on top of /proc/net/* files, retrieving per-process and system-wide open connections (TCP, UDP, UNIX) similarly to “netstat -an”.

Note: in case of UNIX sockets we’re only able to determine the local endpoint/path, not the one it’s connected to. According to [1] it would be possible but not easily.

[1] http://serverfault.com/a/417946

get_proc_inodes(self, pid)
get_all_inodes(self)
static decode_address(addr, family)

Accept an “ip:port” address as displayed in /proc/net/* and convert it into a human readable form, like:

“0500000A:0016” -> (“10.0.0.5”, 22) “0000000000000000FFFF00000100007F:9E49” -> (“::ffff:127.0.0.1”, 40521)

The IP address portion is a little or big endian four-byte hexadecimal number; that is, the least significant byte is listed first, so we need to reverse the order of the bytes to convert it to an IP address. The port is represented as a two-byte hexadecimal number.

Reference: http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html

static process_inet(file, family, type_, inodes, filter_pid=None)

Parse /proc/net/tcp* and /proc/net/udp* files.

static process_unix(file, family, inodes, filter_pid=None)

Parse /proc/net/unix files.

retrieve(self, kind, pid=None)
_connections
net_connections(kind='inet')

Return system-wide open connections.

net_io_counters()

Return network I/O statistics for every network interface installed on the system as a dict of raw tuples.

net_if_stats()

Get NIC stats (isup, duplex, speed, mtu).

disk_usage
disk_io_counters(perdisk=False)

Return disk I/O statistics for every disk installed on the system as a dict of raw tuples.

disk_partitions(all=False)

Return mounted disk partitions as a list of namedtuples.

sensors_temperatures()

Return hardware (CPU and others) temperatures as a dict including hardware name, label, current, max and critical temperatures.

Implementation notes: - /sys/class/hwmon looks like the most recent interface to

retrieve this info, and this implementation relies on it only (old distros will probably use something else)
  • lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
  • /sys/class/thermal/thermal_zone* is another one but it’s more difficult to parse
sensors_fans()

Return hardware fans info (for CPU and other peripherals) as a dict including hardware label and current speed.

Implementation notes: - /sys/class/hwmon looks like the most recent interface to

retrieve this info, and this implementation relies on it only (old distros will probably use something else)
  • lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
sensors_battery()

Return battery information. Implementation note: it appears /sys/class/power_supply/BAT0/ directory structure may vary and provide files with the same meaning but under different names, see: https://github.com/giampaolo/psutil/issues/966

users()

Return currently connected users as a list of namedtuples.

boot_time()

Return the system boot time expressed in seconds since the epoch.

pids()

Returns a list of PIDs currently running on the system.

pid_exists(pid)

Check for the existence of a unix PID. Linux TIDs are not supported (always return False).

ppid_map()

Obtain a {pid: ppid, …} dict for all running processes in one shot. Used to speed up Process.children().

wrap_exceptions(fun)

Decorator which translates bare OSError and IOError exceptions into NoSuchProcess and AccessDenied.

class Process(pid)

Bases:object

Linux process implementation.

__slots__ = ['pid', '_name', '_ppid', '_procfs_path', '_cache']
_assert_alive(self)

Raise NSP if the process disappeared on us.

_parse_stat_file(self)

Parse /proc/{pid}/stat file and return a dict with various process info. Using “man proc” as a reference: where “man proc” refers to position N always substract 3 (e.g ppid position 4 in ‘man proc’ == position 1 in here). The return value is cached in case oneshot() ctx manager is in use.

_read_status_file(self)

Read /proc/{pid}/stat file and return its content. The return value is cached in case oneshot() ctx manager is in use.

_read_smaps_file(self)
oneshot_enter(self)
oneshot_exit(self)
name(self)
exe(self)
cmdline(self)
environ(self)
terminal(self)
io_counters(self)
cpu_times(self)
cpu_num(self)

What CPU the process is on.

wait(self, timeout=None)
create_time(self)
memory_info(self)
memory_full_info(self, _private_re=re.compile(b'\nPrivate.*:\s+(\d+)'), _pss_re=re.compile(b'\nPss\:\s+(\d+)'), _swap_re=re.compile(b'\nSwap\:\s+(\d+)'))
memory_maps(self)

Return process’s mapped memory regions as a list of named tuples. Fields are explained in ‘man proc’; here is an updated (Apr 2012) version: http://goo.gl/fmebo

/proc/{PID}/smaps does not exist on kernels < 2.6.14 or if CONFIG_MMU kernel configuration option is not enabled.

cwd(self)
num_ctx_switches(self, _ctxsw_re=re.compile(b'ctxt_switches:\t(\d+)'))
num_threads(self, _num_threads_re=re.compile(b'Threads:\t(\d+)'))
threads(self)
nice_get(self)
nice_set(self, value)
cpu_affinity_get(self)
_get_eligible_cpus(self, _re=re.compile(b'Cpus_allowed_list:\t(\d+)-(\d+)'))
cpu_affinity_set(self, cpus)
ionice_get(self)
rlimit(self, resource, limits=None)
status(self)
open_files(self)
connections(self, kind='inet')
num_fds(self)
ppid(self)
uids(self, _uids_re=re.compile(b'Uid:\t(\d+)\t(\d+)\t(\d+)'))
gids(self, _gids_re=re.compile(b'Gid:\t(\d+)\t(\d+)\t(\d+)'))