Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call python script using node.js child_process

I was trying to call a python code from my node file.

Here is my node.js Code:

var util = require("util");

var spawn = require("child_process").spawn;
var process = spawn('python',["workpad.py"]);

util.log('readingin')

process.stdout.on('data',function(data){
    util.log(data);
});

and my python part:

import sys

data = "test"
print(data)
sys.stdout.flush()

In the cmd window, only util.log('readingin') is shown. What's the problem of my code?

like image 441
Bing Gan Avatar asked Dec 10 '15 23:12

Bing Gan


1 Answers

There is no problem ...

Here is a slight tweak of your working code (I convert the buffer to string so its human readable)

// spawn_python.js
var util = require("util");

var spawn = require("child_process").spawn;
var process = spawn('python',["python_launched_from_nodejs.py"]);

util.log('readingin')

process.stdout.on('data',function(chunk){

    var textChunk = chunk.toString('utf8');// buffer to string

    util.log(textChunk);
});

and here is your python

# python_launched_from_nodejs.py
import sys

data = "this began life in python"
print(data)
sys.stdout.flush()

finally here is output of a run

node spawn_python.js 
11 Dec 00:06:17 - readingin
11 Dec 00:06:17 - this began life in python

node --version

v5.2.0

like image 168
Scott Stensland Avatar answered Oct 16 '22 12:10

Scott Stensland