Best method for a menu in a command line program?

  • Thread starter braden faulkner
  • Start date
B

braden faulkner

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
 
R

rantingrick

Just wondering if there is another or more efficient way I should be doing it?


I would move the input inside the respective methods or functions,
short of that, what is more efficient than a conditional... nothing,
and it reads very intuitively. Sure you could throw all the funcs into
a dict and it may clean up a long winded conditional, however then you
have to make a trade. So Zero Sum at that point.
 
T

Tim Harig

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?

You are looking for a dictionary with function references maybe?

menu_options = {
'c':io_celsius_to_fahrenheit,
'f':io_fahrenheit_to_celsisus,
'q':print_options
}

The io versions of the functions would wrap the conversion functions to get
the input and print the output.

choice = "foobar"
while choice != 'q':
try:
menu_options[choice]()
except KeyError:
# else code here
choice = raw_input("option:")
 
C

Carl Banks

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?

You're not even close to the point where you have to start worrying
about efficiency.

If you're at a point where efficiency matters, then by that point you
should have long ago refactored it into a function-call dispatch
(which is what others have posted) for the sake of organizing code.

For this program, what you have it fine.


Carl Banks
 
A

Arnaud Delobelle

Ben Finney said:
commands = {
'q': (lambda: quit()),
'c': (lambda: prompt_and_convert_temperature(
["Celsius", "Fahrenheit"], celsius_to_fahrenheit)),
'f': (lambda: prompt_and_convert_temperature(
["Fahrenheit", "Celsius"], fahrenheit_to_celsius)),

None: print_commands,
}


if __name__ == '__main__':
choice = None
while choice is None:
choice = raw_input("Command: ")

commands.get(choice)()
 
M

Michele Simionato

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
 
P

Peter Otten

braden said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top