3

I am trying to "spawn" a python script in Node.JS. The python script accepts multiple file paths as args. This command works:

python3 script.py 'path1' 'path2' 'path3'

In node, I am given a var with the paths:

args = ["path1", "path2", "path3"]

But when I try to spawn the script:

var spawn = require("child_process").spawn;
var pyspawn = spawn(
  'python3', [pyscript.py, args]
);

But this appears to issue the command:

python3 script.py [path1,path2,path3]

Tinkering with various concat()s, join()s, and toString()s I can get stuff that looks like:

python3 script.py "'path1' 'path2' 'path3'"

... but cant for the life of me figure how to do this simply

1 Answer 1

8

I think unshift might be what you are looking for.

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the new array.

Try the following:

const spawn = require("child_process").spawn;
const pyFile = 'script.py';
const args = ['path1', 'path2', 'path3'];
args.unshift(pyFile);
const pyspawn = spawn('python3', args);

pyspawn.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
});

pyspawn.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
});

pyspawn.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. I teased around this, but never made that leap -- include the pyfile in the list at the outgo!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.