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.
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.
const python = spawn('python3', ['public/script.py', 'welcome', 'Duyen']); That's it!
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With