简体   繁体   English

节点与python之间的通信

[英]Communication between node and python

I have a node script : 我有一个节点脚本:

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

and a python script : 和一个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()

These two scripts are in a folder my_folder/ 这两个脚本位于文件夹my_folder /中

If I'm inside my_folder and run the command node start.js , I get Sum of number=45 , the scripts is working. 如果我在my_folder内并运行命令node start.js ,则得到Sum of number=45 ,脚本正在运行。

If I'm outside the folder and run the command node my_folder/start.js , I get Sum of number= , the script is not working. 如果我不在文件夹中并运行命令node my_folder/start.js ,则得到Sum of number= ,脚本无法正常工作。

Why ?? 为什么??

Most obvious reason: you are using a relative path for your python script so it's looked up in the current working directory. 最明显的原因:您正在为Python脚本使用相对路径,因此会在当前工作目录中查找它。 If you execute your node.js script from the same directory the python script is found, if you execute it from anywhere else (that doesn't happen to contain a compute_input.py file xD) then the python script is not found and the python call fails. 如果您从同一目录执行node.js脚本,则会找到python脚本,如果您从其他任何地方执行该脚本(该脚本恰好不包含compute_input.py文件xD),则找不到python脚本,并且python通话失败。

Use the absolute path instead and you should be fine (how you get the absolute path from your node.js script is left as an exercice) 请改用绝对路径,您应该没事(如何从node.js脚本获取绝对路径作为练习)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM