You were on the right track using re
; your best bet (assuming the decimal can be arbitrary, etc.) is something like this:
import re
def temp():
command = "/opt/vc/bin/vcgencmd measure_temp"
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
output = proc.stdout.read()
# Build the regex. Use () to capture the group; we want any number of
# digits \d or decimal points \. that is preceded by temp= and
# followed by 'C
temp_regex = re.compile(r'temp=([\d\.]*)\'C')
matches = re.findall(temp_regex, output) # now matches = ['54.1']
temp = float(matches[0])
return temp
The regex captures any combination of numbers and decimal places (e.g. 12.34.56
would get matched); you could restrict it if necessary to only allow a single decimal place, but that's more work than it appears to be worth, if you can trust that the data you're getting back is well-formed. If you do want the number to be more precise, you could compile the regex like this (for at least one numeral preceding the decimal place and exactly one following it):
temp_regex = re.compile(r'temp=(\d+.\d)\'C')
Again, we capture the expression using the parentheses (captured groups are returned by findall), but this time, increase the specificity of what we're looking for. This will capture any number like 123.4
but not .4
and not 123.
If you find that you need to broaden it out a bit but still want only one decimal place:
temp_regex = re.compile(r'temp=(\d+.\d+)\'C')
That will capture any number with at least one numeral proceeding and following the decimal, so 1234.5678
would match but 1234.
would not and .1234
would not.
As an alternative to using re.findall()
, you might use re.match()
, which returns match objects. Then your usage would look something like this (using the direct method, rather than pre-compiling the string:
match = re.match(r'temp=(\d+.\d+)\'C', output)
if match:
temp = float(match.group(1)) # get the first matching group captured by ()
else:
pass # You should add some error handling here
One of the things this makes clearer than the way I had re.findall()
above is that if nothing is captured, you have an issue, and you need to figure out how to handle it.
You can look at other ways to vary that up at Regular-Expressions.info, easily the best site I've found on the web for a quick resource on the topic.