Best method for a menu in a command line program?

Michele Simionato michele.simionato at gmail.com
Thu Nov 4 06:40:55 EDT 2010


On Nov 4, 2:19 am, braden faulkner <brf... at gmail.com> wrote:
> I'm using a menu for my command line app using this method.
>
> choice = "foobar"
> while choice != "q":
>     if choice == "c":
>         temp = input("Celsius temperature:")
>         print "Fahrenheit:",celsius_to_fahrenheit(temp)
>     elif choice == "f":
>         temp = input("Fahrenheit temperature:")
>         print "Celsius:",fahrenheit_to_celsius(temp)
>     elif choice != "q":
>         print_options()
>     choice = raw_input("option:")
>
> Just wondering if there is another or more efficient way I should be doing it?
>
> Thanks
> -- Braden Faulkner

Here is a solution using plac (http://pypi.python.org/pypi/plac):

$ echo c2f.py

import plac

class Converter(object):
    commands = ['celsius_to_fahrenheit', 'fahrenheit_to_celsius']

    @plac.annotations(t='convert Celsius to Fahrenheit')
    def celsius_to_fahrenheit(self, t):
        return round(32 + float(t) * 9/5)

    @plac.annotations(t='convert Fahrenheit to Celsius')
    def fahrenheit_to_celsius(self, t):
        return round((float(t) - 32) * 5 / 9.0)

if __name__ == '__main__':
    import plac; plac.Interpreter.call(Converter)


Here is an example of non-interactive usage:

$ python c2f.py fahrenheit_to_celsius 212
100.0
$ python c2f.py celsius_to_fahrenheit 100
212.0

Here is an example of interactive usage:$ python c2f.py -i

i> celsius_to_fahrenheit 100
212.0
i> celsius_to_fahrenheit 0
32.0
i> fahrenheit_to_celsius 32
0.0
i> fahrenheit_to_celsius 212
100.0




More information about the Python-list mailing list