0

I am trying to return a json object from a javascript function which runs a python script.

I have a python script which goal is to build a list as below (here i provide only the result).

mydict ={
  "counterParty_Car": "Ford",
  "counterParty_CarPlate" : "O XXX YYY",
  "counterParty_Name" : "John Snow",
  "counterParty_Policy": "0123456789"      
}
print(mydict)

this python script is launched by a function on javascript using pyhton-shell

function runPythonScript(pythonPath, pythonScript){
    console.log('ND - server - run python without argument');
    let myPath = __dirname;
    console.log('myPath: ', myPath);
    //let pythonPath = pythonPath;
    console.log('pythonPath: ', pythonPath);
    //let pythonScript = pythonScript;
    console.log('pythonScript: ', pythonScript);
    
    //Here are the option object in which arguments can be passed for the python_test.js.
    let options = {
        mode: 'text',
        pythonOptions: ['-u'], // get print results in real-time
        scriptPath: myPath + pythonPath //If you are having python_test.py script in same folder, then it's optional.
        //args: ['xxxx'] //An argument which can be accessed in the script using sys.argv[1]
    };

    PythonShell.run(pythonScript, options, function (err, result){
        if (err) throw err;
        // result is an array consisting of messages collected
        //during execution of script.
        console.log('data: ', result.toString());
        let parsedData = JSON.parse(JSON.stringify(result.join('\n')));
        console.log('data type: ',typeof parsedData, ' of length ', parsedData.length);
        parsedData = parsedData.replace(/'/g, `"`); // replace the quote by the double quotes for parsing the string to a JSON object.
        parsedData = JSON.parse(parsedData);
        console.log('parsed data type: ', typeof parsedData);
        console.log('parsed data: ', parsedData);
        return parsedData;
    });
}

In javascript I finally call the runPythonScript as below

let counterpartyData = runPythonScript('/python','test.py');
console.log('ND - server - counterparty data: ', counterpartyData);

But when check the result on the console, i see that counterpartyData is undefined. Do you have an idea why?

ND - server - run python without argument
myPath:  /app
pythonPath:  /python
pythonScript:  test.py
[...]
parsed data:  {
counterParty_Car: 'Ford',
counterParty_CarPlate: 'O XXX YYY',
counterParty_Name: 'John Snow',
counterParty_Policy: '0123456789'
}
ND - server - counterparty data:  undefined
Nassim
  • 117
  • 9
  • 2
    `return parsedData;` returns from the inner function you're passing to .run(), *not* your own runPythonScript() function. You need to promisify the callback function and use async / await. Further reading: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron and https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call –  Jan 12 '22 at 12:28
  • Here's a live example that explains the problem and shows how to promisify a callback based API: https://jsfiddle.net/nqvsuch2/ –  Jan 12 '22 at 12:36
  • Hi @ChrisG thanks for your help. I just started with JS so I don't really get how to use this async thing. Could you please show me directly with my example how to use it? – Nassim Jan 12 '22 at 12:57
  • 1
    Right, try this version: https://pastebin.com/a6eWa07u –  Jan 12 '22 at 13:05
  • @ChrisG tank you very much! it's working perfectly. – Nassim Jan 12 '22 at 14:49

0 Answers0