You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python脚本选择功能1后不再重复显示主菜单?

解决选择选项1后主菜单重复显示的问题

要实现选择选项1后不再显示主菜单,有两种简单的实现方式,都是基于你提到的break或标记位思路:

方法一:用break直接退出循环

在选项1的代码块末尾添加break语句,执行完浏览器操作后直接终止while循环,菜单就不会再重复显示了。

修改后的完整代码:

import os
import asyncio
# 假设initialize_browser和authorize_system是已定义的函数

async def main_menu():
    menu_active = True  # 控制菜单显示的变量
    while menu_active:
        print("\nMain Menu:")
        print("1. Activate script")
        print("2. Account authorization")
        print("3. Exit")

        choice = input("Enter the option number: ")
        os.system('cls')
        if choice == '1':
            headless_choice = input("Do you want to use headless mode? (yes/no): ").lower() == 'yes'
            driver = initialize_browser(headless=headless_choice)
            driver.get("https://my.site")
            os.system('cls')
            break  # 执行完脚本后退出菜单循环
        elif choice == '2':
            authorize_system()
        elif choice == '3':
            print("Exiting the program...")
            break
        else:
            print("Invalid choice. Please try again.")


if __name__ == "__main__":
    asyncio.run(main_menu())

方法二:修改menu_active标记位

把控制循环的menu_active变量设为False,这样下一次循环的条件不满足,菜单就不会再显示了。

修改后的完整代码:

import os
import asyncio
# 假设initialize_browser和authorize_system是已定义的函数

async def main_menu():
    menu_active = True  # 控制菜单显示的变量
    while menu_active:
        print("\nMain Menu:")
        print("1. Activate script")
        print("2. Account authorization")
        print("3. Exit")

        choice = input("Enter the option number: ")
        os.system('cls')
        if choice == '1':
            headless_choice = input("Do you want to use headless mode? (yes/no): ").lower() == 'yes'
            driver = initialize_browser(headless=headless_choice)
            driver.get("https://my.site")
            os.system('cls')
            menu_active = False  # 关闭菜单激活状态,不再显示菜单
        elif choice == '2':
            authorize_system()
        elif choice == '3':
            print("Exiting the program...")
            break
        else:
            print("Invalid choice. Please try again.")


if __name__ == "__main__":
    asyncio.run(main_menu())

两种方法效果一致,你可以根据个人习惯选择其中一种。

内容的提问来源于stack exchange,提问作者machachuchez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 05:07:04