You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.5 KiB

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<boolean> {
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();