You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用spawn调用Python3脚本时如何传递--name等命令行参数

配置方法

spawn的第二个参数是参数数组,需要将脚本路径之后的所有命令行参数按顺序逐个作为数组元素传入即可,不需要额外添加引号包裹参数值,spawn会自动处理参数转义逻辑。

你需要把原来的spawn调用改成如下写法:

var { spawn } = require('child_process');

console.log("--------------------START--------------------- ");
       
var scriptPath = "/home/usr/Documentos/Proyectos/Repos/test_recurrent.py";

// 所有参数按命令行顺序依次放入数组
const pythonProcess = spawn('python3', [
  scriptPath,
  '--name', 'Default_name',
  '--dataroot', '/home/usr/UIInputs',
  '--which_epoch', '72000',
  '--ancho_ventana', '512',
  '--alto_ventana', '1200',
  '--numero_imagenes', '4',
  '--numero_generaciones', '7',
  '--output_path', '/home/usr/UIResults',
  '--xcoor', '1526', '1526', '1526', '1526',
  '--ycoor', '3995', '3995', '3995', '3995'
]);


console.log("--------------------SPAWN--------------------- ");
pythonProcess.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
  });
  
  pythonProcess.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`);
  });
  
  pythonProcess.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
  });
注意事项
  • 不要将选项和参数值合并为同一个字符串,比如错误写法:['--name "Default_name"'],这种写法会被Python的命令行解析工具识别为单个参数,导致解析失败
  • 如果参数值是动态变量,直接将变量替换对应位置的字符串即可,不需要手动添加引号处理特殊字符,spawn会自动完成转义

内容的提问来源于stack exchange,提问作者segu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:45:03