Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning data from Python to node.js

Tags:

python

node.js

I've been following along with a couple examples I found to call a Python script from Node. I'm able to execute the script, but I can't return data from Python.

test.js

var sys   = require('sys'),
    spawn = require('child_process').spawn,
    dummy  = spawn('python', ['test.py']);

dummy.stdout.on('data', function (data) {
sys.print("testing...\n");
sys.print(data);
});

test.py

import time
def dummy() :
    out = '';
    for i in range(0,10) :
        out += str(i + 1) + "\n"
        time.sleep(0.1)
    print out
    return out
if __name__ =='__main__' :
    dummy = dummy()

Could someone provide an example of how to return the results from test.py to test.js?

Thanks.

Note: test.py edited for proper indent.

like image 536
RobertFrenette Avatar asked Dec 29 '13 18:12

RobertFrenette


People also ask

Can we integrate Python with node js?

Now, you already have a simple API application built with Node. js and Python. Please note that this example is to show a concept of integrating them together, the scripts can be improved in Node. js for better API route structure and in Python for more complex data manipulation workflow.

How do I run a Python file in node?

const python = spawn('python3', ['public/script.py', 'welcome', 'Duyen']); That's it!

Why node js is better than Python?

js vs Python, Node. js is faster due to JavaScript, whereas Python is very slow compared to compiled languages. Node. js is suitable for cross-platform applications, whereas Python is majorly used for web and desktop applications.


1 Answers

I figured out how to do this, by printing the data in Python, and "listening" for the print in Node using stdout.on().

test.js

var sys   = require('sys'),
    spawn = require('child_process').spawn,
    dummy  = spawn('python', ['test.py']);

dummy.stdout.on('data', function(data) {
    sys.print(data.toString());
});

test.py

import time
def dummy() :
    out = '';
    for i in range(0,10) :
        out += str(i + 1) + ", "
        time.sleep(0.1)
    print out
if __name__ =='__main__' :
    dummy = dummy()
like image 170
RobertFrenette Avatar answered Oct 06 '22 01:10

RobertFrenette