将多个参数传递给从 node.js 生成的 python 脚本

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

我正在尝试 "spawn" python 脚本 Node.JS。 python 脚本接受多个文件路径作为参数。此命令有效:

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

在节点中,我得到了一个带有路径的变量:

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

但是当我尝试生成脚本时:

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

但这似乎发出命令:

python3 script.py [path1,path2,path3]

修改各种 concat()、join() 和 toString() 我可以获得如下内容:

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

...但我想不出如何简单地做到这一点

我想 unshift 可能就是您要找的。

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

尝试以下操作:

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