Python wrapper to take the pain out of the units command

17:04, Sunday August 22nd, 2004 • feeling relaxed

#!/usr/bin/python

"""Wrap the standard Unix units command but do the calculation as well.
Arguments are the amount, the from-unit and the to-unit"""

import os, sys

a = sys.argv
if (len(a) < 4):
    print "usage: convert.py quantity from-units to-units"
    sys.exit()

cmd = "/usr/bin/units"
pipe = os.popen("%s -q %s %s" % (cmd, a[2], a[3]))

try:
    numberpart = lambda x: float(x.readline().strip()[2:])
    mult, div = numberpart(pipe), numberpart(pipe)
    print "%0.3f %s = %0.3f %s" % \
            (float(a[1]), a[2], float(a[1]) * mult, a[3])

except ValueError, e:
    message = str(e).split(":")
    unit = message[len(message) - 1].split(" ")
    print "Unknown unit: \"%s\"" % unit[len(unit) - 1].strip()[1:-1]

Tomsky says...

time: 4:04, Monday August 23rd, 2004 • email: thomas AT noise DOT org DOT uk

Nice python code, but doesn't command ./units "quantity from-unit" "to-unit", work just as well?

Afternoon says...

time: 15:13, Monday August 23rd, 2004 • email: noon AT aftnn DOT org

Damn, yes. Arses. Thanks for the knowledge though.

Permanent link

If you would like to link to this entry, it will always be available at http://aftnn.org/journal/534.

aftnn.orgafternoon's journal → entry 534