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

一个人想着一个人 提交于 2020-12-30 02:14:52

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/56079548/is-it-possible-to-install-python-packages-in-node-js-using-python-shell-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!