CPU Temperature Overlay on X11 with Python: Cross-Platform Monitoring
A ~120-line Python script monitors CPU temperature and overlays text directly onto the X11 desktop. It uses the python-xlib library to draw on the root window or Desktop window without requiring elevated privileges. Supports FreeBSD (via sysctl with coretemp/amdtemp modules) and Linux (/sys/class/thermal). Updates every 15 seconds and clears the display area on Ctrl-C.
Reading Sensor Data
On FreeBSD, temperature is accessible via sysctl after loading kernel modules:
- Intel:
kldload coretemp, readsysctl dev.cpu |grep temperature - AMD:
kldload amdtemp, readsysctl dev.amdtemp.0 |grep core
On Linux, use sysfs:
cat /sys/class/thermal/thermal_zone*/temp
Values are in millidegrees Celsius (divide by 1000). The script parses output from subprocess.Popen, formats temperatures into a comma-separated string.
Working with the X Server
The key trick: drawing in other windows without notification. Xlib enables:
- Retrieve the root window or Desktop window via _NET_CLIENT_LIST.
- Create a GC (graphics context) with white text on black background.
- Clear the area with fill_rectangle before rendering.
- Draw text using a fixed-width font with draw_text.
The get_root_window function scans top-level windows, looks for 'Desktop' in WM_NAME (KDE/Xfce). Fallback is the root window.
Full Source Code
Self-executing script (.sh with shebang). Only dependency: python-xlib.
#!/usr/bin/env python3
import Xlib
from Xlib import display, X # display and X are not imported automatically
import subprocess,time,logging
# logging configuration
logging.basicConfig(level=logging.INFO)
#logging.basicConfig(level=logging.DEBUG)
# screen coordinates for overlay
POS_X = 150
POS_Y = 50
# for FreeBSD and AMD systems
PATTERN = 'sysctl dev.amdtemp.0 |grep core'
# for FreeBSD with coretemp module
#PATTERN = 'sysctl dev.cpu |grep temperature'
# for Linux
#PATTERN = "cat /sys/class/thermal/thermal_zone*/temp | awk '{ print "temp: " ($1 / 1000) "C" }'"
# font
FONT = '-misc-fixed-medium-r-normal--13-120-75-75-c-70-iso8859-1'
# refresh interval
REFRESH_SECS = 15
last_dim = [0,0]
def get_root_window(d):
screen = d.screen()
root = screen.root
windowIDs = root.get_full_property(d.intern_atom('_NET_CLIENT_LIST'),
X.AnyPropertyType).value
logging.debug('Found %d windows.',len(windowIDs))
for windowID in windowIDs:
window = d.create_resource_object('window', windowID)
try:
window_name = window.get_wm_name()
if window_name:
if 'Desktop' in window_name:
logging.debug("Found desktop ID: %d - Name: %s",
windowID,window_name)
return window
else:
logging.debug("ID: %d - Name: None (no WM_NAME property)",
windowID)
except X.BadWindow:
logging.debug("ID: %d - Window no longer exists",windowID)
return root
def clear_rect(msg):
global last_dim
if last_dim[0] > 0:
root.fill_rectangle(gc2, POS_X,POS_Y-last_dim[1],
last_dim[0]-20, last_dim[1]+5)
else:
text_extents = font.query_text_extents(msg)
tw = text_extents.overall_width
th = text_extents.font_ascent + text_extents.font_descent
root.fill_rectangle(gc2, POS_X, POS_Y-th, tw-20, th+5)
last_dim = [tw,th]
def draw_message(msg):
clear_rect(msg)
root.draw_text(gc, POS_X, POS_Y, msg)
display.flush()
display = Xlib.display.Display()
screen = display.screen()
root = get_root_window(display)
root_id = root.id
logging.debug("Root window ID: %d",root_id)
root.change_attributes(event_mask=X.ExposureMask)
gc = root.create_gc(foreground = screen.white_pixel,
background = screen.black_pixel)
colormap = screen.default_colormap
color = colormap.alloc_named_color('black')
gc2 = root.create_gc(foreground=color.pixel)
try:
font = display.open_font(FONT)
gc.font = font.id
except Exception as e:
logging.exception(e)
exit(1)
try:
while 1:
process = subprocess.Popen(PATTERN,
shell=True, text=True,
stdout=subprocess.PIPE)
stdout_list = process.communicate()[0].split('\n')
out = ''
for s in stdout_list:
if ':' not in s: continue
kv = s.split(':')
if len(out) > 0: out+= ','
out+= kv[1]
logging.debug(out)
draw_message(out.encode())
time.sleep(REFRESH_SECS)
except KeyboardInterrupt:
x = POS_X // 2
y = POS_Y // 2
root.clear_area(x,y,last_dim[0]+x,last_dim[1]+y,True)
display.flush()
Customizing Settings
All constants are at the top of the script:
POS_X,POS_Y: overlay position on screen.PATTERN: sensor command (adjust per platform).FONT: X11 font in XLFD format.REFRESH_SECS: update frequency.- Logging: set to INFO or DEBUG.
Install python-xlib:
- FreeBSD:
pkg install py311-python-xlib - Linux: install
python3-xlibvia apt/yum
Key Highlights
- Cross-platform: Works on FreeBSD/Linux, Intel/AMD, no Wayland.
- Minimalist: Just 120 lines, no OOP/threads, single dependency.
- X11 hack: Draws on root/Desktop without permissions or visual indicators.
- Cleanup: Uses fill_rectangle and clear_area on exit.
- Parsing: Relies on subprocess + split for sysctl/sysfs data.
— Editorial Team
No comments yet.