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

标签 python python-2.6 python-os

如何使 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 项。

它对用户输入进行一些原始检查,真正的程序应该显示比“错误选择”更有用的消息。

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上也能正常工作,你只需要更改 raw_inputinput对于 Python 3。但是不要使用 input在 Python 2 上。

关于python - 如何使 OS.popen 命令的输出成为选择菜单列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50115102/

相关文章:

python - 无法从 'available_if' 导入名称 'sklearn.utils.metaestimators'

python - 是否有 NLP 包或函数知道或可以从文档中找到位置?

python - 在 python 中编写 "try elsetry"的最佳方法?

python - 查找Python中所有解决方案列表中是否存在一组潜力的最快方法

python - Django 模板如果检查 bool True 时标记在 FastCGI 下不起作用

Python - 在函数之间来回传递参数

python - Django 保存()错误

python - 为什么 os 模块不运行 wget cmd 命令?

python - 在 python 中继续播放 youtube 剪辑

python - 关闭的文件描述符是怎么回事?