# 上传git仓库
import os
import sys
import time
import os
import signal
import subprocess
import psutil
from datetime import datetime

# 配置部分
APP_SCRIPT = 'web_app_2006.py'
# 使用绝对路径指定pythonw.exe
# 如果当前路径有问题，可手动修改为正确的pythonw.exe路径
PYTHON_EXE = 'pythonw.exe'
LOG_FILE = 'restart_app.log'
WAIT_TIME_BEFORE_KILL = 1  # 进程终止前等待时间(秒)
WAIT_TIME_AFTER_KILL = 1  # 进程终止后等待时间(秒)
WAIT_TIME_BEFORE_RESTART = 1  # 重启前等待时间(秒)

# 设置UTF-8编码
os.environ['PYTHONIOENCODING'] = 'utf-8'

# 日志函数
def log(message):
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    log_message = f'[{timestamp}] {message}'
    print(log_message)
    with open(LOG_FILE, 'a', encoding='utf-8') as f:
        f.write(log_message + '\n')

# 查找并终止相关进程
def kill_processes():
    log(f'正在查找并终止 {APP_SCRIPT} 相关进程...')
    killed = False
    for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
        try:
            if proc.name().lower() == 'python.exe' or proc.name().lower() == 'pythonw.exe':
                cmdline = proc.cmdline()
                if len(cmdline) >= 2 and APP_SCRIPT in cmdline[1]:
                    log(f'找到进程: PID={proc.pid}, 命令行={cmdline}')
                    proc.kill()
                    killed = True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return killed

# 启动应用
def start_application():
    log(f'正在启动 {APP_SCRIPT}...')
    try:
        # 获取当前脚本所在目录
        script_dir = os.path.dirname(os.path.abspath(__file__))
        # 构建启动命令
        cmd = [PYTHON_EXE, APP_SCRIPT]
        # 在后台启动进程
        # 使用pythonw.exe在后台运行，不显示控制台窗口
        # 设置进程创建标志，确保应用完全独立运行
        CREATE_NEW_PROCESS_GROUP = 0x00000200
        DETACHED_PROCESS = 0x00000008
        creationflags = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
        
        # 使用shell=True确保命令正确执行
        # 不捕获输出，因为pythonw.exe不会返回控制台输出
        try:
            subprocess.Popen(
                f'{PYTHON_EXE} {APP_SCRIPT}',
                cwd=script_dir,
                shell=True,
                creationflags=creationflags
            )
            log(f'{APP_SCRIPT} 启动成功')
            return True
        except Exception as e:
            log(f'启动 {APP_SCRIPT} 失败: {str(e)}')
            return False

        log(f'{APP_SCRIPT} 启动成功')
        return True
    except Exception as e:
        log(f'启动 {APP_SCRIPT} 失败: {str(e)}')
        return False

# 主函数
def main():
    log('===== 应用重启脚本开始执行 =====')
    
    log(f'等待 {WAIT_TIME_BEFORE_KILL} 秒确保response完成...')
    time.sleep(WAIT_TIME_BEFORE_KILL)
    # 终止现有进程
    killed = kill_processes()
    if killed:
        log(f'等待 {WAIT_TIME_AFTER_KILL} 秒确保进程完全终止...')
        time.sleep(WAIT_TIME_AFTER_KILL)
    else:
        log('未找到需要终止的进程')

    # 启动新进程
    start_application()

    log(f'等待 {WAIT_TIME_BEFORE_RESTART} 秒后脚本将退出...')
    time.sleep(WAIT_TIME_BEFORE_RESTART)
    log('===== 应用重启脚本执行完毕 =====')

if __name__ == '__main__':
    main()

    