Skip to content

Instantly share code, notes, and snippets.

@wangwanzhong
Last active April 29, 2020 02:01
Show Gist options
  • Save wangwanzhong/ad04848b7b9642023bf9978a81f27d9d to your computer and use it in GitHub Desktop.
Save wangwanzhong/ad04848b7b9642023bf9978a81f27d9d to your computer and use it in GitHub Desktop.
select menu to excute in interactive model
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
class Menu:
'''Display a menu and respond to choices when run. '''
def __init__(self):
self.choices = {
'1': self.start,
'2': self.stop,
'3': self.status,
'4': self.quit
}
def display_menu(self):
print('''
Menu
1. Start script
2. Stop script
3. status script
4. Quit script
''')
def run(self):
'''Display the menu and respond to choices.'''
self.display_menu()
choice = input("Enter your option: ")
action = self.choices.get(str(choice))
if action:
action()
else:
print("{0} is not a valid choice".format(choice))
def start(self):
print("start")
def stop(self):
print("stop")
def status(self):
print("status")
def quit(self):
print("quit")
if __name__ == '__main__':
Menu().run()
#!/bin/bash
VERSIONS='5.3.26 5.4.6 5.5.0 5.4.19'
PS3='Choose your version {1|2|3}: '
select i in ${VERSIONS}
do
# 二次确认
if [ "$i" != "" ];then
echo
echo "You select is :"
echo -ne " \033[32m ${i} \033[0m(yes/no)[enter]:"
read -t 30 JUGE
if [ "$JUGE" != "yes" ];then
echo "Ensure your parameter!!!! exit"
exit 1
fi
break 2
else
echo "wrong select input the number 1|2|3 or ctrl^c exit"
fi
done
echo "Your select is ${i}"
@shamil17
Copy link

Menu

  1. Start script
  2. Stop script
  3. status script
  4. Quit script

Enter your option:1
None is not a valid choice

Process finished with exit code 0

isn't it should be start should execute?

@wangwanzhong
Copy link
Author

Menu

  1. Start script
  2. Stop script
  3. status script
  4. Quit script

Enter your option:1
None is not a valid choice

Process finished with exit code 0

isn't it should be start should execute?

Thanks for your feedback.

problem is choice = input("Enter your option: ") returns string rather than integer,

i fix it through changing self.choices keys from integer to string.

self.choices = { 1: self.start, 2: self.stop, 3: self.status, 4: self.quit }
to
self.choices = { '1': self.start, '2': self.stop, '3': self.status, '4': self.quit }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment