0

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

  • npm python-shell package

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);
});

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.