I'm building a Python backend for an Electron app using FastAPI (and Uvicorn). I develop on both macOS and Windows, so I'm looking for a cross-platform solution to the following question.
How can I spawn and gracefully kill a python Uvicorn server from Node.js (specifically the electron.js script of my Electron app)?
The only way I've been able to launch the server is with exec instead of spawn. So this works:
const { spawn, exec, execFile } = require("child_process");function launchPython() { pythonProcess = exec("C:\\Users\\user2\\miniconda3\\envs\\myenv\\python.exe .\\py_src\\main.py" ); console.log("Python process started in dev mode") return pythonProcess;}But this does not:
function launchPython() { pythonProcess = spawn("C:\\Users\\user2\\miniconda3\\envs\\myenv\\python.exe .\\py_src\\main.py" ); console.log("Python process started in dev mode") return pythonProcess;}.\py_src\main.py looks like this:
import uvicornif __name__ == "__main__": uvicorn.run("app.api:app", host="0.0.0.0", port=8000, reload=True )Also, upon exiting the Electron app, the Uvicorn server is not killed. The "exit" code in my main electron.js file is as follows:
app.on("window-all-closed", function () { if (process.platform !== "darwin") { pythonProcess.kill(); app.quit(); return }});So two main questions:
- Why doesn't
spawnwork to run the python Uvicorn server (py_src\main.py)? NOTE: I'm using a specific python version from a Miniconda environment. Could that be the cause? - How can I shutdown the Uvicorn server programmatically when the Electron app exits (because killing the python process that I opened with
execdoesn't seem to work)?
Eventually I'm going to use Pyinstaller to build an executable for the FastAPI backend, and launch it with child_process.execFile, which is why I need a programmatic way to shutdown the Uvicorn server (e.g. with a "quit" or "shutdown" call to the API)