Best method for a menu in a command line program?

Peter Otten __peter__ at web.de
Thu Nov 4 07:49:01 EDT 2010


braden faulkner 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?

The user interface will be slightly different, but the cmd module is great 
to build simple interactive command line apps quickly:

# -*- coding: utf-8 -*-
from __future__ import division
import cmd

class Cmd(cmd.Cmd):
    prompt = "Enter a command (? for help) --> "
    def do_celsius_to_fahrenheit(self, value):
        """Convert Celsius to Fahrenheit"""
        celsius = float(value)
        print u"%f °F" % (celsius * 9/5 + 32)
    def do_fahrenheit_to_celsius(self, value):
        fahrenheit = float(value)
        print u"%f °C" % ((fahrenheit - 32) * 5/9)
    def do_quit(self, value):
        return True
    do_EOF = do_quit

Cmd().cmdloop()

A sample session:

$ python convert_temperature.py
Enter a command (? for help) --> ?

Documented commands (type help <topic>):
========================================
celsius_to_fahrenheit

Undocumented commands:
======================
EOF  fahrenheit_to_celsius  help  quit

Enter a command (? for help) --> ? celsius_to_fahrenheit
Convert Celsius to Fahrenheit
Enter a command (? for help) --> celsius_to_fahrenheit 0
32.000000 °F
Enter a command (? for help) --> fahrenheit_to_celsius 212
100.000000 °C
Enter a command (? for help) --> quit
$

Peter



More information about the Python-list mailing list