Python3命令行菜单脚本

文章描述了一种Python脚本,用于创建可自定义菜单的交互系统,支持多语言和多级菜单,旨在提高交互效率和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近期遇到的一些场景,使用菜单式交互操作可以有效减少记忆负担,提升交互效率。从既有代码中剥离并完善形成了一个可以自定义菜单内容的 Python 脚本。

主函数及测试函数如下,使用方法可以参考测试用例子。

# -*- coding: utf-8 -*-
"""
Created on Mon Oct 17 10:56:22 2022 at
Hami, Xinjiang Uygur Autonomous Regions, PRC.
@author: Farman
"""

import sys

#------------------------------------------------------------------------------

def pymenu(menu_items, lang="chs"):
    """ 
    set lang to "chs" to show Simplified Chinese menus.
    otherwise         to show English            menus.
    """
    
    def GetInput(prompt="请输入"):
        prompt += " : "
        return input(prompt)
    
    def show_invalid_input(index):
        print()
        print("%s :%s"%("输入无效" if lang=="chs" else "Invalid input", index))
        print()
        return
    
    while True:
        index = 1
    
        print("")
        print("操作选项" if lang=="chs" else "Menu Items")
        print("--------------------------------------")
                
        for title, func in menu_items:
            print("%6s - %s"%(index, title)); index += 1

        print()
        print("%6s - %s"%(index, ("退出本级菜单" if lang=="chs" else "Exit this menu"))); index += 1
        print("%6s - %s"%(index, ("退出程序"    if lang=="chs" else "Exit program"))); index += 1
        print("--------------------------------------")
    
        index = GetInput("请输入操作序号" if lang=="chs" else "Input the index number")
        
        if len(index):
            try:
                index = int(index)
                
                if index < 1 or index > len(menu_items) + 2:
                    show_invalid_input(index)
                    continue
            except:
                show_invalid_input(index)
                continue
            
            # no exceptions and index is in [1, len(menu_items) + 2]
            if index <= len(menu_items):
                function = menu_items[index - 1][1]
                function()
            elif index == len(menu_items) + 1:
                print("退出本级菜单。" if lang=="chs" else "Exit menu.")
                break
            elif index == len(menu_items) + 2:
                print("退出程序。"    if lang=="chs" else "Exit program.")
                sys.exit(0)
                print("now should exit.")
                
            input("按回车键继续 ..." if lang=="chs" else 'Press "Enter" to continue ...')
    return

#------------------------------------------------------------------------------------

def pymenu_test1():
    def test1():
        print("This is function test 1.")
        return

    def test2():
        print("This is function test 2.")
        return

    menu_items = [
            ["Test-1",    test1],
            ["Test-2",    test2],
            ]
    
    pymenu(menu_items, "eng")
    return

def pymenu_test2(lang):
    def sub_test1():
        print("This is sub function test 1.")
        return
    
    def sub_test2():
        print("This is sub function test 2.")
        return
    
    def test1():
        menu_items = [
                ["Submenu-1",    sub_test1],
                ["Submenu-2",    sub_test2],
                ]
        pymenu(menu_items, lang)
        return

    def test2():
        print("This is function test 2.")
        return

    menu_items = [
            ["Test-1",    test1],
            ["Test-2",    test2],
            ]
    
    pymenu(menu_items, lang)
    return

#------------------------------------------------------------------------------

if __name__ == "__main__":
    print("PyMenu Test")
    print("Now test 1-level menus")
    pymenu_test1()
    print("Now test 2-level menus")
    pymenu_test2('eng')

Enjoy.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值