首页 > 解决方案 > 将数据从节点发送到python并打印

问题描述

我一直在尝试在节点和 python 之间进行通信,我想将对象数组发送到 python,并在 python 中打印,但我的代码不起作用。

content=[
{

    "username": "admin",
    "first_name": "",
    "last_name": "",
    "roles": "system_admin system_user",
    "locale": "en",
    "delete_at": 0,
    "update_at": 1511335509393,
    "create_at": 1511335500662,
    "auth_service": "",
    "email": "adminuser@cognizant.com",
    "auth_data": "",
    "position": "",
    "nickname": "",
    "id": "pbjds5wmsp8cxr993nmc6ozodh"
},
{

    "username": "chatops",
    "first_name": "",
    "last_name": "",
    "roles": "system_user",
    "locale": "en",
    "delete_at": 0,
    "update_at": 1511335743479,
    "create_at": 1511335743393,
    "auth_service": "",
    "email": "chatops@cognizant.com",
    "auth_data": "",
    "position": "",
    "nickname": "",
    "id": "akxdddp5p7fjirxq7whhntq1nr"
}]

JavaScript 代码:

const express=require('express')

const app=express()

let p = require('python-shell');

app.get('/send',(req,res)=>{


    var options = {
        args:
        [
          content

        ]
      }
      p.PythonShell.run('hello.py', options, function  (err, results)  {


        console.log(results.toString())

      });

})

app.listen('5000')

Python脚本:

import sys 

import json

details=sys.argv[1]

print (details)

标签: javascriptpythonnode.jsjson

解决方案


由于我们无法将对象传递给命令行,因此python-shell正在调用 .toString()内容对象的方法。制作它object Object

解决方案:options将您的对象 更改为:

var options = {
        args:
        [
          JSON.stringify(content)

        ]
      }

在 python 文件中:

parsed = json.loads(sys.argv[1])
print (json.dumps(parsed))

推荐阅读