简体   繁体   中英

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. I can't seem to figure out the correct steps to call instantiate and invoke a pip.commands.InstallCommand() instance, however.

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. 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'

I'm not sure what to pass in for options and args though.

Question : Does anyone know what the correct invocation of the pip InstallCommand looks like?

The only supported way to pip install from a script is via a subprocess. See the section in the documentation 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.

Use sys.executable to ensure you're targeting the correct pip for the current runtime:

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

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

You can install any package by using at a command prompt: pip install 'SomeProject'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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