Running Python script in nodejs

北城以北 提交于 2019-12-08 10:56:18

问题


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:


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.



来源:https://stackoverflow.com/questions/28713694/running-python-script-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!