3

My script runs the C program digitemp. The output is in rows containing the sensor ID and the temperature. I need to match the sensor ID with a particular name thus all the elifs. I have used first, second third in this example as the names to math the ID's. Is there any way to reduce all the elif statements as there are more to be added?

import os

# get digitemps output
cmd = "/bin/digitemp_ -c /bin/digitemp.conf -q -a"

def digitemps():
    for outline in os.popen(cmd).readlines():
        outline = outline[:-1].split()
        if outline[0] == '28F4F525030000D1':
            temp_ = outline[1]
            print 'first ' + temp_
        elif outline[0] == '28622A260300006B':
            temp_ = outline[1]
            print 'second ' + temp_
        elif outline[0] == '28622A2603000080':
            temp_ = outline[1]
            print 'third ' + temp_

digitemps()
bob_the_bob
  • 345
  • 1
  • 13
  • Aside #1: you don't need `.readlines()` here; the code will work as well without it. Aside #2: you don't need the `[:-1]`; `.split()` will automatically strip trailing whitespace, and `[:-1]` is a little dangerous in general as sometimes files are missing a CR on the very last line. [For example, in Python, people sometimes do things like `'\n'.join(some_strings)`, which doesn't add a trailing `\n`.] – DSM Apr 14 '13 at 19:51

2 Answers2

4

Use a dictionary to map from sensor ID to a human-readable name:

id_to_name = {"28F4F525030000D1": "first",
              "28622A260300006B": "second",
              "28622A2603000080", "third"}
print id_to_name.get(outline[0], outline[0]) + outline[1]

The advantage of this approach is that the get method will return the ID without any change if there is no human-readable name assigned to it.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
Tamás
  • 47,239
  • 12
  • 105
  • 124
  • 2
    A bit offtopic: why do you prefer `dict(tuples)` to a literal? – bereal Apr 14 '13 at 19:49
  • 2
    The backslashes are definitely useless. Apart from that (I think this is what bereal is getting at) `{"28F4F525030000D1": "first", ...}` is the more common and IMHO readable syntax. –  Apr 14 '13 at 19:54
  • This isn't valid syntax. `dict` will accept an iterable of tuples, but as written it'll raise a `TypeError: dict expected at most 1 arguments, got 3` exception. – DSM Apr 14 '13 at 19:54
  • @delnan: ah yes, that could have been an option, sure. My bad. – Tamás Apr 14 '13 at 19:57
0

Most of the logic inside the loop can be written using generator expressions, this is code is equivalent and takes into account @DSM's advice in the comments:

d = {'28F4F525030000D1':'first ',
     '28622A260300006B':'second ',
     '28622A2603000080':'third '}

def digitemps():
  for s in (d.get(x[0],x[0]) + x[1] for x in (e.split() for e in os.popen(cmd))):
    print s
Óscar López
  • 232,561
  • 37
  • 312
  • 386