#!/usr/bin/env python3 import time import sys def read_file(filename): with open(filename) as f: return f.read() def read_cpu_idle_jiffys(procstat): line = procstat.split("\n")[0] fields = line.split() return int(fields[4]) def count_cpus(procstat): count = -1 for line in procstat.split("\n"): if line.startswith("cpu"): count += 1 return count def read_cpu_percent(): procstat = read_file("/proc/stat") num_cpus = count_cpus(procstat) tstart = time.time() idle_jiffy1 = read_cpu_idle_jiffys(procstat) time.sleep(0.1) idle_jiffy2 = read_cpu_idle_jiffys(read_file("/proc/stat")) tend = time.time() duration = tend - tstart idle_jiffys_per_second = (idle_jiffy2 - idle_jiffy1) / duration idle_jiffys_per_cpu_second = idle_jiffys_per_second / num_cpus # One jiffy is 10ms, so we can get the percentage very easily! return 100 - idle_jiffys_per_cpu_second def read_mem_percent(): meminfo = read_file("/proc/meminfo") d = {} for line in meminfo.strip().split("\n"): key, value = line.split()[:2] d[key] = int(value) mem_total = d["MemTotal:"] mem_free = d["MemAvailable:"] mem_used = mem_total - mem_free return mem_used / mem_total * 100 def write(s): sys.stdout.write(s) def print_percent(name, units, value, red_threshold): if value > red_threshold: color = "red" else: color = "black" write( "%s %s%s " % (name, color, value, units) ) def main(): write("") print_percent( "cpu", "%", round(read_cpu_percent()), red_threshold=50, ) print_percent( "mem", "%", round(read_mem_percent()), red_threshold=70, ) write("") if __name__ == "__main__": main()