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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With