Using the Node.js child_process module to create and use a python3 process to do a sum over an array.
node father.js
Using the Node.js child_process module to create and use a python3 process to do a sum over an array.
node father.js
/* Generate a python process using nodejs child_process module */ | |
var spawn = require('child_process').spawn, | |
py_process = spawn('python3', ['son.py']), | |
data = getData(), | |
dataResult = ''; | |
/* Define what to do on everytime node application receives data from py_process */ | |
py_process.stdout.on('data', function(data){ | |
dataResult += data.toString(); | |
}); | |
/* At the end, show the result from py_process computing (stored in 'dataResult') */ | |
py_process.stdout.on('end', function(){ | |
console.log('Sum result: ', dataResult); | |
}); | |
/* Stringify the array before send to py_process */ | |
py_process.stdin.write(JSON.stringify(data)); | |
/* Close the stream */ | |
py_process.stdin.end(); | |
function getData() { | |
return [1, 8, 16, 32, 64, 128, 256]; | |
} |
import sys | |
import json | |
# Read data from the Writable Stream | |
def read_in(): | |
lines = sys.stdin.readlines() | |
return json.loads(lines[0]) | |
# Work work | |
def compute_sum(data): | |
return sum(data) | |
def main(): | |
# Store the data as an array in 'data_input' | |
data_input = read_in() | |
# Compute the sum | |
sum_result = compute_sum(data_input) | |
# Return the sum | |
sys.stdout.write(str(sum_result)) | |
# Start the process | |
if __name__ == '__main__': | |
main() |