Hamza
Hamza

Reputation: 21

How to run python environment through node.js

I am developing a web application that will use python model.I have created environment for python model as well.But the problem i am facing is i have no idea how to execute that python environment through node js because i am using node.js at backend.

Upvotes: 2

Views: 3436

Answers (2)

Mussa Charles
Mussa Charles

Reputation: 849

After you setting your python virtual enironment, You can use PythonShell in node js Firstly install PythonShell to your project by this command npm install python-shell --save

then you can call python script in your js file by the following

const path = require('path');
const { PythonShell } = require("python-shell");

// this is your current folder

const py_path = path.join(__dirname, '');

// this is your folder with python environment in it

const python_exe_path = path.join(__dirname, 'python_env/scripts/python.exe'); 


// then create your python shell options

const py_shell_options = {
    mode: 'text',
    pythonPath: python_exe_path,
    pythonOptions: ['-u'], // get print results in real-time
    scriptPath: py_path
    // args: ['value1', 'value2', 'value3']
};

// now you can initialize your shell and ready to use it

const pyshell = new PythonShell('py_scripts/my_script.py', py_shell_options);

// sends a message to the Python script via stdin

pyshell.send('hello');

pyshell.on('message', function (message) {
  // received a message sent from the Python script (a simple "print" statement)
  console.log(message);
});

// end the input stream and allow the process to exit

pyshell.end(function (err,code,signal) {
  if (err) throw err;
  console.log('The exit code was: ' + code);
  console.log('The exit signal was: ' + signal);
  console.log('finished');
});

That it, please read more about PythonShell from the official site

Upvotes: 2

Taher Fattahi
Taher Fattahi

Reputation: 1007

you can run python virtual environment inside nodejs, you need call python environment from bin directory where you install python virtual environment, and then you can use child_process for run python code inside nodejs, see this example:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('~/py3env/bin/python', ['test.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(3000, () => console.log('listening on port 3000')) 

even you can excecute command line with shelljs, and in this moment you can run pm2: see this:

const shell = require('shelljs');

shell.exec('pm2 start test.py --interpreter=./py3env/bin/python', function(code, output) {
  console.log('Exit code:', code);
  console.log('Program output:', output);
});

Upvotes: 5

Related Questions