已复制
全屏展示
复制代码

Python 脚本实现 Menu 菜单

· 1 min read

在操作系统上执行某些脚本时,会有一些  menu  选择菜单, 如果用  Python  来实现,可以尝试用下面的思路试试,毕竟  Python  的可读性比  bash  高的可不是一点点。

#!/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()
    
🔗

文章推荐