Files
gushi/run.py
2025-12-21 00:33:04 +08:00

108 lines
2.8 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
古诗词智能查询与解析器 - 启动脚本
"""
import os
import sys
import subprocess
import time
import webbrowser
def install_dependencies():
"""安装Python依赖"""
print("1. 安装Python依赖...")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
print("依赖安装成功!")
return True
except subprocess.CalledProcessError as e:
print(f"依赖安装失败: {e}")
return False
def start_backend():
"""启动后端API服务器"""
print("2. 启动后端API服务器...")
backend_cmd = [sys.executable, "api/app.py"]
# 在Windows上使用CREATE_NEW_CONSOLE标志
if sys.platform == "win32":
subprocess.Popen(backend_cmd, cwd=os.getcwd(),
creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
subprocess.Popen(backend_cmd, cwd=os.getcwd())
print("后端服务器启动中...")
time.sleep(3)
return True
def start_frontend():
"""启动前端HTTP服务器"""
print("3. 启动前端HTTP服务器...")
frontend_cmd = [sys.executable, "-m", "http.server", "8000"]
if sys.platform == "win32":
subprocess.Popen(frontend_cmd, cwd=os.getcwd(),
creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
subprocess.Popen(frontend_cmd, cwd=os.getcwd())
print("前端服务器启动中...")
time.sleep(2)
return True
def open_browser():
"""打开浏览器"""
print("4. 打开浏览器访问应用...")
url = "http://localhost:8000"
webbrowser.open(url)
print(f"已打开浏览器访问: {url}")
return True
def main():
"""主函数"""
print("=" * 50)
print("古诗词智能查询与解析器 - 启动程序")
print("=" * 50)
# 检查当前目录
if not os.path.exists("api/app.py"):
print("错误: 请在项目根目录运行此脚本")
return
# 安装依赖
if not install_dependencies():
print("警告: 依赖安装失败,尝试继续运行...")
# 启动后端
if not start_backend():
print("错误: 后端启动失败")
return
# 启动前端
if not start_frontend():
print("错误: 前端启动失败")
return
# 打开浏览器
if not open_browser():
print("警告: 无法自动打开浏览器")
print("\n" + "=" * 50)
print("应用启动完成!")
print("后端API: http://localhost:5000")
print("前端应用: http://localhost:8000")
print("\n按Ctrl+C停止所有服务器")
print("=" * 50)
try:
# 保持脚本运行
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n正在停止服务器...")
if __name__ == "__main__":
main()