I need to call this python script in NodeJs.
Read.py
#!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import MF
If you like to avoid package managers / bloat, consider writing a shell script function to run the python, stream results locally to a txt file, collect and send on e.g. using http:
const { exec } = require("child_process");
function runShellScript(script, callback) {
exec(script, (error, stdOut, stderr) => {
var result = {status: true};
if (error) {
result.status = false;
result.error = error.message;
}
if (stderr) {
result.status = false;
result.stderr = stderr;
}
if(stdOut){
result.result = stdOut;
}
callback(result);
});
}
runShellScript("python3 myscript.py >> output.txt", function(res) {
console.log(res);
fs.readFileSync('output.txt');
});
Adopt a micro-services approach. Host the Python script as a HTTP REST API service. Consume the API from node.js - you do not need to integrate the technologies; it's not scalable.
install python-shell :- npm install python-shell
Index.js
let {PythonShell} = require('python-shell')
function runPy(){
return new Promise(async function(resolve, reject){
let options = {
mode: 'text',
pythonOptions: ['-u'],
scriptPath: './test.py',//Path to your script
args: [JSON.stringify({"name": ["xyz", "abc"], "age": ["28","26"]})]//Approach to send JSON as when I tried 'json' in mode I was getting error.
};
await PythonShell.run('test.py', options, function (err, results) {
//On 'results' we get list of strings of all print done in your py scripts sequentially.
if (err) throw err;
console.log('results: ');
for(let i of results){
console.log(i, "---->", typeof i)
}
resolve(results[1])//I returned only JSON(Stringified) out of all string I got from py script
});
})
}
function runMain(){
return new Promise(async function(resolve, reject){
let r = await runPy()
console.log(JSON.parse(JSON.stringify(r.toString())), "Done...!@")//Approach to parse string to JSON.
})
}
runMain() //run main function
test.py
import sys #You will get input from node in sys.argv(list)
import json
import pandas as pd #Import just to check if you dont have pandas module you can comment it or install pandas using pip install pandas
def add_two(a, b):
sum = 0
for i in range(a, b):
sum += i
print(sum)
if __name__ == "__main__":
print("Here...!")
# print(sys.argv)
j = json.loads(sys.argv[1]) #sys.argv[0] is filename
print(j)
add_two(20000, 5000000) #I make this function just to check
# So for all print done here you will get a list for all print in node, here-> console.log(i, "---->", typeof i)
There are multiple ways of doing this.
npm install python-shell
and here's the code
var PythonShell = require('python-shell');
//you can use error handling to see if there are any errors
PythonShell.run('my_script.py', options, function (err, results) {
//your code
you can send a message to python shell using
pyshell.send('hello');
you can find the API reference here- https://github.com/extrabacon/python-shell
second way - another package you can refer to is node python , you have to do npm install node-python
third way - you can refer to this question where you can find an example of using a child process- How to invoke external scripts/programs from node.js
a few more references - https://www.npmjs.com/package/python
if you want to use service-oriented architecture - http://ianhinsdale.com/code/2013/12/08/communicating-between-nodejs-and-python/
Well yoy can run python script from node.js in way like this. Use child_process.spawn (this is build in node.js library)
router.get('/', (req, res) => {
const {spawn} = require('child_process');
const path = require('path');
function runScript(){
return spawn('python', [
path.join(__dirname, '../../scripts/myscript.py'),
'-some_arg',
'--another_arg',
]);
}
const subprocess = runScript();
// print output of script
subprocess.stdout.on('data', (data) => {
console.log(`data:${data}`);
});
subprocess.stderr.on('data', (data) => {
console.log(`error:${data}`);
});
subprocess.stderr.on('close', () => {
console.log("Closed");
});
// const subprocess = runScript()
res.set('Content-Type', 'text/plain');
subprocess.stdout.pipe(res);
subprocess.stderr.pipe(res);
});