Files
crpto_predictor/start_system.py

88 lines
2.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""
系统启动脚本
同时启动:
1. FastAPI 后端服务 (提供前端看板 API)
2. Polymarket 自动交易程序
"""
import subprocess
import sys
import time
import signal
import os
from datetime import datetime
# 颜色代码
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
RESET = '\033[0m'
def log(message, color=RESET):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"{color}[{timestamp}] {message}{RESET}")
def start_process(command, name):
"""启动子进程"""
log(f"正在启动 {name}...", YELLOW)
try:
process = subprocess.Popen(
command,
shell=True,
stdout=sys.stdout,
stderr=sys.stderr,
preexec_fn=os.setsid # 创建新的进程组,方便统一杀掉
)
log(f"{name} 已启动 (PID: {process.pid})", GREEN)
return process
except Exception as e:
log(f"启动 {name} 失败: {e}", RED)
return None
def main():
# 激活 Conda 环境
# 注意:在子进程中直接使用当前已激活的 python 解释器路径,避免 conda activate 问题
python_exec = sys.executable
# 1. 启动 API 服务 (Uvicorn)
# 使用 --host 0.0.0.0 允许局域网访问
api_cmd = f"{python_exec} -m uvicorn api.main:app --host 0.0.0.0 --port 8000"
api_process = start_process(api_cmd, "API 服务 & 前端看板")
# 等待几秒确保 API 启动
time.sleep(3)
# 2. 启动自动交易程序
# 使用 -u 参数禁用输出缓冲
trade_cmd = f"{python_exec} -u auto_trade_polymarket.py"
trade_process = start_process(trade_cmd, "Polymarket 自动交易程序")
log("系统启动完成!", GREEN)
log("前端访问地址: http://localhost:8000", GREEN)
log("按 Ctrl+C 停止所有服务...", YELLOW)
try:
# 监控子进程状态
while True:
if api_process.poll() is not None:
log("API 服务意外退出", RED)
break
if trade_process.poll() is not None:
log("自动交易程序意外退出", RED)
break
time.sleep(1)
except KeyboardInterrupt:
log("\n正在停止服务...", YELLOW)
finally:
# 优雅退出
if api_process:
os.killpg(os.getpgid(api_process.pid), signal.SIGTERM)
if trade_process:
os.killpg(os.getpgid(trade_process.pid), signal.SIGTERM)
log("所有服务已停止", GREEN)
if __name__ == "__main__":
main()