Installing python module within code


Question

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.

1
232
2/16/2018 2:33:44 PM

Accepted Answer

You can also use something like:

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')
350
8/17/2018 11:37:29 AM

Rickard's solution is not supported by the pip development team and will crash in some cases (e.g. multi threaded). Furthermore since pip 10 the code has been moved to pip._internal in order to make it clear that this is not supported, This solution will thus fail with an import error on "pip>=10.0.0".

Quantum's solution is the prefered way of solving the problem, however his implementation does not guarantee it will call the correct pip.

This solution guarantees it calls the pip of the python interpreter running the code.

import subprocess
import sys

def install(package):
    subprocess.call([sys.executable, "-m", "pip", "install", package])

It does the same as Quantum's solution, however instead of running pip directly, it runs the same python executable running the code and tells it to execute the pip module it has installed and passes the rest of the arguments to it.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon