是否可以使用 python-shell 包在 Node JS 中安装 python 包? [英] Is it possible to install python packages in Node JS using python-shell package?
问题描述
我刚刚知道我们可以使用下面的 npm 包在 Node JS 中运行 Python 脚本.
I just came to know that we can run Python scripts in Node JS using the below npm package.
是否可以使用相同的库安装 python 包?类似于 pip install package
Is it possible to install python packages using the same library?
Something like pip install package
我需要导入一些库来处理 Python 脚本.
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?
推荐答案
这是第一个文件: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);
})
此文件运行另一个文件 install_package.py
,并通过命令行为该文件提供参数.
您可以使用诸如 document.getElementById().value()
之类的东西从 HTML 中获取包名称
这是第二个文件:install_package.py
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]))
安装任何传递给它的包名.
由于包 pytube
已经为我安装,输出是:
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)' ]
同样可以使用 subprocess
而不是 os
来完成:
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)
使用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.
这篇关于是否可以使用 python-shell 包在 Node JS 中安装 python 包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!