How to run a Python script in Node.js synchronously?
Question: I am running the following Python script in Node.js through [python-
shell](https://github.com/extrabacon/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!


Answer: As this is asynchronous, add an end callback (found in the documentation)
instead of instructions at top level

    
    
    // end the input stream and allow the process to exit 
    pyshell.end(function (err) {
      if (err) throw err;
      console.log ("Now reading data");
    });
    

