【问题标题】:passing values from node.js to python function将值从 node.js 传递到 python 函数
【发布时间】:2023-01-26 05:52:26
【问题描述】:

我在 Node.js 中有这段代码

let options = req.body
PythonShell.run('./chat.py', options, function (err, results) {
    console.log(results)
})

在我的 chat.py 文件中,我有这个:

import sys
import json

def chatFun():
    options = json.loads(sys.argv[1])
    print(options)
    print(sys.argv[1])
    return

chatFun()

当我在没有 print(sys.argv[1]) 的情况下运行我的代码时,只需输入 print("hello world"),它就可以工作,但随后我输入 print(sys.argv[1]),它会给我:

null
null

不知道为什么会这样。谁能分享一些建议。

【问题讨论】:

    标签: javascript python node.js python-3.x pip


    【解决方案1】:

    这里的问题是,当您将选项变量传递给 PythonShell.run() 函数时,它没有被正确转换为可以作为命令行参数传递给 Python 脚本的字符串。

    Python 中的 sys.argv[1] 变量用于访问传递给脚本的命令行参数,在本例中,它需要选项变量的字符串表示形式。但是,由于选项未正确转换为字符串,因此 sys.argv[1] 返回 null。

    您可以尝试使用将选项变量转换为字符串

    JSON.stringify() before passing it to the PythonShell.run() function:
    let options = req.body
    let optionsStr = JSON.stringify(options)
    PythonShell.run('./chat.py', optionsStr, function (err, results) {
        console.log(results)
    })
    

    此外,在您的 chat.py 文件中,您应该使用 json.loads() 将选项的字符串表示解析为字典对象。

    import sys
    import json
    
    def chatFun():
        options = json.loads(sys.argv[1])
        print(options)
        return
    
    chatFun()
    

    这应该正确地将选项变量作为命令行参数传递给 Python 脚本,并允许您使用 sys.argv[1] 访问它的值。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2017-07-19
      • 2020-05-31
      • 2020-03-24
      • 2017-09-21
      • 1970-01-01
      相关资源
      最近更新 更多