+++ /dev/null
-#!/usr/bin/env python3
-
-import time
-import subprocess
-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 read_battery_percent():
- args = ["upower", "--show-info", "/org/freedesktop/UPower/devices/DisplayDevice"]
- with subprocess.Popen(args, stdout=subprocess.PIPE) as process:
- upower_data, _ = process.communicate()
- if process.poll() != 0:
- return
-
- for line in upower_data.decode("ascii").split("\n"):
- line = line.strip()
- if line.startswith("percentage:"):
- percent_str = line.split()[1]
- return int(percent_str.replace("%", ""))
-
-def write(s):
- sys.stdout.write(s)
-
-def print_percent(name, units, value, color_map):
- if value is None:
- return
-
- value = round(value)
-
- for low, high, color in color_map:
- if value >= low and value <= high:
- break
- else:
- color = "black"
-
- write(
- "%s <span color='%s'>%s</span>%s " %
- (name, color, value, units)
- )
-
-def main():
- write("<txt>")
-
- print_percent(
- "cpu", "%",
- read_cpu_percent(),
- color_map=[(50, 100, "red"), (0, 5, "green")],
- )
-
- print_percent(
- "mem", "%",
- read_mem_percent(),
- color_map=[(70, 100, "red")],
- )
-
- print_percent(
- "batt", "%",
- read_battery_percent(),
- color_map=[(0, 25, "red")],
- )
-
- write("</txt>")
-
-if __name__ == "__main__":
- main()