我的目标是使用来自 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'
虽然我不确定要为 options
和 args
传递什么。
问题:有谁知道 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 viaimport 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/