我对代码进行了一些包装,使其更易于使用(兼容Python2和3)。
这是使其工作的机器,您可以剪切并粘贴它:
from collections import namedtuple
# version compatibility shim
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.x
inp = input
def get_int(prompt, lo=None, hi=None):
"""
Prompt for integer input
"""
while True:
try:
value = int(inp(prompt))
if (lo is None or lo <= value) and (hi is None or value <= hi):
return value
except ValueError:
pass
# a menu option
Option = namedtuple("Option", ["name", "function"])
def do_menu(options, prompt="? ", fmt="{:>2}: {}"):
while True:
# show menu options
for i,option in enumerate(options, 1):
print(fmt.format(i, option.name))
# get user choice
which = get_int(prompt, lo=1, hi=len(options))
# run the chosen item
fn = options[which - 1].function
if fn is None:
break
else:
fn()
然后你可以这样使用它:
def my_func_1():
print("\nCalled my_func_1\n")
def my_func_2():
print("\nCalled my_func_2\n")
def main():
do_menu(
[
Option("Gestion de listes", my_func_1),
Option("Gestion de matrices", my_func_2),
Option("Quitter", None)
],
"Choissisez une commande: "
)
if __name__=="__main__":
main()