| 520 | } |
| 521 | |
| 522 | async runPythonModule( |
| 523 | moduleName: string, |
| 524 | args: string[], |
| 525 | mainWindow: BrowserWindow | null, |
| 526 | ): Promise<string> { |
| 527 | if (!this.SurferPythonPath) { |
| 528 | throw new Error( |
| 529 | 'Python path is not set. Make sure to call findPython() before running a module.', |
| 530 | ); |
| 531 | } |
| 532 | |
| 533 | const pythonPath = this.SurferPythonPath; |
| 534 | |
| 535 | // Quote arguments that contain spaces |
| 536 | const quotedArgs = args.map((arg) => |
| 537 | arg.includes(' ') ? `"${arg}"` : arg, |
| 538 | ); |
| 539 | |
| 540 | console.log( |
| 541 | `Executing: ${pythonPath} -m ${moduleName} ${quotedArgs.join(' ')}`, |
| 542 | ); |
| 543 | |
| 544 | return new Promise((resolve, reject) => { |
| 545 | const process2 = spawn(pythonPath, ['-m', moduleName, ...quotedArgs], { |
| 546 | shell: true, |
| 547 | windowsVerbatimArguments: process.platform === 'win32', // This helps with Windows |
| 548 | }); |
| 549 | |
| 550 | let stdoutData = ''; |
| 551 | let stderrData = ''; |
| 552 | |
| 553 | process2.stdout.on('data', (data) => { |
| 554 | const output = data.toString().trim(); |
| 555 | stdoutData += output + '\n'; |
| 556 | console.log(`stdout: ${output}`); |
| 557 | mainWindow?.webContents.send('console-output', output); |
| 558 | }); |
| 559 | |
| 560 | process2.stderr.on('data', (data) => { |
| 561 | const error = data.toString().trim(); |
| 562 | stderrData += error + '\n'; |
| 563 | console.error(`stderr: ${error}`); |
| 564 | mainWindow?.webContents.send('console-error', error); |
| 565 | }); |
| 566 | |
| 567 | process2.on('close', (code) => { |
| 568 | if (code === 0) { |
| 569 | mainWindow?.webContents.send( |
| 570 | 'console-completed', |
| 571 | 'Process completed successfully.', |
| 572 | ); |
| 573 | resolve(stdoutData.trim()); |
| 574 | } else { |
| 575 | const errorMessage = `Process exited with code ${code}\n${stderrData}`; |
| 576 | mainWindow?.webContents.send('console-error', errorMessage); |
| 577 | reject(new Error(errorMessage)); |
| 578 | } |
| 579 | }); |