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 :
## 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/
If I'm inside my_folder and run the command node start.js, I get Sum of number=45, the scripts is working.
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.
Why ??
1 Answer 1
Most obvious reason: you are using a relative path for your python script so it's looked up in the current working directory. 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.
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)