Reputation: 209
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.
Upvotes: 1
Views: 2464
Reputation: 111336
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
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();
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
$
Upvotes: 1
Reputation: 6547
You shouldn't really be doing that. Processes should be handled by a real process manager.
If you want to run a background process, you should look into how to run services in Raspberry Pi. It depends on the Linux distribution that is being run on the Raspberry Pi (Upstart (like in Debian) or systemd (like in CentOS))
But anyways, quoting an example from documentation:
const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
Upvotes: 2