Noopur Nawge
Noopur Nawge

Reputation: 1

Running Python script in nodejs

I am trying to run a python script with node.js server using the

A simple program runs perfectly. But when I am trying to use some functions from python it throws a error. For eg.

I am writing a program to get input from the user and reply for the same.

I am using raw_input in python which is not working in node.js.

Can anyone please help me.

here is the python code :

while True :

question=raw_input('you :')
print cb1.ask(question)

Node.js code :

var PythonShell = require('python-shell');
PythonShell.run('index.py', function (err, results) {
  if (err) throw err;
  console.log('result: %j', results);
});

Upvotes: 0

Views: 5463

Answers (1)

jessireedev
jessireedev

Reputation: 99

PythonShell accepts arguments that you can pass to the python script via options arguments like in this example.

var PythonShell = require('python-shell');

var options = {
  mode: 'text',
  pythonPath: 'path/to/python',
  pythonOptions: ['-u'],
  scriptPath: 'path/to/my/scripts',
  args: ['value1', 'value2', 'value3']
};

PythonShell.run('my_script.py', options, function (err, results) {
  if (err) throw err;
  // results is an array consisting of messages collected during execution
  console.log('results: %j', results);
});

Meanwhile at python script, you can access the arguments passed by:

import sys 

arg1 = sys.argv[1] #value1
arg2 = sys.argv[2] #value2
arg3 = sys.argv[3] #value3

which is how a python script accepts arguments from the command line.

As for your problem, I think that you won't need to use raw_input in python if you'll be accepting input from node.js. That is, if you'll just be using python for a background process.

I hope that helps.

Upvotes: 3

Related Questions