main.mjs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import { app, BrowserWindow, ipcMain, dialog } from "electron";
  2. import { fileURLToPath } from "url";
  3. import path from "path";
  4. import { execFile } from "child_process";
  5. import fs from "fs";
  6. process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
  7. const __filename = fileURLToPath(import.meta.url);
  8. const __dirname = path.dirname(__filename);
  9. let mainWindow = null;
  10. function createWindow() {
  11. mainWindow = new BrowserWindow({
  12. width: 1400,
  13. height: 900,
  14. minWidth: 800,
  15. minHeight: 600,
  16. webPreferences: {
  17. preload: path.join(__dirname, "./preload.mjs"),
  18. contextIsolation: true,
  19. nodeIntegration: false,
  20. allowRunningInsecureContent: false,
  21. },
  22. });
  23. //环境判断引入不同的页面
  24. if (process.env.NODE_ENV === "development") {
  25. mainWindow.loadURL("http://localhost:5173");
  26. mainWindow.webContents.openDevTools();
  27. } else {
  28. //生产环境将引入打包好的文件
  29. mainWindow.loadFile(path.join(__dirname, "../dist/index.html"));
  30. mainWindow.webContents.openDevTools();
  31. }
  32. // **🔹 监听渲染进程调用 Python EXE**
  33. ipcMain.handle("run-python-exe", async (event, apiName, params = {}) => {
  34. return new Promise((resolve, reject) => {
  35. let pythonExePath = null;
  36. if (process.env.NODE_ENV === "development") {
  37. // **开发环境**
  38. pythonExePath = path.join(__dirname, "../serves/dist/api_test.exe");
  39. } else {
  40. //这里需要区分开发环境还是生产环境 生产环境用到这个路径
  41. pythonExePath = path.join(
  42. process.resourcesPath, // `app.asar.unpacked` 的默认路径
  43. "app.asar.unpacked",
  44. "serves",
  45. "dist",
  46. "api_test.exe"
  47. );
  48. }
  49. // **修改 Python EXE 的路径**
  50. if (!fs.existsSync(pythonExePath)) {
  51. reject(`Python EXE 不存在: ${pythonExePath}`);
  52. return;
  53. }
  54. // **参数列表:API 名称 + JSON 格式参数**
  55. // const args = [apiName, JSON.stringify(params)];
  56. // ✅ **解决中文乱码**:使用 Base64 进行参数传输
  57. const args = [
  58. apiName,
  59. Buffer.from(JSON.stringify(params)).toString("base64"),
  60. ];
  61. const res = execFile(
  62. pythonExePath,
  63. args,
  64. { encoding: "utf8" },
  65. (error, stdout, stderr) => {
  66. if (error) {
  67. console.error("❌ Python EXE 运行失败:", error);
  68. reject(`Error: ${error.message}`);
  69. return;
  70. }
  71. if (stderr) {
  72. console.warn("⚠️ Python EXE 输出警告:", stderr);
  73. }
  74. // **尝试解析 JSON**
  75. try {
  76. console.log("✅ Python EXE 输出:", stdout);
  77. resolve(JSON.parse(stdout)); // 返回 JSON 数据
  78. } catch (parseError) {
  79. console.warn("⚠️ Python EXE 返回的不是 JSON:", stdout);
  80. resolve(stdout.trim()); // 返回原始文本
  81. }
  82. }
  83. );
  84. // **✅ 实时查看 Python print 的输出**
  85. res.stdout.on("data", (data) => {
  86. console.log("🐍 Python stdout:", data.toString());
  87. });
  88. res.stderr.on("data", (data) => {
  89. console.error("🐍 Python stderr:", data.toString());
  90. });
  91. });
  92. });
  93. // 监听 get-file-path 事件 监听渲染进程请求文件路径
  94. ipcMain.handle("get-file-path", async () => {
  95. try {
  96. const { filePaths } = await dialog.showOpenDialog({
  97. properties: ["openFile", "multiSelections"], // ✅ 允许选择多个文件
  98. });
  99. if (filePaths.length > 0) {
  100. console.log("用户选择的文件路径:", filePaths[0]);
  101. return filePaths[0]; // 返回文件路径
  102. } else {
  103. console.log("用户取消了选择");
  104. return null; // 用户没有选择文件
  105. }
  106. } catch (error) {
  107. console.error("获取文件路径失败:", error);
  108. return null;
  109. }
  110. });
  111. mainWindow.on("closed", () => {
  112. mainWindow = null;
  113. });
  114. }
  115. app.whenReady().then(createWindow);
  116. app.on("window-all-closed", () => {
  117. if (process.platform !== "darwin") app.quit();
  118. });
  119. app.on("activate", () => {
  120. if (BrowserWindow.getAllWindows().length === 0) createWindow();
  121. });
  122. export { createWindow };