在代码中安装 python 模块 [英] Installing python module within code

查看:36
本文介绍了在代码中安装 python 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要直接在我的脚本中安装来自 PyPi 的软件包.也许有一些模块或 distutils(distributepip 等)功能允许我执行类似 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆