import { spawn } from 'child_process'; import * as path from 'path'; import { config } from '../../config'; class PythonServiceManager { private pythonProcess: any = null; private isRunning: boolean = false; async start(): Promise { if (this.isRunning) { console.log('Python服务已经在运行'); return true; } try { // 构建Python服务的路径 const pythonServicePath = path.join(__dirname, '../../../python_service/main.py'); // 从配置中读取端口,默认3007 const port = config.dataSource?.tqsdk?.pythonPort || 3007; console.log(`启动Python TQAPI服务,端口: ${port}...`); // 启动Python服务,传递端口参数 this.pythonProcess = spawn('python', [pythonServicePath, '--port', port.toString()], { cwd: path.join(__dirname, '../../../python_service'), stdio: 'inherit', shell: true }); this.pythonProcess.on('error', (error: any) => { console.error('启动Python服务失败:', error); this.isRunning = false; }); this.pythonProcess.on('exit', (code: number, signal: string) => { console.log(`Python服务退出,代码: ${code}, 信号: ${signal}`); this.isRunning = false; }); // 等待2秒,确保Python服务有时间启动 await new Promise(resolve => setTimeout(resolve, 2000)); this.isRunning = true; console.log('Python TQAPI服务启动成功'); return true; } catch (error) { console.error('启动Python服务时出错:', error); this.isRunning = false; return false; } } stop(): void { if (this.pythonProcess) { try { console.log('停止Python TQAPI服务...'); // 发送终止信号 this.pythonProcess.kill(); // 等待进程退出 this.pythonProcess.on('exit', (code: number, signal: string) => { console.log(`Python服务退出,代码: ${code}, 信号: ${signal}`); }); this.pythonProcess = null; this.isRunning = false; console.log('Python TQAPI服务已停止'); } catch (error) { console.error('停止Python服务时出错:', error); this.pythonProcess = null; this.isRunning = false; } } else { console.log('Python服务未运行,无需停止'); } } getStatus(): boolean { return this.isRunning; } } // 导出单例实例 export const pythonServiceManager = new PythonServiceManager();