Last active
August 29, 2015 14:05
-
-
Save manics/ec924e0dc33cc07b4818 to your computer and use it in GitHub Desktop.
ASCII/terminal CPU usage graph. Bars are split into coloured blocks for each CPU if termcolor module is available, otherwise a single bar is shown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import math | |
import os | |
import psutil | |
import sys | |
import time | |
try: | |
import termcolor | |
TERMCOLORS = termcolor.COLORS.keys() | |
except ImportError: | |
TERMCOLORS = None | |
def get_term_size(): | |
import fcntl | |
import struct | |
import termios | |
return struct.unpack('hh', fcntl.ioctl(os.open( | |
os.ctermid(), os.O_RDONLY), termios.TIOCGWINSZ, '0000')) | |
def get_bars(ps, scale): | |
cps = [0] | |
for p in ps: | |
cps.append(p * scale + cps[-1]) | |
icps = [math.ceil(c) for c in cps] | |
bars = [int(a - b) for a, b in zip(icps[1:], icps[:-1]) if a > b] | |
return bars | |
def color(text, i): | |
if TERMCOLORS: | |
return termcolor.colored(text, TERMCOLORS[i % len(TERMCOLORS)], | |
'on_' + TERMCOLORS[(i + 1) % len(TERMCOLORS)]) | |
return text | |
try: | |
w = get_term_size()[1] | |
scale = (w - 7) / 100.0 | |
except Exception: | |
scale = 1.0 | |
if len(sys.argv) > 1: | |
interval = int(sys.argv[1]) | |
else: | |
interval = 2 | |
ps = sorted(psutil.cpu_percent(percpu=True), reverse=True) | |
while True: | |
time.sleep(interval) | |
ps = sorted(psutil.cpu_percent(percpu=True), reverse=True) | |
bars = sorted(get_bars(ps, scale / len(ps)), reverse=True) | |
s = '%5.1f ' % (sum(ps) / len(ps)) | |
for n in xrange(len(bars)): | |
s += color('#' * bars[n], n) | |
print s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment