Skip to content

Instantly share code, notes, and snippets.

@nikolasrangel
Last active January 3, 2018 01:47
Show Gist options
  • Save nikolasrangel/9b14a7379e110f42d185734921fd02e3 to your computer and use it in GitHub Desktop.
Save nikolasrangel/9b14a7379e110f42d185734921fd02e3 to your computer and use it in GitHub Desktop.
Node.js and Python communication

Node.js + Python

Using the Node.js child_process module to create and use a python3 process to do a sum over an array.

Usage

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment