Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to install python packages in Node JS using python-shell package?

I just came to know that we can run Python scripts in Node JS using the below npm package.

python-shell

Is it possible to install python packages using the same library? Something like pip install package

I need to import a few libraries to work with the Python scripts.

If it is not possible with this package, is there any other way to achieve it?

like image 484
Anirudh Avatar asked May 10 '19 14:05

Anirudh


1 Answers

Here's the first file : test.js

let {PythonShell} = require('python-shell');
var package_name = 'pytube'
let options = {
    args : [package_name]
}
PythonShell.run('./install_package.py', options, 
    function(err, results)
    {
        if (err) throw err;
        else console.log(results);
    })

This file runs another file install_package.py with arguments given to that file through command line.
You can get the package name from your HTML by using something like document.getElementById().value()
Here's the second file:install_package.py

import os
import sys
os.system('python3 -m pip install {}'.format(sys.argv[1]))

This install whatever package name was passed to it.
As package pytube is already installed for me the output is:

rahul@RNA-HP:~$ node test.js
[ 'Requirement already satisfied: pytube in ./.local/lib/python3.7/site-packages (9.5.0)' ]

Same can be done using subprocess instead of os:

import subprocess
import sys
process = subprocess.Popen(['python3', '-m', 'pip', 'install', sys.argv[1]], stdout = subprocess.PIPE)
output, error = process.communicate()
output = output.decode("utf-8").split('\n')
print(output)

Output using subprocess:

rahul@RNA-HP:~$ node test.js
[ "['Requirement already satisfied: pytube in ./.local/lib/python3.7/site-packages (9.5.0)', '']" ]

Hope this helps.
Comment if anything can be improved.

like image 70
Rahul Avatar answered Sep 28 '22 04:09

Rahul