Skip to content

Instantly share code, notes, and snippets.

@snim2
Created January 21, 2012 12:25
Show Gist options
  • Save snim2/1652633 to your computer and use it in GitHub Desktop.
Save snim2/1652633 to your computer and use it in GitHub Desktop.
Parse the output of the Ubuntu sensors utility
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script parses the output of the Ubuntu 'sensors' utility.
The output of sensors looks like this on my machine:
acpitz-virtual-0
Adapter: Virtual device
temp1: +56.0°C (crit = +107.0°C)
coretemp-isa-0000
Adapter: ISA adapter
Core 0: +50.0°C (high = +95.0°C, crit = +105.0°C)
Core 2: +50.0°C (high = +95.0°C, crit = +105.0°C)
Typical output:
{'core2': (57.0, 95.0, 105.0), 'core1': (56.0, 95.0, 105.0), 'acpi': (52.0, 107.0)}
If you want to adapt this for your own machine you may have
to make some adjustments to the reg exps.
Thanks to the folks on SO for Unicode advice:
http://stackoverflow.com/questions/8952430/
"""
import locale
import re
import subprocess
# Could be more belt and braces by getting this information
# from `which` rather than hard-coding a path.
SENSORS = '/usr/bin/sensors'
def parse():
temps = {'temp1':None, 'core1':None, 'core2':None}
temp_re = re.compile(ur'(temp1:)\s+(\+|-)(\d+\.\d+)°C\s+' +
ur'\(crit\s+=\s+(\+|-)(\d+\.\d+)°C\).*',
flags=re.UNICODE)
core_re = re.compile(ur'Core (\d):\s+' +
ur'(\+|-)(\d+\.\d+)°C\s+'
ur'\(high\s+=\s+(\+|-)(\d+\.\d+)°C, ' +
ur'crit\s+=\s+(\+|-)(\d+\.\d+)°C\).*',
flags=re.UNICODE)
# Should really be in a try / except.
data = subprocess.check_output(SENSORS).decode(locale.getpreferredencoding())
for line in data.split('\n'):
if line.startswith('temp1'):
match = re.match(temp_re, line)
if match:
temp, crit = float(match.group(3)), float(match.group(5))
temps['acpi'] = (temp, crit)
elif line.startswith('Core 0') or line.startswith('Core 2'):
match = re.match(core_re, line)
if match:
temp, high, crit = (float(match.group(3)),
float(match.group(5)),
float(match.group(7)))
if match.group(1) == '0':
temps['core1'] = (temp, high, crit)
else:
temps['core2'] = (temp, high, crit)
return temps
if __name__ == '__main__':
print parse()
# Typical output:
# {'core2': (57.0, 95.0, 105.0), 'core1': (56.0, 95.0, 105.0), 'acpi': (52.0, 107.0)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment