Receiving python code using nodejs - python

I'm using python-shell to run a python script that classifies an image and returns a yes/no if that image is what I'm looking for or not.
Node.js code:
app.get('/classify', function(req, res) {
var options = {
mode: 'text',
pythonOptions: ['-u'],
scriptPath: 'src/',
args: ['--image', '../../images/image.png', 'classifer.xml']
};
PythonShell.run('classify_images.py', options, function(err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
res.send('classify');
});
If I run the command as a python script, it works fine but when I run it through node.js, it gives me back all no's.
The python command (in src) is:
python classify_images.py --image ../../images/image.png classifer.xml

Apparently I didn't put in the right file path - it worked after that.

Related

How can I use node.js to run a python file that runs forever?

I am wondering how to use node.js to run a python file that prints until it stops.
Right now when I run it it does not print anything, is there a way I can make it work properly?
Node.js
let {PythonShell} = require('python-shell')
var options = {
pythonOptions: ['-u']
};
PythonShell.run('main.py', options, function (err, result){
if (err) throw err;
// result is an array consisting of messages collected
//during execution of script.
if (result !== null){
console.log(result.toString());
}
});
PythonShell.run('main.py', options, function (err, result){
if (err) throw err;
// result is an array consisting of messages collected
//during execution of script.
if (result !== null){
console.log(result.toString());
}
});
A function similar to mine
main.py
num = 1
while True:
print(num)
num += 1
I'm not familiar with python-shell package but you can easily spawn a new process to run python programs by using spawn method from child_process package that comes with node.
Here is how you can use it:
const { spawn } = require("child_process");
const cmd = spawn("python3", [__dirname + "/main.py"]);
cmd.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
});
cmd.stderr.on("data", (data) => {
console.error(`stderr: ${data}`);
});
cmd.on("close", (code) => {
console.log(`child process exited with code ${code}`);
});
Read the documentation for more info [link]

pythonPath for python-shell is not working after when electron is build

I'm using electron app to run python scripts using python-shell. I have set pythonPath to my anaconda env shown below. This works find when I run the app but after packing the app with electron-builder, it shows the following error: No such file or directory found even I'm using absolute path on the same PC.
const {PythonShell} = require('python-shell');
const path = require('path');
const options = {
mode: 'text',
pythonPath: 'C:/Users/nauma/.conda/envs/YOLO/python.exe',
pythonOptions: ['-u'], // get print results in real-time
scriptPath: path.join(__dirname, '/build/engine/')
};
PythonShell.run('index.py', options, function (err, res) {
if (err) throw err;
console.log(res);
});
Exception after building app is shown below:
[
on windows when not setting pythonPath,
python shell could find by itself the path to python,
potentially using an env var or registry key.
But to make sure my electron app would run everywhere,
I prefered to embed python using a specific configuration
for electron builder to bundle python
package.json:
"build": {
"appId": "angular_electron.id",
"extraFiles": [
{
"from": "resources/${os}",
"to": "Resources",
}
]
}
and calling python using the right resourcepath:
import { isPackaged } from 'electron-is-packaged';
const resourcesPath = isPackaged
? join(rootPath, './resources')
: join(rootPath, './resources', getPlatform());
pyshell.PythonShell.run('hello.py',
{pythonPath:join(resourcesPath,'/python-3.6.3-embed-amd64/python.exe'),scriptPath:join(resourcesPath,'/bin')},
function (err, results) {
if (err) throw err;
console.log('hello.py finished.');
console.log('results:', results);
});

Python script works alone but no such file when run through nodejs child process

Error, could not create TXT output file: No such file or directory
tesseract ./downloads/en.jpg outputs/1585336201.287781output -l eng
is the error i'm having trouble with, this command works fine from the python script but not through a childprocess spawn, downloads and the .py script are in the same folder, and both of them are in a folder next to the nodejs script
this is the method that i call from a post function to give it the imagine fine that i need to transcribe, then the python script can't run the tesseract command, even though it can do it when its run manually
const verif = async (fileName, filePath) => {
var uint8arrayToString = function(data){
return String.fromCharCode.apply(null, data);
};
const spawn = require('child_process').spawn;
const scriptExecution = spawn('python',['-u', './diploma/app.py']);
var data = JSON.stringify([fileName]);
scriptExecution.stdin.write(data);
scriptExecution.stdin.end();
scriptExecution.stdout.on('data', (data) => {
console.log(uint8arrayToString(data));
});
scriptExecution.stderr.on('data', (data) => {
// As said before, convert the Uint8Array to a readable string.
console.log(uint8arrayToString(data));
});
scriptExecution.on('exit', (code) => {
console.log("Process quit with code : " + code);
});
return true;
}
The problem was that tesseract needed windows permissions when executed from the js file

running a Python script from a Node.Js application

I absolutely love using Node.JS for my web projects but i also love using Python at the same time, so i have been wondering, if is it possible to run Python scripts from Node, for example my Node.JS backend calls a python script to retrive some data from a SQL Database and gives it back to Node (i know i can do that all in Node but just using an example). I thought about doing it this way
1.Node creates a Json files which contains the variable the Python script will use(for example name:Jon birthDate:1996)
2.It runs a python script that reads those variables from that Json file(so it searches for Jon born in 1996)
3.It deletes the Json file when its done
4.Rinse and Repeat
Would this be a good and safe way of doing this type of thing or are there any other ways of running and "modifiying" the Python script?
I had to build a node app, but for the backend calculations, it seemed better to use NumPy and Pandas, so I did what you are doing... in the end I found an npm package called python-shell.
It works via promises, so I'd call my calculation script, and also would do some clean up with another Python script if there were any errors.
Worked pretty good. Code was something like this:
const PythonShell = require('python-shell');
router.get('/calc', (req, res) => {
PythonShell.run('py/calculate.py', {pyPath: pyPath , args: [tmpPath],}, function(err, results) {
if (err) {
PythonShell.run('py/clean_up.py', {pyPath: pyPath, args: [tmpPath2]}, function(err, results2) {
if (err) throw err;
res.json(
{
message: "error: Running clean up",
ang: 0,
vec: 0,
}
);
});
} else {
let data = JSON.parse(results);
let message = data[0];
let ang = data[1];
let vec = data[2];
res.json(
{
message: message,
ang: ang,
vec: vec,
}
);
}
});
});

Interact with python script inside nodejs application at runtime

Hello I'm trying to interact with a python script inside a nodejs application at runtime.
The python script is more a command center for doing whatsapp operations called yowsup.
https://github.com/tgalal/yowsup/tree/master
I'm able to run the 'Yowsup Cli client' in a shell and work with it. But I want to run it in a nodejs application because it is written in python and I'm not good in python.
So what I did was to spawn the command I normally use in the shell like this:
var spawn = require('child_process').spawn,
ls = spawn('./yowsup/yowsup-cli', ['demos','--login', '49XXXXXXXXXXX:8bF0hUewVcX1hf6adpuasonFdEP=', '--yowsup', '-E', 's40']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code.toString());
});
The problem is, that I don't get any data from the process. The python script normally prints some output as start but I can't get anything inside node while the process is running.
I looked inside the python script and saw that the output is generated like this:
print("%s send '%s'" % (messageProtocolEntity.getFrom(False), messageProtocolEntity.getBody()))
How can I get some data from the python script on runtime?
This is slightly different than your approach and uses an npm lib, but does work (results is the stdout of the random_geo.py script):
var py = require('python-shell');
var pyOptions = {
mode: 'text',
pythonPath: '/opt/local/bin/python',
scriptPath: '.'
};
function getCoords(req, res, next) {
py.run('random_geo.py', pyOptions, function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
}
});
}

Categories

Resources