How to call python script from NodeJs

后端 未结 5 963
轻奢々
轻奢々 2020-12-01 07:06

I need to call this python script in NodeJs.

Read.py

#!/usr/bin/env python
# -*- coding: utf8 -*-

import RPi.GPIO as GPIO
import MF         


        
5条回答
  •  星月不相逢
    2020-12-01 07:25

    • install python-shell :- npm install python-shell

      Index.js

      let {PythonShell} = require('python-shell')
      
      function runPy(){
          return new Promise(async function(resolve, reject){
                let options = {
                mode: 'text',
                pythonOptions: ['-u'],
                scriptPath: './test.py',//Path to your script
                args: [JSON.stringify({"name": ["xyz", "abc"], "age": ["28","26"]})]//Approach to send JSON as when I tried 'json' in mode I was getting error.
               };
      
                await PythonShell.run('test.py', options, function (err, results) {
                //On 'results' we get list of strings of all print done in your py scripts sequentially. 
                if (err) throw err;
                console.log('results: ');
                for(let i of results){
                      console.log(i, "---->", typeof i)
                }
            resolve(results[1])//I returned only JSON(Stringified) out of all string I got from py script
           });
         })
       } 
      
      function runMain(){
          return new Promise(async function(resolve, reject){
              let r =  await runPy()
              console.log(JSON.parse(JSON.stringify(r.toString())), "Done...!@")//Approach to parse string to JSON.
          })
       }
      
      runMain() //run main function
      

    test.py

        import sys #You will get input from node in sys.argv(list)
        import json
        import pandas as pd #Import just to check if you dont have pandas module you can comment it or install pandas using pip install pandas
    
        def add_two(a, b):
            sum = 0
            for i in range(a, b):
                sum += i
            print(sum)  
    
        if __name__ == "__main__":
            print("Here...!")
            # print(sys.argv)
            j = json.loads(sys.argv[1]) #sys.argv[0] is filename
            print(j)
            add_two(20000, 5000000) #I make this function just to check 
        # So for all print done here you will get a list for all print in node, here-> console.log(i, "---->", typeof i)
    

提交回复
热议问题