1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It can run. But I have a question about the Python-shell API said Sends a message to the Python script via stdin. The data is formatted according to the selected mode (text or JSON), or through a custom function when formatter is specified.. So really can't send JSON ..? Sorry about my question. But I really want to know.
You can send JSON by only like a string, because if you send JSON variable without JSON.stringify(), your python scripts will accept [object Object]. But I think that it is no problem because you can use a json library for python (docs.python.org/3/library/json.html) and covert accepted string to JSON or from JSON to string. And you can convert the accepted string variable in your js event with function JSON.parse().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.