Creek
Creek

Reputation: 215

Node.js communicate with python-shell

I have the json data in nodejs. And I try to pass this data to python. But I can't get a reply from PythonFIle.

jsonData Format

[
    {
        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

Thanks for your help.

Upvotes: 1

Views: 1782

Answers (1)

Nazarii Kulyk
Nazarii Kulyk

Reputation: 46

First of all, you can not send a JSON variable by send() method, because this method sends to stdin which accepts only string and bytes. Please try to execute my example:

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');
});

If this example works for you, then change {"hello": "hello"} to jsonData.

I hope that I helped you.

Upvotes: 1

Related Questions