Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a Python script in Node.js synchronously?

Tags:

python

node.js

I am running the following Python script in Node.js through python-shell:

import sys
import time
 x=0
 completeData = "";
 while x<800:
  crgb =  ""+x;
  print crgb
  completeData = completeData + crgb + "@";
  time.sleep(.0001)
  x = x+1
  file = open("sensorData.txt", "w")
  file.write(completeData)
  file.close()
  sys.stdout.flush()
else:
 print "Device not found\n"

And my corresponding Node.js code is:

var PythonShell = require('python-shell');

PythonShell.run('sensor.py', function (err) {
    if (err) throw err;
    console.log('finished');
});
console.log ("Now reading data");

Output is:

Now reading data
finished

But expected output is:

finished 
Now reading data

Node.js can not execute my Python script synchronously, it executes first all the code following the PythonShell.run function then executes PythonShell.run. How can I execute first PythonShell.run then the following code? Any help will be mostly appreciated... It is an emergency please!

like image 520
Ramzan Avatar asked Nov 20 '22 22:11

Ramzan


1 Answers

It work for me:

let {PythonShell} = require('python-shell');

var options = {
    mode:           'text',
    pythonPath:     'python',
    pythonOptions:  [],
    scriptPath:     '',
    args:           []
};

async function runTest()
{
    const { success, err = '', results } = await new Promise(
        (resolve, reject) =>
        {
            PythonShell.run('hello.py', options,
                function (err, results)
                {
                    if (err)
                    {
                        reject({ success: false, err });
                    }

                    console.log('PythonShell results: %j', results);

                    resolve({ success: true, results });
                }
            );
        }
    );

    console.log("python call ends");

    if (! success)
    {
        console.log("Test Error: " + err);
        return;
    }

    console.log("The result is: " + results);

    // My code here

    console.log("end runTest()");
}

console.log('start ...');

runTest();

console.log('... end main');

The result is:

start ...
... end main
PythonShell results: ["Hello World!"]
python call ends
The result is: Hello World!
end runTest()
like image 58
Diarex Avatar answered Nov 25 '22 13:11

Diarex