【问题标题】:call python def function in nodejs在nodejs中调用python def函数
【发布时间】:2021-12-12 15:02:34
【问题描述】:

我在 nodejs 中运行 python 脚本。有用 。但我想保持打开状态,然后多次从 nodejs 调用 def 函数。我该怎么做。

nodejs

let {PythonShell}=require( 'python-shell');


let py=PythonShell.run('test.py', null, function (err, results) {

  console.log('results: %j', results);
});

test.py

print('start');

def hello():
    print ('hello');

【问题讨论】:

  • 你可以多次运行你的nodejs代码。把它放在一个函数中,然后调用它

标签: javascript python node.js


【解决方案1】:

在没有配置目标 Python 脚本的情况下,PythonShell 库不支持在运行时调用特定函数。例如,根据您当前的示例考虑以下 Python 脚本文件:

print('start')

def hello():
    print ('hello')

if "say-hello" in sys.argv:
    hello()

您可以在从 Node 调用脚本文件时传递 say-hello 参数,以按照您的意愿执行此方法:

let {PythonShell}=require( 'python-shell');


let py=PythonShell.run('test.py', ["say-hello"], function (err, results) {
  console.log('results: %j', results);
});

【讨论】:

  • 没有。例如,我想在第一个 python 中加载一个数据库。然后我想用不同的参数运行几次查询。如果我每次调用 python shell 时都运行你的代码,我应该等待加载 db。
  • 您选择的库不支持此类功能。为什么不直接在 Node 中以这样的速度做呢??
  • 因为数据库是二进制的,方法非常庞大。我无法将它们全部转换为 nodejs 。你有更好的解决方案吗
【解决方案2】:

如果我没记错的话,你想运行 python 脚本几次?

将let py=pythonShell... 放入一个函数中,并根据需要多次调用它

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多