Python modules you should know: psutil
April 24, 2012 at 10:25 AM | categories: Python, PyMYSK, Howto | View CommentsNext in our series of Python modules you should know is psutil.
Home page
Use
psutil is a module providing an interface for retrieving information on all running processes and system utilization (CPU, disk, memory, network) in a portable way by using Python, implementing many functionalities offered by command line tools such as:
- ps
- top
- df
- kill
- free
- lsof
- netstat
- ifconfig
- nice
- ionice
- iostat
- iotop
- uptime
- pidof
- tty
- who
It currently supports Linux, Windows, OSX and FreeBSD, both 32-bit and 64-bit, with Python versions from 2.4 to 3.3 by using a single code base. Pypy is also known to work.
I have used it to gather system information like CPU usage, disk usage and RAM usage.
Installation
pip install psutil
Usage
Example usage,
CPU usage
import psutil for x in range(3): psutil.cpu_percent(interval=1)
Output:
4.7
5.2
5.0
RAM usage
import psutil psutil.phymem_usage() psutil.virtmem_usage()
Output:
usage(total=4294967296L, used=4158287872L, free=136679424L, percent=96.8)
usage(total=2147483648L, used=2045067264L, free=102416384L, percent=95.2)
Disks
Get list of partitions
import psutil psutil.disk_partitions()
Output:
[partition(device='/dev/disk0s2', mountpoint='/', fstype='hfs')]
Disk usage
import psutil psutil.disk_usage('/')
Output:
usage(total=499248103424, used=195677974528, free=303307984896, percent=39.2)
Network
import psutil psutil.network_io_counters(True)
Output:
{'gif0': iostat(bytes_sent=0L, bytes_recv=0L, packets_sent=0L, packets_recv=0L),
'pflog0': iostat(bytes_sent=0L, bytes_recv=0L, packets_sent=0L, packets_recv=0L),
'en0': iostat(bytes_sent=2376067805L, bytes_recv=5789960439L, packets_sent=10769542L, packets_recv=11796673L),
'en1': iostat(bytes_sent=40665975852L, bytes_recv=40514227524L, packets_sent=62248599L, packets_recv=55179277L),
'lo0': iostat(bytes_sent=21946718L, bytes_recv=21946718L, packets_sent=104300L, packets_recv=104300L),
'p2p0': iostat(bytes_sent=0L, bytes_recv=0L, packets_sent=0L, packets_recv=0L),
'stf0': iostat(bytes_sent=0L, bytes_recv=0L, packets_sent=0L, packets_recv=0L),
'fw0': iostat(bytes_sent=346L, bytes_recv=0L, packets_sent=0L, packets_recv=0L)}
And there is more
Lots more can be done using this package, please refer to the documentation for further usage information.
blog comments powered by Disqus