如何用python实现菜单_Python 脚本实现 Menu 菜单

[TOC]

# 一、说明

在操作系统上执行某些脚本时,会有一些 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()

```

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值