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

基于调用场景动态处理Python CLI命令交互提示的实现方案

实现区分交互式/脚本调用的Python CLI命令

完全可以实现,核心思路是通过判断标准输入是否为终端来区分两种调用场景,具体实现方案如下:

核心逻辑

Python的sys.stdin.isatty()方法可检测当前程序的标准输入是否连接到终端:

  • 返回True:终端交互式调用,需显示警告并等待用户手动确认
  • 返回False:脚本/Ansible等非交互式调用,自动默认选择'y'执行操作

完整代码示例

#!/usr/bin/env python3
import sys
import argparse

def perform_factory_reset():
    print("Starting factory reset . .")
    # 此处写入实际的恢复出厂设置业务逻辑

def main():
    parser = argparse.ArgumentParser(description='Device factory reset utility')
    parser.add_argument('command', choices=['factory-reset'], help='Target command to execute')
    args = parser.parse_args()

    if args.command == 'factory-reset':
        warning_content = """WARNING: Performing a factory-reset will erase all user
defined configurations and reset all settings to system default.
Do you wish to continue ? (y/n)"""
        
        # 判断是否为交互式终端环境
        if sys.stdin.isatty():
            print(warning_content)
            # 循环等待有效输入
            while True:
                user_choice = input().strip().lower()
                if user_choice in ['y', 'n']:
                    break
                print("Invalid input, please enter 'y' or 'n'")
            
            if user_choice != 'y':
                print("Factory reset cancelled.")
                sys.exit(0)
        else:
            # 非交互式模式自动确认
            print(warning_content)
            print("Auto-confirming (non-interactive mode)...")
        
        # 执行恢复操作
        perform_factory_reset()

if __name__ == '__main__':
    main()

使用说明

  1. 给脚本添加执行权限:chmod +x app.py
  2. 交互式调用:直接运行./app.py factory-reset,会弹出提示并等待用户输入确认
  3. 脚本/Ansible调用:在bash脚本或Ansible任务中直接调用./app.py factory-reset,程序自动确认执行,无阻塞

关键细节

  • sys.stdin.isatty()是跨平台实现,Linux/macOS/Windows环境均可正常工作
  • 非交互式模式下仍会打印警告信息,便于日志回溯,但不会阻塞流程
  • 交互式场景添加输入验证,确保用户只能输入有效选项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:50:39