packages = [package.project_name for package in pip.
    get_installed_distributions()]
if 'package' not in packages:
    pip.main(['install', 'package'])
How to install a missing python package from inside the script that needs it?