从NodeJS运行python

时间:2018-04-29 21:19:32

标签: python node.js

我正试图运行这个例子:

//start.js
var spawn = require('child_process').spawn,
    py    = spawn('python', ['compute_input.py']),
    data = [1,2,3,4,5,6,7,8,9],
    dataString = '';

py.stdout.on('data', function(data){
  dataString += data.toString();
});
py.stdout.on('end', function(){
  console.log('Sum of numbers=',dataString);
});
py.stdin.write(JSON.stringify(data));
py.stdin.end();

这是一个Python脚本:

## compute_input.py

import sys, json, numpy as np

#Read data from stdin
def read_in():
    lines = sys.stdin.readlines()
    #Since our input would only be having one line, parse our JSON data from that
    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 start.js时,我会收到输出“Sum of numbers=”,但我希望“Sum of numbers=45”。

似乎Python没有运行。我安装了numpy并使用Python 3。

其他用户收到正确的结果,但我没有。可能是什么原因?

0 个答案:

没有答案