节点和python之间的通信

我有一个节点脚本:

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

这两个脚本位于一个文件夹my_folder /

如果我在my_folder里面并运行命令node start.js ,我得到Sum of number=45 ,脚本正在工作。

如果我在该文件夹之外并运行命令node my_folder/start.js ,则得到Sum of number= ,该脚本不起作用。

为什么?

最明显的原因是:你正在为你的Python脚本使用相对path,所以在当前的工作目录中查找它。 如果你从同一目录执行你的node.js脚本,python脚本被发现,如果你从其他地方执行它(这不会包含compute_input.py文件xD),那么python脚本没有find,python通话失败。

使用绝对path,你应该没问题(你如何得到你的node.js脚本的绝对path是作为一个练习)