javascript - Python 和 Node.js 通信

标签 javascript python node.js numpy

我一直在尝试按照本教程在 Node JS 和 Python 之间进行通信:http://www.sohamkamani.com/blog/2015/08/21/python-nodejs-comm/

Python 文件读取 JavaScript 数组并使用 numpy 模块打印总和。以下是 python 和 Node js 文件的代码。

Python 代码:

    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()

Node 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 而不是 python 2.7,为此编写了脚本,但脚本出错了。由于 python 脚本过早结束并且 Node 尝试读取/写入已关闭的管道,因此引发了 EPIPE 错误。

关于javascript - Python 和 Node.js 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45617143/

相关文章:

javascript - 为什么这个 jQuery 片段之前没有动画一次?

python - 过零率

python - 在一行中查找一个字符串并返回找到的字符串正下方的字符串 - Python 或 UNIX

python 2 定时器不遵循顺序

javascript - 为什么要用一个复杂的函数来计算字符串的长度而不是 string.length?

javascript - 使用 onclick 事件停止 javascript 倒数计时器

javascript - 原型(prototype) javascript 无法正常工作

javascript - 放大可见图像的中心?

javascript - 无法在 import 或 require 中连接 var

javascript - element.setAttribute 元素 ['attr' 之间的任何差异] element.attr