Search code examples
pythonpippython-modulepypi

How can I Install a Python module with Pip programmatically (from my code)?


I need to install a package from PyPI straight within my script.

Is there maybe 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?


Solution

  • The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.

    Use sys.executable to ensure that you will call the same pip associated with the current runtime.

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