Search code examples
pythonpython-2.6python-os

How to make the output of OS.popen command a list of choice menu?


How to make the output of os.popen a list of choice menu options which will be used as input for another program?

Note - Every time the output varies we cannot define one constant choice menu. It can be more than 10 or sometimes less than 10 elements.

SG = "dzdo symaccess -sid {0} show {1} view -detail"
IG = os.popen SG).read()
print SG

Above is the program if the output of SG has some ten elements like below:

tiger
lion
elephant
deer
pigeon
fox
hyena
leopard
cheatah
hippo

The above elements I want to make as choice of elements like:

print("1. tiger")
print("2. lion")
print("3. elephant")
print("4. deer")
.
.
.
print("11. exit")
print ("\n")
choice = input('enter your choice [1-11] :')
choice = int(choice)
if choice ==1:
    ...

So how do we add each element in each print statement and make it have a choice option, and how can we know the number of elements and make the same number of choices menu?


Solution

  • Obviously I can't demonstrate the popen stuff, so I've hard-coded the input data into a multi-line string, which I turn into a list using the .splitlines method. This code will cope with data of any size, it's not restricted to 10 items.

    It does some primitive checking of the user input, a real program should display a more helpful message than 'Bad choice'.

    from __future__ import print_function
    
    IG = '''\
    tiger
    lion
    elephant
    deer
    pigeon
    fox
    hyena
    leopard
    cheatah
    hippo
    '''
    
    data = IG.splitlines()
    for num, name in enumerate(data, 1):
        print('{0}: {1}'.format(num, name))
    
    exitnum = num + 1
    print('{0}: {1}'.format(exitnum, 'exit'))
    while True:
        choice = raw_input('Enter your choice [1-{0}] : '.format(exitnum))
        try:
            choice = int(choice)
            if not 1 <= choice <= exitnum:
                raise ValueError
        except ValueError:
            print('Bad choice')
            continue
        if choice == exitnum:
            break
        elif choice == 1:
            print('Tigers are awesome')
        else:
            print('You chose {0}'.format(data[choice-1]))
    
    print('Goodbye')
    

    demo output

    1: tiger
    2: lion
    3: elephant
    4: deer
    5: pigeon
    6: fox
    7: hyena
    8: leopard
    9: cheatah
    10: hippo
    11: exit
    Enter your choice [1-11] : 3
    You chose elephant
    Enter your choice [1-11] : c
    Bad choice
    Enter your choice [1-11] : 1
    Tigers are awesome
    Enter your choice [1-11] : 12
    Bad choice
    Enter your choice [1-11] : 4
    You chose deer
    Enter your choice [1-11] : 11
    Goodbye
    

    Tested on Python 2.6.6. This code will also work correctly on Python 3, you just need to change raw_input to input for Python 3. But please don't use input on Python 2.