在nodejs中运行Python脚本 [英] Running Python script in nodejs

查看:488
本文介绍了在nodejs中运行Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用


  • npm python-shell软件包运行带有node.js服务器的python脚本

一个简单的程序运行完美。但是当我尝试使用python中的某些函数时,它会抛出一个错误。例如。

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.

我正在使用python中的 raw_input 在node.js中不起作用。

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

任何人都可以帮助我。

这里是python代码:

here is the python code :

while True :

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

Node.js代码:

Node.js code :

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


推荐答案

PythonShell接受可以传递给python脚本的参数通过 options 参数,例如示例

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

同时在python脚本中,您可以访问传递的参数:

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

这是python脚本接受的方式来自命令行的参数。

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

至于你的问题,我认为你不需要使用 raw_input 在python中,如果你将接受来自node.js的输入。也就是说,如果您只是将python用于后台进程。

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.

我希望有所帮助。

这篇关于在nodejs中运行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆