Node.js与python shell通信
我在nodejs中有json数据。我尝试将这些数据传递给python。 但我无法从PythonFIle得到回复 jsonData格式Node.js与python shell通信,python,node.js,Python,Node.js,我在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"], descr
[
{
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
});
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');
});
pythonFile.py
import json
import sys
jsJSONdata = input() //recieve js data
print(jsJSONdata) //send jsJSONdata to nodejs
value = input()
print(f"Python script response: {value}")
感谢您的帮助。首先,您不能通过send()方法发送JSON变量,因为此方法发送到只接受字符串和字节的stdin。 请尝试执行我的示例: test.py
import json
import sys
jsJSONdata = input() //recieve js data
print(jsJSONdata) //send jsJSONdata to nodejs
value = input()
print(f"Python script response: {value}")
test.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
});
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
希望我能帮助你。谢谢。它可以运行。但是我有一个关于pythonshellapi的问题,即通过stdin向Python脚本发送消息。数据根据所选模式(文本或JSON)进行格式化,或者在指定formatter时通过自定义函数进行格式化。。所以真的不能发送JSON吗。。?对不起,我的问题。但我真的很想知道,你只能像字符串一样发送JSON,因为如果你发送的JSON变量没有JSON.stringify(),你的python脚本将接受[object]。但我认为这没有问题,因为您可以使用python()的json库并将接受的字符串转换为json或从json转换为字符串。您可以使用函数JSON.parse()在js事件中转换接受的字符串变量。