Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. # Author: Hong Xu. This file is under CC0.
  2.  
  3. def pip_install_with_confirmation(packages):
  4. """Run ``pip install`` with a confirmation only if some packages are missing. This is useful to put in the beginning of
  5. a Jupyter notebook.
  6.  
  7. Args:
  8.  
  9. packages (dict): Each key is the name of a package to be installed. Each value is a sequence of size 3. The
  10. first two elements are the ``package`` and ``name`` parameter of ``importlib.import_module()``, respectively.
  11. The last element is the imported name. Roughly speaking, the three elements correspond to the following three
  12. spots in an import statement::
  13.  
  14. from {param 0} import {param 1} as {param 2}
  15.  
  16. Example::
  17.  
  18. pip_install_with_confirmation({
  19. 'requests': [None, 'requests', 'requests'],
  20. 'numpy': [None, 'numpy', 'np'],
  21. 'matplotlib': ['matplotlib', '.pyplot', 'plt']
  22. })
  23.  
  24. """
  25. def import_all_modules():
  26. from importlib import import_module, invalidate_caches
  27. for package, info in packages.items():
  28. globals()[info[2]] = import_module(package=info[0], name=info[1])
  29. invalidate_caches()
  30.  
  31. try:
  32. ModuleNotFoundError()
  33. except NameError:
  34. ModuleNotFoundError = ImportError
  35.  
  36. try:
  37. import_all_modules()
  38. except ModuleNotFoundError:
  39. import sys
  40. pip_install_command = [sys.executable, '-m', 'pip', '-q', 'install'] + list(packages)
  41. answer = input('Will run "{}". Confirm? [y/n]'.format(' '.join(pip_install_command)))
  42. if answer == 'y':
  43. import subprocess
  44. subprocess.check_call(pip_install_command)
  45. print("Package installation succeeded!")
  46. import_all_modules()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement