node js raspberry pi spawn python script code example

Example 1: child process spawn python node js

const path = require('path')
const {spawn} = require('child_process')
/**
   * Run python myscript, pass in `-u` to not buffer console output
   * @return {ChildProcess}
*/
function runScript(){
   return spawn('python', [
      "-u",
      path.join(__dirname, 'myscript.py'),
     "--foo", "some value for foo",
   ]);
}
const subprocess = runScript()
// print output of script
subprocess.stdout.on('data', (data) => {
   console.log(`data:${data}`);
});
subprocess.stderr.on('data', (data) => {
   console.log(`error:${data}`);
});
subprocess.stderr.on('close', () => {
   console.log("Closed");
});

Example 2: child process spawn python node js

#Import library
import sys, getopt, time
def main(argv):
   argument = ''
   usage = 'usage: myscript.py -f <sometext>'
   # parse incoming arguments
   try:
      opts, args = getopt.getopt(argv,"hf:",["foo="])
   except getopt.GetoptError:
      print(usage)
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print(usage)
         sys.exit()
      elif opt in ("-f", "--foo"):
         argument = arg
   # print output
   print("Start : %s" % time.ctime())
   time.sleep( 2 )
   print('Foo is')
   time.sleep( 2 )
   print(argument)
   print("End : %s" % time.ctime())
if __name__ == "__main__":
main(sys.argv[1:])