Python 指令碼實現 Menu 選單
阿新 • • 發佈:2019-01-11
一、說明
在作業系統上執行某些指令碼時,會有一些 menu 選擇選單, 如果用 Python 來實現,可以嘗試用下面的思路試試。
二、程式碼
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import time
import sys
class Things():
def __init__(self, username='nobody'):
self.username = username
def clean_disk(self):
print("cleaning disk ... ..." )
time.sleep(1)
print("clean disk done!")
def clean_dir1(self):
print("cleaning dir1 ... ...")
time.sleep(1)
print("clean dir1 done!")
def clean_dir2(self):
print("cleaning dir2 ... ...")
time.sleep(1)
print("clean dir2 done!" )
class Menu():
def __init__(self):
self.thing = Things()
self.choices = {
"1": self.thing.clean_disk,
"2": self.thing.clean_dir1,
"3": self.thing.clean_dir2,
"4": self.quit
}
def display_menu(self):
print("""
Operation Menu:
1. Clean disk
2. Clean dir1
3. Clean dir2
4. Quit
""" )
def run(self):
while True:
self.display_menu()
try:
choice = input("Enter an option: ")
except Exception as e:
print("Please input a valid option!");continue
choice = str(choice).strip()
action = self.choices.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice))
def quit(self):
print("\nThank you for using this script!\n")
sys.exit(0)
if __name__ == '__main__':
Menu().run()