使用python-shell将TypedArray数据从NodeJS发送到Python的最佳方法

我试图从NodeJS发送数据使用python-shell在Python中进行处理。 我的Python脚本需要一个float32数组,但我不知道如何使用python-shell发送该数据types。 我可以发送一个string没有问题,我知道我的Python脚本工作正常否则。 有没有办法直接发送数组或我需要做一些数据转换或parsing在Python?

这是我现在正在尝试的:

在Python中:

import sys input = sys.stdin.read() print type(input) 

在节点中:

 var PythonShell = require('python-shell'); var pyshell = new PythonShell('script.py', {mode:'binary'}); // data is float32 TypedArray pyshell.send(data).end(function(err){ if (err){console.log(err, 'did not work')}; }); pyshell.on('message', function (message) { console.log('message received', message); }); 

在这里我得到以下错误:

 net.js:655 throw new TypeError( ^ TypeError: Invalid data, chunk must be a string or buffer, not object at Socket.write (net.js:655:11) at PythonShell.send (/project/node_modules/python-shell/index.js:205:16) at Object.<anonymous> (/project/server.js:59:11) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:394:7) 

如果我将TypedArray转换为string,它会发送很好,但是在Python中接收这个长string感觉不对,而不是数组。 我确定有一个简单的修复。 任何意见将非常感激!

最后,我把我的float32数组转换为javascript的Buffer对象,并使用“二进制”模式。 此外,我需要从pyshell.on切换到pyshell.stdout.on这是在二进制模式,但在自述文件中的python壳testing脚本…

在节点中:

 var options = {mode: 'binary'}; var pyshell = new PythonShell('test.py', options); var data = Buffer.from(myFloat32TypedArray.buffer, 'float32'); pyshell.send(data).end(function(err){ if (err){ console.log(err) }else{ console.log('data sent') }; }); pyshell.stdout.on('data', function (data) { console.log(data); }); 

在Python中:

 input_data = np.frombuffer(sys.stdin.read(), dtype=np.float32) sys.stdout.write(input_data) 

我不知道直接的方式(我认为这不是一个好的方法),但是你可以在JavaScript方面使用JSON.stringify来把数组转换成一个string,把它发送给python,读取它作为原始input,将其转换回json对象(这将是一个数组)。

JAVASCRIPT侧:

 var a = [1,2,3]; pyshell.send(JSON.stringify(data), ....) 

PYTHON侧:

 import json,sys input = sys.stdin.read() print(json.loads(input))