Bug 930808 - Upgrade to psutil 2.1.3; r=glandium

psutil 2.1.3 is replacing psutil 1.0.1. There are numerous bug fixes and
feature enhancements in psutil worth obtaining.

Source code was obtained from
https://pypi.python.org/packages/source/p/psutil/psutil-2.1.3.tar.gz and
uncompressed into python/psutil without modification except for the
removal of the egg-info directory and the .travis.yml file.
This commit is contained in:
Gregory Szorc
2014-12-23 10:45:15 -08:00
parent af58a95a53
commit 5881d1a65d
88 changed files with 13624 additions and 7313 deletions

View File

@@ -6,6 +6,13 @@
"""
List all mounted disk partitions a-la "df -h" command.
$ python examples/disk_usage.py
Device Total Used Free Use % Type Mount
/dev/sdb3 18.9G 14.7G 3.3G 77% ext4 /
/dev/sda6 345.9G 83.8G 244.5G 24% ext4 /home
/dev/sda1 296.0M 43.1M 252.9M 14% vfat /boot/efi
/dev/sda2 600.0M 312.4M 287.6M 52% fuseblk /media/Recovery
"""
import sys
@@ -13,6 +20,7 @@ import os
import psutil
from psutil._compat import print_
def bytes2human(n):
# http://code.activestate.com/recipes/578019
# >>> bytes2human(10000)
@@ -22,7 +30,7 @@ def bytes2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
@@ -32,19 +40,24 @@ def bytes2human(n):
def main():
templ = "%-17s %8s %8s %8s %5s%% %9s %s"
print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type",
"Mount"))
for part in psutil.disk_partitions(all=False):
if os.name == 'nt' and 'cdrom' in part.opts:
# may raise ENOENT if there's no cd-rom in the drive
continue
if os.name == 'nt':
if 'cdrom' in part.opts or part.fstype == '':
# skip cd-rom drives with no disk in it; they may raise
# ENOENT, pop-up a Windows GUI error for a non-ready
# partition or just hang.
continue
usage = psutil.disk_usage(part.mountpoint)
print_(templ % (part.device,
bytes2human(usage.total),
bytes2human(usage.used),
bytes2human(usage.free),
int(usage.percent),
part.fstype,
part.mountpoint))
print_(templ % (
part.device,
bytes2human(usage.total),
bytes2human(usage.used),
bytes2human(usage.free),
int(usage.percent),
part.fstype,
part.mountpoint))
if __name__ == '__main__':
sys.exit(main())

View File

@@ -6,26 +6,37 @@
"""
A clone of 'free' cmdline utility.
$ python examples/free.py
total used free shared buffers cache
Mem: 10125520 8625996 1499524 0 349500 3307836
Swap: 0 0 0
"""
import psutil
from psutil._compat import print_
def main():
virt = psutil.virtual_memory()
swap = psutil.swap_memory()
templ = "%-7s %10s %10s %10s %10s %10s %10s"
print_(templ % ('', 'total', 'used', 'free', 'shared', 'buffers', 'cache'))
print_(templ % ('Mem:', int(virt.total / 1024),
int(virt.used / 1024),
int(virt.free / 1024),
int(getattr(virt, 'shared', 0) / 1024),
int(getattr(virt, 'buffers', 0) / 1024),
int(getattr(virt, 'cached', 0) / 1024)))
print_(templ % ('Swap:', int(swap.total / 1024),
int(swap.used / 1024),
int(swap.free / 1024),
'', '', ''))
print_(templ % (
'Mem:',
int(virt.total / 1024),
int(virt.used / 1024),
int(virt.free / 1024),
int(getattr(virt, 'shared', 0) / 1024),
int(getattr(virt, 'buffers', 0) / 1024),
int(getattr(virt, 'cached', 0) / 1024)))
print_(templ % (
'Swap:', int(swap.total / 1024),
int(swap.used / 1024),
int(swap.free / 1024),
'',
'',
''))
if __name__ == '__main__':
main()

View File

@@ -12,13 +12,28 @@ It works on Linux only (FreeBSD and OSX are missing support for IO
counters).
It doesn't work on Windows as curses module is required.
Example output:
$ python examples/iotop.py
Total DISK READ: 0.00 B/s | Total DISK WRITE: 472.00 K/s
PID USER DISK READ DISK WRITE COMMAND
13155 giampao 0.00 B/s 428.00 K/s /usr/bin/google-chrome-beta
3260 giampao 0.00 B/s 0.00 B/s bash
3779 giampao 0.00 B/s 0.00 B/s gnome-session --session=ubuntu
3830 giampao 0.00 B/s 0.00 B/s /usr/bin/dbus-launch
3831 giampao 0.00 B/s 0.00 B/s //bin/dbus-daemon --fork --print-pid 5
3841 giampao 0.00 B/s 0.00 B/s /usr/lib/at-spi-bus-launcher
3845 giampao 0.00 B/s 0.00 B/s /bin/dbus-daemon
3848 giampao 0.00 B/s 0.00 B/s /usr/lib/at-spi2-core/at-spi2-registryd
3862 giampao 0.00 B/s 0.00 B/s /usr/lib/gnome-settings-daemon
Author: Giampaolo Rodola' <g.rodola@gmail.com>
"""
import os
import sys
import psutil
if not hasattr(psutil.Process, 'get_io_counters') or os.name != 'posix':
if not hasattr(psutil.Process, 'io_counters') or os.name != 'posix':
sys.exit('platform not supported')
import time
import curses
@@ -37,6 +52,7 @@ atexit.register(tear_down)
curses.endwin()
lineno = 0
def print_line(line, highlight=False):
"""A thin wrapper around curses's addstr()."""
global lineno
@@ -65,13 +81,14 @@ def bytes2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f %s/s' % (value, s)
return '%.2f B/s' % (n)
def poll(interval):
"""Calculate IO usage by comparing IO statics before and
after the interval.
@@ -82,7 +99,7 @@ def poll(interval):
procs = [p for p in psutil.process_iter()]
for p in procs[:]:
try:
p._before = p.get_io_counters()
p._before = p.io_counters()
except psutil.Error:
procs.remove(p)
continue
@@ -94,11 +111,11 @@ def poll(interval):
# then retrieve the same info again
for p in procs[:]:
try:
p._after = p.get_io_counters()
p._cmdline = ' '.join(p.cmdline)
p._after = p.io_counters()
p._cmdline = ' '.join(p.cmdline())
if not p._cmdline:
p._cmdline = p.name
p._username = p.username
p._cmdline = p.name()
p._username = p.username()
except psutil.NoSuchProcess:
procs.remove(p)
disks_after = psutil.disk_io_counters()
@@ -134,17 +151,19 @@ def refresh_window(procs, disks_read, disks_write):
print_line(header, highlight=True)
for p in procs:
line = templ % (p.pid,
p._username[:7],
bytes2human(p._read_per_sec),
bytes2human(p._write_per_sec),
p._cmdline)
line = templ % (
p.pid,
p._username[:7],
bytes2human(p._read_per_sec),
bytes2human(p._write_per_sec),
p._cmdline)
try:
print_line(line)
except curses.error:
break
win.refresh()
def main():
try:
interval = 0

View File

@@ -12,6 +12,7 @@ import os
import sys
import psutil
def main():
if len(sys.argv) != 2:
sys.exit('usage: %s name' % __file__)
@@ -20,7 +21,7 @@ def main():
killed = []
for proc in psutil.process_iter():
if proc.name == NAME and proc.pid != os.getpid():
if proc.name() == NAME and proc.pid != os.getpid():
proc.kill()
killed.append(proc.pid)
if not killed:

View File

@@ -6,21 +6,59 @@
"""
Print system memory information.
$ python examples/meminfo.py
MEMORY
------
Total : 9.7G
Available : 4.9G
Percent : 49.0
Used : 8.2G
Free : 1.4G
Active : 5.6G
Inactive : 2.1G
Buffers : 341.2M
Cached : 3.2G
SWAP
----
Total : 0B
Used : 0B
Free : 0B
Percent : 0.0
Sin : 0B
Sout : 0B
"""
import psutil
from psutil._compat import print_
def to_meg(n):
return str(int(n / 1024 / 1024)) + "M"
def bytes2human(n):
# http://code.activestate.com/recipes/578019
# >>> bytes2human(10000)
# '9.8K'
# >>> bytes2human(100001221)
# '95.4M'
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n
def pprint_ntuple(nt):
for name in nt._fields:
value = getattr(nt, name)
if name != 'percent':
value = to_meg(value)
value = bytes2human(value)
print_('%-10s : %7s' % (name.capitalize(), value))
def main():
print_('MEMORY\n------')
pprint_ntuple(psutil.virtual_memory())

View File

@@ -5,7 +5,18 @@
# found in the LICENSE file.
"""
A clone of 'netstat'.
A clone of 'netstat -antp' on Linux.
$ python examples/netstat.py
Proto Local address Remote address Status PID Program name
tcp 127.0.0.1:48256 127.0.0.1:45884 ESTABLISHED 13646 chrome
tcp 127.0.0.1:47073 127.0.0.1:45884 ESTABLISHED 13646 chrome
tcp 127.0.0.1:47072 127.0.0.1:45884 ESTABLISHED 13646 chrome
tcp 127.0.0.1:45884 - LISTEN 13651 GoogleTalkPlugi
tcp 127.0.0.1:60948 - LISTEN 13651 GoogleTalkPlugi
tcp 172.17.42.1:49102 127.0.0.1:19305 CLOSE_WAIT 13651 GoogleTalkPlugi
tcp 172.17.42.1:55797 127.0.0.1:443 CLOSE_WAIT 13651 GoogleTalkPlugi
...
"""
import socket
@@ -17,36 +28,38 @@ from psutil._compat import print_
AD = "-"
AF_INET6 = getattr(socket, 'AF_INET6', object())
proto_map = {(AF_INET, SOCK_STREAM) : 'tcp',
(AF_INET6, SOCK_STREAM) : 'tcp6',
(AF_INET, SOCK_DGRAM) : 'udp',
(AF_INET6, SOCK_DGRAM) : 'udp6'}
proto_map = {
(AF_INET, SOCK_STREAM): 'tcp',
(AF_INET6, SOCK_STREAM): 'tcp6',
(AF_INET, SOCK_DGRAM): 'udp',
(AF_INET6, SOCK_DGRAM): 'udp6',
}
def main():
templ = "%-5s %-22s %-22s %-13s %-6s %s"
print_(templ % ("Proto", "Local addr", "Remote addr", "Status", "PID",
"Program name"))
templ = "%-5s %-30s %-30s %-13s %-6s %s"
print_(templ % (
"Proto", "Local address", "Remote address", "Status", "PID",
"Program name"))
proc_names = {}
for p in psutil.process_iter():
name = '?'
try:
name = p.name
cons = p.get_connections(kind='inet')
except psutil.AccessDenied:
print_(templ % (AD, AD, AD, AD, p.pid, name))
except psutil.NoSuchProcess:
continue
else:
for c in cons:
raddr = ""
laddr = "%s:%s" % (c.laddr)
if c.raddr:
raddr = "%s:%s" % (c.raddr)
print_(templ % (proto_map[(c.family, c.type)],
laddr,
raddr,
str(c.status),
p.pid,
name[:15]))
proc_names[p.pid] = p.name()
except psutil.Error:
pass
for c in psutil.net_connections(kind='inet'):
laddr = "%s:%s" % (c.laddr)
raddr = ""
if c.raddr:
raddr = "%s:%s" % (c.raddr)
print_(templ % (
proto_map[(c.family, c.type)],
laddr,
raddr or AD,
c.status,
c.pid or AD,
proc_names.get(c.pid, '?')[:15],
))
if __name__ == '__main__':
main()

View File

@@ -10,14 +10,33 @@
Shows real-time network statistics.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
$ python examples/nettop.py
-----------------------------------------------------------
total bytes: sent: 1.49 G received: 4.82 G
total packets: sent: 7338724 received: 8082712
wlan0 TOTAL PER-SEC
-----------------------------------------------------------
bytes-sent 1.29 G 0.00 B/s
bytes-recv 3.48 G 0.00 B/s
pkts-sent 7221782 0
pkts-recv 6753724 0
eth1 TOTAL PER-SEC
-----------------------------------------------------------
bytes-sent 131.77 M 0.00 B/s
bytes-recv 1.28 G 0.00 B/s
pkts-sent 0 0
pkts-recv 1214470 0
"""
import sys
import os
if os.name != 'posix':
sys.exit('platform not supported')
import curses
import atexit
import curses
import time
import psutil
@@ -35,6 +54,7 @@ atexit.register(tear_down)
curses.endwin()
lineno = 0
def print_line(line, highlight=False):
"""A thin wrapper around curses's addstr()."""
global lineno
@@ -63,13 +83,14 @@ def bytes2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f %s' % (value, s)
return '%.2f B' % (n)
def poll(interval):
"""Retrieve raw stats within an interval window."""
tot_before = psutil.net_io_counters()
@@ -86,14 +107,12 @@ def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
global lineno
# totals
print_line("total bytes: sent: %-10s received: %s" \
% (bytes2human(tot_after.bytes_sent),
bytes2human(tot_after.bytes_recv))
print_line("total bytes: sent: %-10s received: %s" % (
bytes2human(tot_after.bytes_sent),
bytes2human(tot_after.bytes_recv))
)
print_line("total packets: sent: %-10s received: %s" \
% (tot_after.packets_sent, tot_after.packets_recv)
)
print_line("total packets: sent: %-10s received: %s" % (
tot_after.packets_sent, tot_after.packets_recv))
# per-network interface details: let's sort network interfaces so
# that the ones which generated more traffic are shown first
@@ -108,12 +127,14 @@ def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
print_line(templ % (
"bytes-sent",
bytes2human(stats_after.bytes_sent),
bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
bytes2human(
stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
))
print_line(templ % (
"bytes-recv",
bytes2human(stats_after.bytes_recv),
bytes2human(stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
bytes2human(
stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
))
print_line(templ % (
"pkts-sent",
@@ -133,7 +154,7 @@ def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
def main():
try:
interval = 0
while 1:
while True:
args = poll(interval)
refresh_window(*args)
interval = 1

View File

@@ -7,6 +7,27 @@
"""
A clone of 'pmap' utility on Linux, 'vmmap' on OSX and 'procstat -v' on BSD.
Report memory map of a process.
$ python examples/pmap.py 32402
pid=32402, name=hg
Address RSS Mode Mapping
0000000000400000 1200K r-xp /usr/bin/python2.7
0000000000838000 4K r--p /usr/bin/python2.7
0000000000839000 304K rw-p /usr/bin/python2.7
00000000008ae000 68K rw-p [anon]
000000000275e000 5396K rw-p [heap]
00002b29bb1e0000 124K r-xp /lib/x86_64-linux-gnu/ld-2.17.so
00002b29bb203000 8K rw-p [anon]
00002b29bb220000 528K rw-p [anon]
00002b29bb2d8000 768K rw-p [anon]
00002b29bb402000 4K r--p /lib/x86_64-linux-gnu/ld-2.17.so
00002b29bb403000 8K rw-p /lib/x86_64-linux-gnu/ld-2.17.so
00002b29bb405000 60K r-xp /lib/x86_64-linux-gnu/libpthread-2.17.so
00002b29bb41d000 0K ---p /lib/x86_64-linux-gnu/libpthread-2.17.so
00007fff94be6000 48K rw-p [stack]
00007fff94dd1000 4K r-xp [vdso]
ffffffffff600000 0K r-xp [vsyscall]
...
"""
import sys
@@ -14,20 +35,22 @@ import sys
import psutil
from psutil._compat import print_
def main():
if len(sys.argv) != 2:
sys.exit('usage: pmap pid')
sys.exit('usage: pmap <pid>')
p = psutil.Process(int(sys.argv[1]))
print_("pid=%s, name=%s" % (p.pid, p.name))
print_("pid=%s, name=%s" % (p.pid, p.name()))
templ = "%-16s %10s %-7s %s"
print_(templ % ("Address", "RSS", "Mode", "Mapping"))
total_rss = 0
for m in p.get_memory_maps(grouped=False):
for m in p.memory_maps(grouped=False):
total_rss += m.rss
print_(templ % (m.addr.split('-')[0].zfill(16),
str(m.rss / 1024) + 'K' ,
m.perms,
m.path))
print_(templ % (
m.addr.split('-')[0].zfill(16),
str(m.rss / 1024) + 'K',
m.perms,
m.path))
print_("-" * 33)
print_(templ % ("Total", str(total_rss / 1024) + 'K', '', ''))

View File

@@ -6,38 +6,63 @@
"""
Print detailed information about a process.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
$ python examples/process_detail.py
pid 820
name python
exe /usr/bin/python2.7
parent 29613 (bash)
cmdline python examples/process_detail.py
started 2014-41-27 03:41
user giampaolo
uids real=1000, effective=1000, saved=1000
gids real=1000, effective=1000, saved=1000
terminal /dev/pts/17
cwd /ssd/svn/psutil
memory 0.1% (resident=10.6M, virtual=58.5M)
cpu 0.0% (user=0.09, system=0.0)
status running
niceness 0
num threads 1
I/O bytes-read=0B, bytes-written=0B
open files
running threads id=820, user-time=0.09, sys-time=0.0
"""
import os
import datetime
import os
import socket
import sys
import psutil
POSIX = os.name == 'posix'
def convert_bytes(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n
def print_(a, b):
if sys.stdout.isatty() and os.name == 'posix':
fmt = '\x1b[1;32m%-17s\x1b[0m %s' %(a, b)
if sys.stdout.isatty() and POSIX:
fmt = '\x1b[1;32m%-17s\x1b[0m %s' % (a, b)
else:
fmt = '%-15s %s' %(a, b)
fmt = '%-15s %s' % (a, b)
# python 2/3 compatibility layer
sys.stdout.write(fmt + '\n')
sys.stdout.flush()
def run(pid):
ACCESS_DENIED = ''
try:
@@ -47,20 +72,21 @@ def run(pid):
sys.exit(str(sys.exc_info()[1]))
try:
if p.parent:
parent = '(%s)' % p.parent.name
parent = p.parent()
if parent:
parent = '(%s)' % parent.name()
else:
parent = ''
except psutil.Error:
parent = ''
started = datetime.datetime.fromtimestamp(pinfo['create_time']
).strftime('%Y-%M-%d %H:%M')
started = datetime.datetime.fromtimestamp(
pinfo['create_time']).strftime('%Y-%m-%d %H:%M')
io = pinfo.get('io_counters', ACCESS_DENIED)
mem = '%s%% (resident=%s, virtual=%s) ' % (
round(pinfo['memory_percent'], 1),
convert_bytes(pinfo['memory_info'].rss),
convert_bytes(pinfo['memory_info'].vms))
children = p.get_children()
round(pinfo['memory_percent'], 1),
convert_bytes(pinfo['memory_info'].rss),
convert_bytes(pinfo['memory_info'].vms))
children = p.children()
print_('pid', pinfo['pid'])
print_('name', pinfo['name'])
@@ -69,41 +95,42 @@ def run(pid):
print_('cmdline', ' '.join(pinfo['cmdline']))
print_('started', started)
print_('user', pinfo['username'])
if os.name == 'posix' and pinfo['uids'] and pinfo['gids']:
if POSIX and pinfo['uids'] and pinfo['gids']:
print_('uids', 'real=%s, effective=%s, saved=%s' % pinfo['uids'])
if os.name == 'posix' and pinfo['gids']:
if POSIX and pinfo['gids']:
print_('gids', 'real=%s, effective=%s, saved=%s' % pinfo['gids'])
if os.name == 'posix':
if POSIX:
print_('terminal', pinfo['terminal'] or '')
if hasattr(p, 'getcwd'):
print_('cwd', pinfo['cwd'])
print_('memory', mem)
print_('cpu', '%s%% (user=%s, system=%s)' % (pinfo['cpu_percent'],
getattr(pinfo['cpu_times'], 'user', '?'),
getattr(pinfo['cpu_times'], 'system', '?')))
print_('cpu', '%s%% (user=%s, system=%s)' % (
pinfo['cpu_percent'],
getattr(pinfo['cpu_times'], 'user', '?'),
getattr(pinfo['cpu_times'], 'system', '?')))
print_('status', pinfo['status'])
print_('niceness', pinfo['nice'])
print_('num threads', pinfo['num_threads'])
if io != ACCESS_DENIED:
print_('I/O', 'bytes-read=%s, bytes-written=%s' % \
(convert_bytes(io.read_bytes),
convert_bytes(io.write_bytes)))
print_('I/O', 'bytes-read=%s, bytes-written=%s' % (
convert_bytes(io.read_bytes),
convert_bytes(io.write_bytes)))
if children:
print_('children', '')
for child in children:
print_('', 'pid=%s name=%s' % (child.pid, child.name))
print_('', 'pid=%s name=%s' % (child.pid, child.name()))
if pinfo['open_files'] != ACCESS_DENIED:
print_('open files', '')
for file in pinfo['open_files']:
print_('', 'fd=%s %s ' % (file.fd, file.path))
print_('', 'fd=%s %s ' % (file.fd, file.path))
if pinfo['threads']:
print_('running threads', '')
for thread in pinfo['threads']:
print_('', 'id=%s, user-time=%s, sys-time=%s' \
% (thread.id, thread.user_time, thread.system_time))
if pinfo['connections'] != ACCESS_DENIED:
print_('', 'id=%s, user-time=%s, sys-time=%s' % (
thread.id, thread.user_time, thread.system_time))
if pinfo['connections'] not in (ACCESS_DENIED, []):
print_('open connections', '')
for conn in pinfo['connections']:
if conn.type == socket.SOCK_STREAM:
@@ -117,8 +144,9 @@ def run(pid):
rip, rport = '*', '*'
else:
rip, rport = conn.raddr
print_('', '%s:%s -> %s:%s type=%s status=%s' \
% (lip, lport, rip, rport, type, conn.status))
print_('', '%s:%s -> %s:%s type=%s status=%s' % (
lip, lport, rip, rport, type, conn.status))
def main(argv=None):
if argv is None:

View File

@@ -0,0 +1,81 @@
#!/usr/bin/env python
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A clone of 'ps -aux' on UNIX.
$ python examples/ps.py
...
"""
import datetime
import os
import time
import psutil
from psutil._compat import print_
def main():
today_day = datetime.date.today()
templ = "%-10s %5s %4s %4s %7s %7s %-13s %5s %7s %s"
attrs = ['pid', 'cpu_percent', 'memory_percent', 'name', 'cpu_times',
'create_time', 'memory_info']
if os.name == 'posix':
attrs.append('uids')
attrs.append('terminal')
print_(templ % ("USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY",
"START", "TIME", "COMMAND"))
for p in psutil.process_iter():
try:
pinfo = p.as_dict(attrs, ad_value='')
except psutil.NoSuchProcess:
pass
else:
if pinfo['create_time']:
ctime = datetime.datetime.fromtimestamp(pinfo['create_time'])
if ctime.date() == today_day:
ctime = ctime.strftime("%H:%M")
else:
ctime = ctime.strftime("%b%d")
else:
ctime = ''
cputime = time.strftime("%M:%S",
time.localtime(sum(pinfo['cpu_times'])))
try:
user = p.username()
except KeyError:
if os.name == 'posix':
if pinfo['uids']:
user = str(pinfo['uids'].real)
else:
user = ''
else:
raise
except psutil.Error:
user = ''
if os.name == 'nt' and '\\' in user:
user = user.split('\\')[1]
vms = pinfo['memory_info'] and \
int(pinfo['memory_info'].vms / 1024) or '?'
rss = pinfo['memory_info'] and \
int(pinfo['memory_info'].rss / 1024) or '?'
memp = pinfo['memory_percent'] and \
round(pinfo['memory_percent'], 1) or '?'
print_(templ % (user[:10],
pinfo['pid'],
pinfo['cpu_percent'],
memp,
vms,
rss,
pinfo.get('terminal', '') or '?',
ctime,
cputime,
pinfo['name'].strip() or '?'))
if __name__ == '__main__':
main()

View File

@@ -8,15 +8,39 @@
A clone of top / htop.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
$ python examples/top.py
CPU0 [| ] 4.9%
CPU1 [||| ] 7.8%
CPU2 [ ] 2.0%
CPU3 [||||| ] 13.9%
Mem [||||||||||||||||||| ] 49.8% 4920M/9888M
Swap [ ] 0.0% 0M/0M
Processes: 287 (running=1 sleeping=286)
Load average: 0.34 0.54 0.46 Uptime: 3 days, 10:16:37
PID USER NI VIRT RES CPU% MEM% TIME+ NAME
------------------------------------------------------------
989 giampaol 0 66M 12M 7.4 0.1 0:00.61 python
2083 root 0 506M 159M 6.5 1.6 0:29.26 Xorg
4503 giampaol 0 599M 25M 6.5 0.3 3:32.60 gnome-terminal
3868 giampaol 0 358M 8M 2.8 0.1 23:12.60 pulseaudio
3936 giampaol 0 1G 111M 2.8 1.1 33:41.67 compiz
4401 giampaol 0 536M 141M 2.8 1.4 35:42.73 skype
4047 giampaol 0 743M 76M 1.8 0.8 42:03.33 unity-panel-service
13155 giampaol 0 1G 280M 1.8 2.8 41:57.34 chrome
10 root 0 0B 0B 0.9 0.0 4:01.81 rcu_sched
339 giampaol 0 1G 113M 0.9 1.1 8:15.73 chrome
...
"""
import os
import sys
if os.name != 'posix':
sys.exit('platform not supported')
import time
import curses
import atexit
import curses
import time
from datetime import datetime, timedelta
import psutil
@@ -34,6 +58,7 @@ atexit.register(tear_down)
curses.endwin()
lineno = 0
def print_line(line, highlight=False):
"""A thin wrapper around curses's addstr()."""
global lineno
@@ -62,13 +87,14 @@ def bytes2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = int(float(n) / prefix[s])
return '%s%s' % (value, s)
return "%sB" % n
def poll(interval):
# sleep some time
time.sleep(interval)
@@ -76,32 +102,35 @@ def poll(interval):
procs_status = {}
for p in psutil.process_iter():
try:
p.dict = p.as_dict(['username', 'get_nice', 'get_memory_info',
'get_memory_percent', 'get_cpu_percent',
'get_cpu_times', 'name', 'status'])
p.dict = p.as_dict(['username', 'nice', 'memory_info',
'memory_percent', 'cpu_percent',
'cpu_times', 'name', 'status'])
try:
procs_status[str(p.dict['status'])] += 1
procs_status[p.dict['status']] += 1
except KeyError:
procs_status[str(p.dict['status'])] = 1
procs_status[p.dict['status']] = 1
except psutil.NoSuchProcess:
pass
else:
procs.append(p)
# return processes sorted by CPU percent usage
processes = sorted(procs, key=lambda p: p.dict['cpu_percent'], reverse=True)
processes = sorted(procs, key=lambda p: p.dict['cpu_percent'],
reverse=True)
return (processes, procs_status)
def print_header(procs_status, num_procs):
"""Print system-related info, above the process list."""
def get_dashes(perc):
dashes = "|" * int((float(perc) / 10 * 4))
dashes = "|" * int((float(perc) / 10 * 4))
empty_dashes = " " * (40 - len(dashes))
return dashes, empty_dashes
# cpu usage
for cpu_num, perc in enumerate(psutil.cpu_percent(interval=0, percpu=True)):
percs = psutil.cpu_percent(interval=0, percpu=True)
for cpu_num, perc in enumerate(percs):
dashes, empty_dashes = get_dashes(perc)
print_line(" CPU%-2s [%s%s] %5s%%" % (cpu_num, dashes, empty_dashes,
perc))
@@ -135,12 +164,13 @@ def print_header(procs_status, num_procs):
st.sort(key=lambda x: x[:3] in ('run', 'sle'), reverse=1)
print_line(" Processes: %s (%s)" % (num_procs, ' '.join(st)))
# load average, uptime
uptime = datetime.now() - datetime.fromtimestamp(psutil.BOOT_TIME)
uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time())
av1, av2, av3 = os.getloadavg()
line = " Load average: %.2f %.2f %.2f Uptime: %s" \
% (av1, av2, av3, str(uptime).split('.')[0])
% (av1, av2, av3, str(uptime).split('.')[0])
print_line(line)
def refresh_window(procs, procs_status):
"""Print results on screen by using curses."""
curses.endwin()
@@ -154,7 +184,7 @@ def refresh_window(procs, procs_status):
for p in procs:
# TIME+ column shows process CPU cumulative time and it
# is expressed as: "mm:ss.ms"
if p.dict['cpu_times'] != None:
if p.dict['cpu_times'] is not None:
ctime = timedelta(seconds=sum(p.dict['cpu_times']))
ctime = "%s:%s.%s" % (ctime.seconds // 60 % 60,
str((ctime.seconds % 60)).zfill(2),

View File

@@ -7,9 +7,14 @@
"""
A clone of 'who' command; print information about users who are
currently logged in.
$ python examples/who.py
giampaolo tty7 2014-02-23 17:25 (:0)
giampaolo pts/7 2014-02-24 18:25 (:192.168.1.56)
giampaolo pts/8 2014-02-24 18:25 (:0)
giampaolo pts/9 2014-02-27 01:32 (:0)
"""
import sys
from datetime import datetime
import psutil
@@ -17,14 +22,13 @@ from psutil._compat import print_
def main():
users = psutil.get_users()
users = psutil.users()
for user in users:
print_("%-15s %-15s %s (%s)" % \
(user.name,
user.terminal or '-',
datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"),
user.host)
)
print_("%-15s %-15s %s (%s)" % (
user.name,
user.terminal or '-',
datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"),
user.host))
if __name__ == '__main__':
main()