Node.js与pythonshell通信

2024-09-29 02:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

jsonData格式

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

pythonFile.py

import json
import sys

jsJSONdata = input() //recieve js data

print(jsJSONdata) //send jsJSONdata to nodejs

谢谢你的帮助


Tags: to数据logjsonmessagedatanodejsthis
1条回答
网友
1楼 · 发布于 2024-09-29 02:28:05

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

test.py

value = input()

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

test.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

我希望我能帮助你

相关问题 更多 >