python - 使用 Python 中的 pip 模块安装模块

标签 python python-3.x pip

我的目标是使用来自 Python 3.6 代码的 pip 模块来安装新的 Python 模块。但是,我似乎无法弄清楚调用实例化和调用 pip.commands.InstallCommand() 实例的正确步骤。

这是我到目前为止尝试过的:

import pip
inst = pip.commands.InstallCommand()
inst.name = 'boto3'
inst.run()

我什至不确定这是否是调用 InstallCommand 类的正确方法。运行上述代码时,我得到的错误是:

Traceback (most recent call last): File "", line 1, in TypeError: run() missing 2 required positional arguments: 'options' and 'args'

虽然我不确定要为 optionsargs 传递什么。

问题:有谁知道 pip InstallCommand 的正确调用是什么样的?

最佳答案

唯一支持从脚本pip install 的方法是通过子进程。请参阅文档中的部分 Using pip from your program :

pip is a command line program. While it is implemented in Python, and so is available from your Python code via import pip, you must not use pip’s internal APIs in this way. ... The most reliable approach, and the one that is fully supported, is to run pip in a subprocess. This is easily done using the standard subprocess module.

使用 sys.executable 确保您为当前运行时定位正确的 pip:

import subprocess, sys
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'boto3'])

关于python - 使用 Python 中的 pip 模块安装模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46959873/

相关文章:

python - Dymola Python 接口(interface) - 模拟扩展模型 : How to set up parameters?

Python/Pandas - 从地址中删除街道号码

python - 如何将数据帧与 pandas 中的冗余行结合起来

python - Django - 如何创建包含其自己类型的集合的模型?

python - 如何通过Gitlab CI成功安装fbprophet?

python - 打印编码字符串

python - 如何创建只有一个帖子的页面?

python - 如何使用 Pandas 类似于 GIS 溶解操作来汇总 Python 中的分段道路数据?

python - pip 需求文件是否有命名约定?

pip - 如何仅按名称搜索 pip 包?