Python – Import Python packages for scripts invoked using nodejs

Import Python packages for scripts invoked using nodejs… here is a solution to the problem.

Import Python packages for scripts invoked using nodejs

I’m trying to use Python scripts with NodeJS. The code below works, but I need a way to execute “pip install pandas” on “npm install”

Node

router.get('/', (req, res) => {
  const filePath = 'python/testing2.py' 
  const spawn = require("child_process").spawn;
  const pythonProcess = spawn('python3',[filePath, '-l']); 

util.log('readingin')
  pythonProcess.stdout.on('data', (data) => { 
    const textChunk = data.toString('utf8');// buffer to string
    util.log(textChunk);
    res.json({'working': true, 'data': textChunk})
  });
});

python :

import sys 
from pandas import read_csv
from pandas import datetime    

def parser(x):
    return datetime.strptime('190'+x, '%Y-%m')    

print("Output from Python") 
series = read_csv('shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
print (series)
sys.stdout.flush()

Solution

You can use the postinstall property of scripts in the package.json file to do this. This is a small demo code. (assuming the pip command works in your cmd).

"scripts": {
 "postinstall": "pip install pandas"
}

Related Problems and Solutions