[英]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. 我才知道我们可以使用下面的npm包在Node JS中运行Python脚本。
Is it possible to install python packages using the same library? 是否可以使用相同的库安装python软件包? Something like
pip install package
像
pip install package
这样的东西
I need to import a few libraries to work with the Python scripts. 我需要导入一些库来使用Python脚本。
If it is not possible with this package, is there any other way to achieve it? 如果无法使用此软件包,是否还有其他方法可以实现?
Here's the first file : test.js
这是第一个文件:
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. 该文件运行另一个文件
install_package.py
,其参数通过命令行指定给该文件。
You can get the package name from your HTML by using something like document.getElementById().value()
您可以使用诸如
document.getElementById().value()
类的东西从HTML中获取包名称document.getElementById().value()
Here's the second file: install_package.py
这是第二个文件:
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: 由于已经为我安装了
pytube
软件包,因此输出为:
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
: 使用
subprocess
而不是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
: 使用
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. 评论是否有任何可以改进的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.