5

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?

4
  • Just to clarify you want to install python packages using python-shell from node-js? Commented May 10, 2019 at 14:27
  • @Rahul yes. I'm new to this package, I'm not sure whether it is possible. Commented May 10, 2019 at 14:28
  • Why not install directly using pip on the terminal? or is it you want to incorporate into something? Commented May 10, 2019 at 14:29
  • @Rahul, I have a node app running on ubuntu server. Is it possible to run pip along with the Node app? Commented May 10, 2019 at 14:33

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.