7 def read_file(filename
):
8 with
open(filename
) as f
:
11 def read_cpu_idle_jiffys(procstat
):
12 line
= procstat
.split("\n")[0]
16 def count_cpus(procstat
):
18 for line
in procstat
.split("\n"):
19 if line
.startswith("cpu"):
23 def read_cpu_percent():
24 procstat
= read_file("/proc/stat")
25 num_cpus
= count_cpus(procstat
)
28 idle_jiffy1
= read_cpu_idle_jiffys(procstat
)
30 idle_jiffy2
= read_cpu_idle_jiffys(read_file("/proc/stat"))
33 duration
= tend
- tstart
34 idle_jiffys_per_second
= (idle_jiffy2
- idle_jiffy1
) / duration
36 idle_jiffys_per_cpu_second
= idle_jiffys_per_second
/ num_cpus
38 # One jiffy is 10ms, so we can get the percentage very easily!
39 return 100 - idle_jiffys_per_cpu_second
41 def read_mem_percent():
42 meminfo
= read_file("/proc/meminfo")
45 for line
in meminfo
.strip().split("\n"):
46 key
, value
= line
.split()[:2]
49 mem_total
= d
["MemTotal:"]
50 mem_free
= d
["MemAvailable:"]
51 mem_used
= mem_total
- mem_free
53 return mem_used
/ mem_total
* 100
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:
62 for line
in upower_data
.decode("ascii").split("\n"):
64 if line
.startswith("percentage:"):
65 percent_str
= line
.split()[1]
66 return int(percent_str
.replace("%", ""))
71 def print_percent(name
, units
, value
, color_map
):
77 for low
, high
, color
in color_map
:
78 if value
>= low
and value
<= high
:
84 "%s <span color='%s'>%s</span>%s " %
85 (name
, color
, value
, units
)
94 color_map
=[(50, 100, "red"), (0, 5, "green")],
100 color_map
=[(70, 100, "red")],
105 read_battery_percent(),
106 color_map
=[(0, 25, "red")],
111 if __name__
== "__main__":