2007-08-11 20:47:46

Simple Menu in Python

#!/usr/bin/python

import sys
import os
import string

width = 80
choice_width = 3
seperator_width = 1
process_width = 20
desc_width = width - choice_width - process_width - (seperator_width * 2)
seperator = ''
selection = [1,2,3,4,5,6]
header_format = '%-*s%*s%*s%*s%*s'
line_format = '%-*d%*s%*s%*s%*s'
home_path = os.environ['HOME']

def clear():
    os.system("clear")

def to_int(in_str):
    "Converts a string to an integer"
    out_num = 0
    if in_str[0] == "-":
        multiplier = -1
        in_str = in_str[1:]
    else:
        multiplier = 1
    for x in range(0,len(in_str)):
        out_num = out_num * 10 + ord(in_str[x]) - ord('0')
    return out_num * multiplier

def ask_question():
    clear()
    print
    print "=" * width
    print header_format % (choice_width, 'Num', seperator_width, seperator,process_width, 'Function', seperator_width, seperator, desc_width, 'Description')
    print "-" * width
    print line_format % (choice_width, 1, seperator_width, seperator, process_width, 'Network Restart', seperator_width, seperator, desc_width, 'Restart the network interfaces')
    print line_format % (choice_width, 2, seperator_width, seperator, process_width, 'SMB Restart', seperator_width, seperator, desc_width, 'Restart the Samba service')
    print line_format % (choice_width, 3,seperator_width, seperator, process_width, 'HTTP Restart', seperator_width, seperator, desc_width, 'Restart the HTTPd service')
    print line_format % (choice_width, 4, seperator_width, seperator, process_width, 'LVM Configuration', seperator_width, seperator, desc_width, 'Open the LVM GUI tool')
    print line_format % (choice_width, 5, seperator_width, seperator, process_width, 'MySQL Restart', seperator_width, seperator, desc_width, 'Perform a restart of the MySQLd service')
    print line_format % (choice_width, 6, seperator_width, seperator, process_width, 'Exit', seperator_width, seperator, desc_width, 'Quit Menu')
    print "=" * width
    print
    print "-" * width
    print "Note: Copyright James Conner"
    print "-" * width
    print
    answer = raw_input('Enter the number for your selection: ')
    answer_converted = to_int(answer)

    if answer_converted in selection:
        if answer_converted == 6:
            sys.exit(0)
        elif answer_converted == 5:
            os.system("service mysqld restart")
            ask_question()
        elif answer_converted == 4:
            os.system("/usr/sbin/system-config-lvm")
            ask_question()
        elif answer_converted == 3:
            os.system("service httpd restart")
            ask_question()
        elif answer_converted == 2:
            os.system("service smb restart")
            ask_question()
        elif answer_converted == 1:
            os.system("service network restart")
            ask_question()
    else:
        ask_question()
ask_question()

Tags:   python     |    Perm Link:   Simple Menu in Python



James Conner