简体   繁体   English

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

[英]Use pip module from Python to install modules

My goal is to use the pip module, from Python 3.6 code, to install a new Python module.我的目标是使用 Python 3.6 代码中的pip模块来安装新的 Python 模块。 I can't seem to figure out the correct steps to call instantiate and invoke a pip.commands.InstallCommand() instance, however.但是,我似乎无法找出调用实例化和调用pip.commands.InstallCommand()实例的正确步骤。

Here's what I've tried so far:这是我迄今为止尝试过的:

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

I'm not even sure if this is the correct method of invoking the InstallCommand class.我什至不确定这是否是调用InstallCommand类的正确方法。 The error I'm getting, when running the above code, is:运行上面的代码时,我得到的错误是:

Traceback (most recent call last): File "", line 1, in TypeError: run() missing 2 required positional arguments: 'options' and 'args'回溯(最近一次调用):文件“”,第 1 行,在 TypeError 中:run() 缺少 2 个必需的位置参数:“options”和“args”

I'm not sure what to pass in for options and args though.不过,我不确定要为optionsargs传递什么。

Question : Does anyone know what the correct invocation of the pip InstallCommand looks like?问题:有谁知道 pip InstallCommand的正确调用是什么样的?

The only supported way to pip install from a script is via a subprocess.从脚本pip install的唯一支持的方法是通过子进程。 See the section in the documentation Using pip from your program :请参阅从程序中使用 pip文档中的部分:

pip is a command line program. pip是一个命令行程序。 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.虽然它是在 Python 中实现的,因此可以通过import pip从你的 Python 代码中获得,但你不能以这种方式使用 pip 的内部 API。 ... The most reliable approach, and the one that is fully supported, is to run pip in a subprocess. ...最可靠的方法,也是完全支持的方法,是在子进程中运行 pip。 This is easily done using the standard subprocess module.这可以使用标准的子流程模块轻松完成。

Use sys.executable to ensure you're targeting the correct pip for the current runtime:使用sys.executable确保您针对当前运行时的正确 pip:

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

According to with https://packaging.python.org/tutorials/installing-packages/根据https://packaging.python.org/tutorials/installing-packages/

You can install any package by using at a command prompt: pip install 'SomeProject'您可以在命令提示符下使用安装任何软件包:pip install 'SomeProject'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM