Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to install a missing python package from inside the script that needs it?

Tags:

python

pip

Assuming that you already have pip or easy_install installed on your python distribution, I would like to know how can I installed a required package in the user directory from within the script itself.

From what I know pip is also a python module so the solution should look like:

try:
    import zumba
except ImportError:
    import pip
    # ... do "pip install --user zumba" or throw exception   <-- how?
    import zumba

What I am missing is doing "pip install --user zumba" from inside python, I don't want to do it using os.system() as this may create other problems.

I assume it is possible...

like image 451
sorin Avatar asked Jun 24 '13 08:06

sorin


3 Answers

Updated for newer pip version (>= 10.0):

try:
    import zumba
except ImportError:
    from pip._internal import main as pip
    pip(['install', '--user', 'zumba'])
    import zumba

Thanks to @Joop I was able to come-up with the proper answer.

try:
    import zumba
except ImportError:
    import pip
    pip.main(['install', '--user', 'zumba'])
    import zumba

One important remark is that this will work without requiring root access as it will install the module in user directory.

Not sure if it will work for binary modules or ones that would require compilation, but it clearly works well for pure-python modules.

Now you can write self contained scripts and not worry about dependencies.

like image 134
sorin Avatar answered Oct 17 '22 10:10

sorin


As of pip version >= 10.0.0, the above solutions will not work because of internal package restructuring. The new way to use pip inside a script is now as follows:

try: import abc
except ImportError:
    from pip._internal import main as pip
    pip(['install', '--user', 'abc'])
    import abc
like image 11
Phoenix Avatar answered Oct 17 '22 11:10

Phoenix


I wanted to note that the current accepted answer could result in a possible app name collision. Importing from the app namespace doesn't give you the full picture of what's installed on the system.

A better way would be:

import pip

packages = [package.project_name for package in pip.get_installed_distributions()]

if 'package' not in packages:
    pip.main(['install', 'package'])
like image 3
Casey Avatar answered Oct 17 '22 10:10

Casey