Installing python module within code

chuwy picture chuwy · Sep 8, 2012 · Viewed 285.1k times · Source

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.

Answer

Rikard Anglerud picture Rikard Anglerud · Apr 11, 2013

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