main.mjs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. console.log("🔹 正在执行 Python EXE:", pythonExePath);
  51. if (!fs.existsSync(pythonExePath)) {
  52. reject(`Python EXE 不存在: ${pythonExePath}`);
  53. return;
  54. }
  55. // **参数列表:API 名称 + JSON 格式参数**
  56. // const args = [apiName, JSON.stringify(params)];
  57. // ✅ **解决中文乱码**:使用 Base64 进行参数传输
  58. const args = [
  59. apiName,
  60. Buffer.from(JSON.stringify(params)).toString("base64"),
  61. ];
  62. console.log("📡 发送给 Python 的参数(Base64 编码):", args);
  63. console.log("📡 调用 Python EXE:", pythonExePath, "参数:", args);
  64. const res = execFile(
  65. pythonExePath,
  66. args,
  67. { encoding: "utf8" },
  68. (error, stdout, stderr) => {
  69. if (error) {
  70. console.error("❌ Python EXE 运行失败:", error);
  71. reject(`Error: ${error.message}`);
  72. return;
  73. }
  74. if (stderr) {
  75. console.warn("⚠️ Python EXE 输出警告:", stderr);
  76. }
  77. // **尝试解析 JSON**
  78. try {
  79. console.log("✅ Python EXE 输出:", stdout);
  80. resolve(JSON.parse(stdout)); // 返回 JSON 数据
  81. } catch (parseError) {
  82. console.warn("⚠️ Python EXE 返回的不是 JSON:", stdout);
  83. resolve(stdout.trim()); // 返回原始文本
  84. }
  85. }
  86. );
  87. // **✅ 实时查看 Python print 的输出**
  88. res.stdout.on("data", (data) => {
  89. console.log("🐍 Python stdout:", data.toString());
  90. });
  91. res.stderr.on("data", (data) => {
  92. console.error("🐍 Python stderr:", data.toString());
  93. });
  94. });
  95. });
  96. // 监听 get-file-path 事件 监听渲染进程请求文件路径
  97. ipcMain.handle("get-file-path", async () => {
  98. try {
  99. const { filePaths } = await dialog.showOpenDialog({
  100. properties: ["openFile", "multiSelections"], // ✅ 允许选择多个文件
  101. });
  102. if (filePaths.length > 0) {
  103. console.log("用户选择的文件路径:", filePaths[0]);
  104. return filePaths[0]; // 返回文件路径
  105. } else {
  106. console.log("用户取消了选择");
  107. return null; // 用户没有选择文件
  108. }
  109. } catch (error) {
  110. console.error("获取文件路径失败:", error);
  111. return null;
  112. }
  113. });
  114. mainWindow.on("closed", () => {
  115. mainWindow = null;
  116. });
  117. }
  118. app.whenReady().then(createWindow);
  119. app.on("window-all-closed", () => {
  120. if (process.platform !== "darwin") app.quit();
  121. });
  122. app.on("activate", () => {
  123. if (BrowserWindow.getAllWindows().length === 0) createWindow();
  124. });
  125. export { createWindow };