在代码中安装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屋!