Skip to content

Instantly share code, notes, and snippets.

@ddaws
Created February 23, 2014 04:23
Show Gist options
  • Save ddaws/9166792 to your computer and use it in GitHub Desktop.
Save ddaws/9166792 to your computer and use it in GitHub Desktop.
The following may be used within a setup.py file to ensure packages are installed prior to the installation process.
def is_installed(pkg):
'''
Tests if a python module is installed.
'''
try:
__import__(pkg)
return True
except ImportError:
return False
def ensure_installed(pkg):
'''
Ensures a package is installed. This is done by
first testing if a module has already been
installed. If the module has not already been
installed pip is used to install the module.
'''
if not is_installed(pkg):
import pip
pip.main(['install', pkg])
# at this point pkg should be installed
if not is_installed(pkg):
print('Sorry, {0} must be installed to proceed.')
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment