[python] Installing python module within code

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.

This question is related to python pip python-module pypi

The answer is


You define the dependent module inside the setup.py of your own package with the "install_requires" option.

If your package needs to have some console script generated then you can use the "console_scripts" entry point in order to generate a wrapper script that will be placed within the 'bin' folder (e.g. of your virtualenv environment).


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

for installing multiple packages, i am using a setup.py file with following code:

import sys
import subprocess
import pkg_resources

required = {'numpy','pandas','<etc>'} 
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed


if missing:
    # implement pip as a subprocess:
    subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

If you want to use pip to install required package and import it after installation, you can use this code:

def install_and_import(package):
    import importlib
    try:
        importlib.import_module(package)
    except ImportError:
        import pip
        pip.main(['install', package])
    finally:
        globals()[package] = importlib.import_module(package)


install_and_import('transliterate')

If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.


import os
os.system('pip install requests')

I tried above for temporary solution instead of changing docker file. Hope these might be useful to some


i added some exception handling to @Aaron's answer.

import subprocess
import sys

try:
    import pandas as pd
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", 'pandas'])
finally:
    import pandas as pd

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to pip

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip "E: Unable to locate package python-pip" on Ubuntu 18.04 How to Install pip for python 3.7 on Ubuntu 18? What is the meaning of "Failed building wheel for X" in pip install? Could not install packages due to an EnvironmentError: [Errno 13] How do I install Python packages in Google's Colab? Conda version pip install -r requirements.txt --target ./lib pip: no module named _internal AttributeError: Module Pip has no attribute 'main' Error after upgrading pip: cannot import name 'main'

Examples related to python-module

ImportError: libSM.so.6: cannot open shared object file: No such file or directory How to write a Python module/package? Python: OSError: [Errno 2] No such file or directory: '' Unable to import a module that is definitely installed Installing python module within code How to import other Python files? How do I find out my python path using python? What does if __name__ == "__main__": do? How to do relative imports in Python? How to import a module given the full path?

Examples related to pypi

'pip install' fails for every package ("Could not find a version that satisfies the requirement") Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI? Installing python module within code pypi UserWarning: Unknown distribution option: 'install_requires' Find all packages installed with easy_install/pip? Installing specific package versions with pip Why use pip over easy_install? python setup.py uninstall What is setup.py?