javascript - NodeJS 和 Python 之间的通信 : Passing back multiple arguments

标签 javascript python node.js python-3.x child-process

截至目前,我正在使用内置的 child_process 来启动 Python 脚本并监听通过 stdout.on('data', (data)) 返回的任何数据,就像第一个 JS 代码的第 6 行一样。但是从我所做的谷歌搜索中,我只看到一个东西被传回或一组东西被传回的例子。我想知道是否有可能发回不止一个参数。下面是我的代码:

JS:

const spawn = require('child_process').spawn;
pythonProcess = spawn('python', ["/path/to/python/file"]);

pythonProcess.stdout.on('data', (data) => {
    console.log(data);
});

python :

import sys

var thing1 = "Cold";
var thing2 = "Hot";
var thing3 = "Warm";

print(thing1);
print(thing2);
print(thing3);
sys.stdout.flush();

但我想要发生的事情可能是传回一个数组之类的东西,里面装满了我想发回的东西,这样我就可以像这样在 JS 文件中访问它们:

const spawn = require('child_process').spawn;
pythonProcess = spawn('python', ["/path/to/python/file"]);

pythonProcess.stdout.on('data', (data) => {
    thing1 = data[0];
    thing2 = data[1];
    thing3 = data[2];
})

console.log('thing1: ' + thing1);
console.log('thing2: ' + thing2);
console.log('thing3: ' + thing3);

输出:

thing1: Hot
thing2: Cold
thing3: Warm

我该怎么做?

提前致谢!

最佳答案

Node.js 和 Python 之间没有直接通信的接口(interface),所以你不能传递自定义参数,你所做的只是使用 child_process 执行一个 python 程序,所以您不发送参数,在 'data' 上接收到的任何内容都是从 python 打印到 stdout 的内容。

所以你需要做的是序列化数据,然后在 Node 中反序列化它,你可以使用 JSON 来实现这一点。

从您的 python 脚本中,输出以下 JSON 对象:

{
   "thing1": "Hot",
   "thing2": "Cold",
   "thing3": "Warm"
}

在您的 Node.js 脚本中:

const spawn = require('child_process').spawn;
const pythonProcess = spawn('python', ["/path/to/python/file"]);

const chunks = [];

pythonProcess.stdout.on('data', chunk => chunks.push(chunk));

pythonProcess.stdout.on('end', () => {

    try {
        // If JSON handle the data
        const data = JSON.parse(Buffer.concat(chunks).toString());

        console.log(data);
        // {
        //    "thing1": "Hot",
        //    "thing2": "Cold",
        //    "thing3": "Warm"
        // }

    } catch (e) {
        // Handle the error
        console.log(result);
    }
});

请记住,data 是分块的,因此在解析 JSON 之前必须等到 end 事件发出,否则SyntaxError 将被触发。 ( Sending JSON from Python to Node via child_process gets truncated if too long, how to fix? )

您可以使用任何您觉得舒服的序列化类型,JSON 是最简单的,因为我们使用的是 javascript。


请注意,stdout 是一个流,因此它是异步的,这就是您的示例永远无法运行的原因。

pythonProcess.stdout.on('data', (data) => {
    thing1 = data[0];
    thing2 = data[1];
    thing3 = data[2];
})

// Things do not exist here yet
console.log('thing1: ' + thing1);
console.log('thing2: ' + thing2);
console.log('thing3: ' + thing3);

关于javascript - NodeJS 和 Python 之间的通信 : Passing back multiple arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352274/

相关文章:

python - 抛出什么异常? (Python)

Python - 将 float 四舍五入为整数的最佳方法是什么

node.js - Node.js 中的 Anytime 算法

node.js - 呃!网络。无法安装最新版本的 npm、yeoman、bower 和 grunt

javascript - 当窗口变量在 react 中发生变化时如何更新状态

python - 如何创建每个点有两种颜色的散点图?

javascript - 使用 1 个输入字段存储 2 个值

node.js - 直接流式表达响应时处理mongodb错误

javascript - YouTube 使用 Web Audio API 提取音频

javascript - 无限循环在哪里?