script_runner.py 4.15 KB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python脚本执行控制台工具
提供菜单界面,方便选择和执行项目中的Python脚本
"""

import os
import sys
import subprocess
from pathlib import Path

# 脚本配置
SCRIPTS = [
    {
        'id': '1',
        'name': '生成2025年12月客户开单数据Excel',
        'file': 'generate_november_customer_excel.py',
        'description': '生成2025年12月客户开单数据Excel文件,包含客户档案号、姓名、注册时间、来源、开单业绩、时间、归属门店等字段'
    },
    {
        'id': '2',
        'name': '导出所有用户剩余权益数据',
        'file': 'export_all_member_remaining_rights.py',
        'description': '导出所有用户的剩余权益数据Excel文件,包含客户档案号、姓名、手机号、注册时间、归属门店、来源、品项名称、单价、总购买次数、已消费次数、已退卡次数、已扣除次数、剩余次数、剩余价值等字段'
    },
    {
        'id': '3',
        'name': '测试天王组业绩完成度接口',
        'file': 'test_tianwang_api.py',
        'description': '测试天王组业绩完成度接口,查询2025年1月和当前月份的数据'
    }
]

def clear_screen():
    """清屏"""
    os.system('clear' if os.name != 'nt' else 'cls')

def print_header():
    """打印标题"""
    print("=" * 70)
    print(" " * 20 + "Python脚本执行工具")
    print("=" * 70)
    print()

def print_menu():
    """打印菜单"""
    print_header()
    print("可用脚本列表:")
    print("-" * 70)
    for script in SCRIPTS:
        print(f"  [{script['id']}] {script['name']}")
        print(f"      {script['description']}")
        print()
    print("-" * 70)
    print("  [0] 退出")
    print("=" * 70)
    print()

def get_script_by_id(script_id):
    """根据ID获取脚本配置"""
    for script in SCRIPTS:
        if script['id'] == script_id:
            return script
    return None

def execute_script(script):
    """执行脚本"""
    script_path = Path(__file__).parent / script['file']
    
    if not script_path.exists():
        print(f"\n❌ 错误: 脚本文件不存在: {script_path}")
        input("\n按回车键继续...")
        return
    
    print(f"\n{'=' * 70}")
    print(f"正在执行: {script['name']}")
    print(f"脚本文件: {script['file']}")
    print(f"{'=' * 70}\n")
    
    try:
        # 使用subprocess执行脚本,保持输出实时显示
        process = subprocess.Popen(
            [sys.executable, str(script_path)],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            universal_newlines=True,
            bufsize=1
        )
        
        # 实时输出
        for line in process.stdout:
            print(line, end='')
        
        process.wait()
        
        if process.returncode == 0:
            print(f"\n{'=' * 70}")
            print(f"✅ 脚本执行成功: {script['name']}")
            print(f"{'=' * 70}\n")
        else:
            print(f"\n{'=' * 70}")
            print(f"❌ 脚本执行失败: {script['name']} (退出码: {process.returncode})")
            print(f"{'=' * 70}\n")
            
    except Exception as e:
        print(f"\n❌ 执行脚本时发生错误: {e}\n")
    
    input("按回车键继续...")

def main():
    """主函数"""
    while True:
        clear_screen()
        print_menu()
        
        try:
            choice = input("请选择要执行的脚本 (输入数字): ").strip()
            
            if choice == '0':
                print("\n感谢使用,再见!\n")
                break
            
            script = get_script_by_id(choice)
            
            if script:
                clear_screen()
                execute_script(script)
            else:
                print(f"\n❌ 无效的选择: {choice}")
                input("按回车键继续...")
                
        except KeyboardInterrupt:
            print("\n\n程序已中断,再见!\n")
            break
        except Exception as e:
            print(f"\n❌ 发生错误: {e}")
            input("按回车键继续...")

if __name__ == '__main__':
    main()