varm varm - 5 months ago 144
Node.js Question

Running a python script in the background using child_process (node js)

I have a python script test.py on a raspberry pi which needs to be running in the background. Using the CLI, I do this:

python test.py &


But, how do I do the same using the child_process in node js.

var spawn = require("child_process").spawn;
var process = spawn("python",["/path/to/test.py", "&"]);


I have this code and this seems to be not working. Please suggest possible ways to achieve this.

rsp rsp
Answer

Don't use the & (ampersand) in the command line arguments. It is used by shell, not by python.

Use {detached: true} option so it will be able to live when your Node process exits:

var spawn = require("child_process").spawn;
var p = spawn("python", ["/path/to/test.py"], {detached: true});

If you also want to gnore its output, use {stdio: 'ignore'}

var spawn = require("child_process").spawn;
var p = spawn("python", ["/path/to/test.py"], {detached: true, stdio: 'ignore'});

Also, I wouldn't name the variable process because it is used by node:

The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require().

See: https://nodejs.org/api/process.html#process_process

Update

If it still doesn't exit, try adding:

p.unref();

to your program, where p is what is returned by spawn:

var spawn = require("child_process").spawn;
var p = spawn("python", ["/path/to/test.py"], {detached: true, stdio: 'ignore'});
p.unref();

Update 2

Here is an example shell session - how to run it, test if it works and kill it:

$ cat parent.js 
var spawn = require("child_process").spawn;
var fs = require("fs");
var p = spawn("sh", ["child.sh"], {detached: true, stdio: 'ignore'});
p.unref();
$ cat child.sh 
#!/bin/sh
sleep 60
$ node parent.js 
$ ps x | grep child.sh
11065 ?        Ss     0:00 sh child.sh
11068 pts/28   S+     0:00 grep child.sh
$ kill 11065
$ ps x | grep child.sh
11070 pts/28   S+     0:00 grep child.sh
$