]> code.delx.au - dotfiles/blob - bin/xfce4-genmon-script
d892bec04462a1e2296fa8a3a1aea8dba2845e73
[dotfiles] / bin / xfce4-genmon-script
1 #!/usr/bin/env python3
2
3 import time
4 import subprocess
5 import sys
6
7 def read_file(filename):
8 with open(filename) as f:
9 return f.read()
10
11 def read_cpu_idle_jiffys(procstat):
12 line = procstat.split("\n")[0]
13 fields = line.split()
14 return int(fields[4])
15
16 def count_cpus(procstat):
17 count = -1
18 for line in procstat.split("\n"):
19 if line.startswith("cpu"):
20 count += 1
21 return count
22
23 def read_cpu_percent():
24 procstat = read_file("/proc/stat")
25 num_cpus = count_cpus(procstat)
26
27 tstart = time.time()
28 idle_jiffy1 = read_cpu_idle_jiffys(procstat)
29 time.sleep(0.1)
30 idle_jiffy2 = read_cpu_idle_jiffys(read_file("/proc/stat"))
31 tend = time.time()
32
33 duration = tend - tstart
34 idle_jiffys_per_second = (idle_jiffy2 - idle_jiffy1) / duration
35
36 idle_jiffys_per_cpu_second = idle_jiffys_per_second / num_cpus
37
38 # One jiffy is 10ms, so we can get the percentage very easily!
39 return 100 - idle_jiffys_per_cpu_second
40
41 def read_mem_percent():
42 meminfo = read_file("/proc/meminfo")
43
44 d = {}
45 for line in meminfo.strip().split("\n"):
46 key, value = line.split()[:2]
47 d[key] = int(value)
48
49 mem_total = d["MemTotal:"]
50 mem_free = d["MemAvailable:"]
51 mem_used = mem_total - mem_free
52
53 return mem_used / mem_total * 100
54
55 def read_battery_percent():
56 args = ["upower", "--show-info", "/org/freedesktop/UPower/devices/DisplayDevice"]
57 with subprocess.Popen(args, stdout=subprocess.PIPE) as process:
58 upower_data, _ = process.communicate()
59 if process.poll() != 0:
60 return
61
62 for line in upower_data.decode("ascii").split("\n"):
63 line = line.strip()
64 if line.startswith("percentage:"):
65 percent_str = line.split()[1]
66 return int(percent_str.replace("%", ""))
67
68 def write(s):
69 sys.stdout.write(s)
70
71 def print_percent(name, units, value, color_map):
72 if value is None:
73 return
74
75 value = round(value)
76
77 for low, high, color in color_map:
78 if value >= low and value <= high:
79 break
80 else:
81 color = "black"
82
83 write(
84 "%s <span color='%s'>%s</span>%s " %
85 (name, color, value, units)
86 )
87
88 def main():
89 write("<txt>")
90
91 print_percent(
92 "cpu", "%",
93 read_cpu_percent(),
94 color_map=[(50, 100, "red"), (0, 5, "green")],
95 )
96
97 print_percent(
98 "mem", "%",
99 read_mem_percent(),
100 color_map=[(70, 100, "red")],
101 )
102
103 print_percent(
104 "batt", "%",
105 read_battery_percent(),
106 color_map=[(0, 25, "red")],
107 )
108
109 write("</txt>")
110
111 if __name__ == "__main__":
112 main()