Skip to content

Instantly share code, notes, and snippets.

@achillesrasquinha
Created May 25, 2018 15:54
Show Gist options
  • Save achillesrasquinha/e1740314251f55f172b90e6016d641d4 to your computer and use it in GitHub Desktop.
Save achillesrasquinha/e1740314251f55f172b90e6016d641d4 to your computer and use it in GitHub Desktop.
import or install

Usage

_import('matplotlib') # Installs matplotlib and imports into global space if not available.

Snippet

import os
import os.path as osp
import importlib
import pip

PIP10 = int(pip.__version__.split('.')[0]) == 10

if PIP10:
    from pip._internal import main as pip_main
else:
    from pip           import main as pip_main

def pip_install(*packages, upgrade = False):
    args = [
        'install',
        '--upgrade' if upgrade else ''
    ] + list(packages)
    args = [arg for arg in args if bool(arg)]
    
    pip_main(args)

def _import(package, install = True):
    try:
        importlib.import_module(package)
    except ImportError as e:
        if not install:
            raise
        else:
            pip_install(package)
            _import(package, install = False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment