Search code examples
node.jsspawn

Pass muliple args to a python script spawned from node.js


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


Solution

  • 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}`);
    });