如何使 OS.popen 命令的输出成为一个选择菜单列表?

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

如何使 os.popen 的输出成为将用作另一个程序的输入的选择菜单选项列表?

注意 - 每次输出变化时,我们无法定义一个不变的选择菜单。它可以多于 10 个,有时少于 10 个元素。

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

如果 SG 的输出有如下十个元素,以上是程序:

tiger
lion
elephant
deer
pigeon
fox
hyena
leopard
cheatah
hippo

我想将以上元素作为元素的选择,例如:

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:
    ...

那么我们如何在每个打印语句中添加每个元素并使其具有选择选项,以及我们如何知道元素的数量并制作相同数量的选择菜单?

显然我无法演示 popen 内容,所以我将输入数据硬编码为多行字符串,然后使用 .splitlines 方法将其转换为列表.此代码将处理任何大小的数据,它不限于 10 个项目。

它对用户输入进行一些原始检查,真正的程序应该显示比 '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')

演示输出

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

在 Python 2.6.6 上测试。此代码也将在 Python 3 上正常工作,您只需将 Python 3 的 raw_input 更改为 input。但是 不要在 Python 上使用 input 2.