繁体   English   中英

Node.js 与 python-shell 通信

[英]Node.js communicate with python-shell

我在 nodejs 中有 json 数据。 我尝试将此数据传递给 python。 但我无法得到 PythonFIle 的回复。

json数据格式

[
    {
        id: 123,
        option: ["A","B"],
        description: "Why I can't pass this data to Python" 
    },
    {
        id: 456,
        option: ["A","B"],
        description: "Why I can't pass this data to Python" 
    },{....}
]

node.js

var { PythonShell } = require('python-shell'); 
let pyshell = new PythonShell('../pythonFile.py', { mode: 'json ' }); 
pyshell.send(jsonData)
pyshell.on('message', function (message) { //But never receive data from pythonFile.
        console.log("HIHI, I am pythonFile context") //Not appear this message
        console.log(message); //Not appear this message
    });
pyshell.end(function (err) { // Just run it
        if (err)  throw err;
        console.log('finished'); //appear this message
    });

python文件.py

import json
import sys

jsJSONdata = input() //recieve js data

print(jsJSONdata) //send jsJSONdata to nodejs

谢谢你的帮助。

首先,您不能通过 send() 方法发送 JSON 变量,因为该方法发送到只接受字符串和字节的标准输入。 请尝试执行我的示例:

测试.py

value = input()

print(f"Python script response: {value}")

测试.js

const {PythonShell} = require('python-shell')

const pyshell = new PythonShell('test.py');

pyshell.send(JSON.stringify({"hello": "hello"}));

pyshell.on('message', function (message) {
  console.log(message);
});

pyshell.end(function (err,code,signal) {
  if (err) throw err;
  console.log('finished');
});

如果此示例适合您,则将{"hello": "hello"}更改为jsonData

我希望我对你有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM