Javascript Python与Node-js通信
根据本教程,我一直在尝试在Node JS和Python之间进行通信: python文件读取javascript数组,并使用numpy模块打印总和。下面是python和NodeJS文件的代码 Python代码:Javascript Python与Node-js通信,javascript,python,node.js,numpy,Javascript,Python,Node.js,Numpy,根据本教程,我一直在尝试在Node JS和Python之间进行通信: python文件读取javascript数组,并使用numpy模块打印总和。下面是python和NodeJS文件的代码 Python代码: import sys, json, numpy as np #Read data from stdin def read_in(): lines = sys.stdin.readlines() return json.loads(lines
import sys, json, numpy as np
#Read data from stdin
def read_in():
lines = sys.stdin.readlines()
return json.loads(lines[0])
def main():
#get our data as an array from read_in()
lines = read_in()
#create a numpy array
np_lines = np.array(lines)
#use numpys sum method to find sum of all elements in the array
lines_sum = np.sum(np_lines)
#return the sum to the output stream
print lines_sum
#start process
if __name__ == '__main__':
main()
节点js代码:
var spawn = require('child_process').spawn,
py =spawn('python', ['compute_input.py']),
data = [1,2,3,4,5,6],
dataString='';
py.stdout.on('data', function(data) {
dataString += data.toString();
});
py.stdout.on('end', function() {
console.log('Sum = ', dataString);
});
py.stdin.write(JSON.stringify(data));
py.stdin.end();
错误消息:
Error: write EPIPE
at exports._errnoException (util.js:1018:11)
at Socket._writeGeneric (net.js:711:26)
at Socket._write (net.js:730:8)
at doWrite (_stream_writable.js:331:12)
at writeOrBuffer (_stream_writable.js:317:5)
at Socket.Writable.write (_stream_writable.js:243:11)
at Socket.write (net.js:657:40)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
Python脚本正在抛出一个错误。
python
命令调用了python3而不是python2.7,为python3编写了脚本,脚本出错<代码>EPIPE引发错误,因为python脚本过早结束,节点尝试从已关闭的管道中读取/写入数据。(1)这不是有效的python代码。(2) 你如何运行脚本?(1)你能澄清什么是无效的吗?(2) 我正在使用node js命令提示符运行脚本。函数定义如**def read_in():**
不应包含这些星号。如果单独运行Python脚本,解释器会告诉您。我猜node接受了来自子进程的错误消息。我知道python函数不使用**。我想弄清楚功能在哪里。请查看修订后的格式。如果没有它们,则更清晰:)您是否尝试手动运行Python脚本?可能有不太明显的错误。