3
# $Id: iotop.py 1213 2011-10-29 03:30:41Z g.rodola $
5
# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
6
# Use of this source code is governed by a BSD-style license that can be
7
# found in the LICENSE file.
10
A clone of iotop (http://guichaz.free.fr/iotop/) showing real time
13
It works on Linux only (FreeBSD and OSX are missing support for IO
15
It doesn't work on Windows as curses module is required.
17
Author: Giampaolo Rodola' <g.rodola@gmail.com>
23
if not hasattr(psutil.Process, 'get_io_counters') or os.name != 'posix':
24
sys.exit('platform not supported')
37
win = curses.initscr()
38
atexit.register(tear_down)
42
def print_line(line, highlight=False):
43
"""A thin wrapper around curses's addstr()."""
47
line += " " * (win.getmaxyx()[1] - len(line))
48
win.addstr(lineno, 0, line, curses.A_REVERSE)
50
win.addstr(lineno, 0, line, 0)
62
>>> bytes2human(10000)
64
>>> bytes2human(100001221)
67
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
69
for i, s in enumerate(symbols):
70
prefix[s] = 1 << (i+1)*10
71
for s in reversed(symbols):
73
value = float(n) / prefix[s]
74
return '%.2f %s/s' % (value, s)
78
"""Calculate IO usage by comparing IO statics before and
80
Return a tuple including all currently running processes
81
sorted by IO activity and total disks I/O activity.
83
# first get a list of all processes and disk io counters
84
procs = [p for p in psutil.process_iter()]
87
p._before = p.get_io_counters()
91
disks_before = psutil.disk_io_counters()
96
# then retrieve the same info again
99
p._after = p.get_io_counters()
100
p._cmdline = ' '.join(p.cmdline)
103
p._username = p.username
104
except psutil.NoSuchProcess:
106
disks_after = psutil.disk_io_counters()
108
# finally calculate results by comparing data before and
111
p._read_per_sec = p._after.read_bytes - p._before.read_bytes
112
p._write_per_sec = p._after.write_bytes - p._before.write_bytes
113
p._total = p._read_per_sec + p._write_per_sec
115
disks_read_per_sec = disks_after.read_bytes - disks_before.read_bytes
116
disks_write_per_sec = disks_after.write_bytes - disks_before.write_bytes
118
# sort processes by total disk IO so that the more intensive
119
# ones get listed first
120
processes = sorted(procs, key=lambda p: p._total, reverse=True)
122
return (processes, disks_read_per_sec, disks_write_per_sec)
125
def refresh_window(procs, disks_read, disks_write):
126
"""Print results on screen by using curses."""
128
templ = "%-5s %-7s %11s %11s %s"
131
disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \
132
% (bytes2human(disks_read), bytes2human(disks_write))
133
print_line(disks_tot)
135
header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
136
print_line(header, highlight=True)
139
line = templ % (p.pid,
141
bytes2human(p._read_per_sec),
142
bytes2human(p._write_per_sec),
154
args = poll(interval)
155
refresh_window(*args)
157
except (KeyboardInterrupt, SystemExit):
160
if __name__ == '__main__':