在代码中安装 python 模块 [英] Installing python module within code
问题描述
我需要直接在我的脚本中安装来自 PyPi 的软件包.也许有一些模块或 distutils
(distribute
、pip
等)功能允许我执行类似 pypi.install('requests')
并且请求将安装到我的 virtualenv 中.
I need to install a package from PyPi straight within my script.
Maybe there's some module or distutils
(distribute
, pip
etc.) feature which allows me to just execute something like pypi.install('requests')
and requests will be installed into my virtualenv.
推荐答案
官方推荐的从脚本安装软件包的方法是通过子进程调用 pip 的命令行界面.pip 不支持此处提供的大多数其他答案一>.此外,自 pip v10 起,所有代码都已精确移至 pip._internal
以向用户明确表示不允许以编程方式使用 pip.
The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal
precisely in order to make it clear to users that programmatic use of pip is not allowed.
使用 sys.executable
确保您将调用与当前运行时关联的相同 pip
.
Use sys.executable
to ensure that you will call the same pip
associated with the current runtime.
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
这篇关于在代码中安装 python 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!