hamster-desktop/electron/core/PythonManager.ts
2024-08-12 17:01:49 +08:00

102 lines
2.8 KiB
TypeScript

import http from "node:http";
import path from "node:path";
import { spawn, ChildProcess } from "node:child_process";
import { BrowserWindow } from "electron";
class PythonManager {
public flaskProcess: ChildProcess | null = null;
private intervalId: NodeJS.Timeout | null = null;
constructor(
private mainWindow: BrowserWindow | null,
private url: string,
private interval = 5000
) {}
// 启动 Python 服务
public startFlask() {
if (this.flaskProcess) {
console.log("Flask service is already running.");
this.mainWindow?.webContents.send("flask", { running: true });
return;
}
// 使用 spawn 启动 Flask 服务
this.flaskProcess = spawn(path.join(process.env.VITE_PUBLIC!, "flask_app"));
// 实时获取 stdout 日志
this.flaskProcess.stdout?.on("data", (data) => {
const message = data.toString();
console.log(`Flask stdout: ${message}`);
this.mainWindow?.webContents.send("flask", { stdout: message });
});
// 实时获取 stderr 日志
this.flaskProcess.stderr?.on("data", (data) => {
const message = data.toString();
console.error(`Flask stderr: ${message}`);
this.mainWindow?.webContents.send("flask-service:response", { stderr: message });
});
// 监听进程关闭事件
this.flaskProcess.on("close", (code) => {
console.log(`Flask process exited with code ${code}`);
this.flaskProcess = null;
this.mainWindow?.webContents.send("flask-service:response", { exited: true, code });
});
// 开始轮询服务状态
// this.startCheckingFlaskStatus();
}
// 停止 Python 服务
public stopFlask() {
if (this.flaskProcess) {
this.flaskProcess.kill();
console.log("Flask service stopped.");
this.flaskProcess = null;
}
// 停止轮询
this.stopCheckingFlaskStatus();
}
// 检查 Flask 服务状态
private checkFlaskStatus() {
if (!this.mainWindow) return;
http
.get(this.url, (res) => {
const { statusCode } = res;
this.mainWindow?.webContents.send("flask-check", {
running: statusCode === 200,
});
})
.on("error", (err) => {
console.error(`Error checking Flask service: ${err.message}`);
this.mainWindow?.webContents.send("flask-check", {
running: false,
});
});
}
// 开始轮询 Flask 服务状态
private startCheckingFlaskStatus() {
if (this.intervalId) {
console.log("Already checking Flask status.");
return;
}
this.intervalId = setInterval(() => this.checkFlaskStatus(), this.interval);
}
// 停止轮询 Flask 服务状态
private stopCheckingFlaskStatus() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
}
export default PythonManager;