0

index.js

const childProcess = require("child_process");

childProcess.spawn("python", ["main.py"]);

main.py

import time

while True:
    time.sleep(1)

When running the NodeJS process with node index.js, it runs forever since the Python child process it spawns runs forever.

When the NodeJS process is ended by x-ing out of the Command Prompt, the Python process ends as well, which is desired, but how can you run some cleanup code in the Python code before it exits?

Previous attempts

  • Look in documentation for child_process.spawn for how this termination is communicated from parent to child, perhaps by a signal. Didn't find it.
  • In Python use signal.signal(signal.SIGTERM, handler) (as well as with signal.SIGINT). Didn't get handler to run (though, ending the NodeJS process with Ctrl-C instead of closing the window did get the SIGINT handler to run even though I'm not explicitly forwarding input from the NodeJS process to the Python child process).

Lastly, though this reproducible example is also valid and much more simple, my real-life use case involves Electron, so in case that introduces a complication, or a solution, figured I'd mention it.

Windows 10, NodeJS 12.7.0, Python 3.8.3

tscizzle
  • 11,191
  • 15
  • 54
  • 88
  • 1
    can you set the `detached` option (in `cp.spawn`) to `true` to keep the child process alive when the parent exits, and then just detect this in your python script , maybe using the ideas [here](https://stackoverflow.com/questions/759443/child-process-detecting-the-parent-process-death-in-python) – pushkin Dec 31 '20 at 22:42
  • Good idea, and potentially what I'll do. Ideally the Python script can run with or without the NodeJS parent being the thing to start it, but that can just be some logic (Node script passes an arg `exitIfNoParent` to Python script, so it knows whether or not it should do that exiting behavior.) – tscizzle Dec 31 '20 at 23:52
  • Does it work now? – Algo7 Jan 12 '21 at 10:43

0 Answers0