extensions.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. # encoding: utf-8
  2. """A class for managing IPython extensions."""
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. import os
  6. from shutil import copyfile
  7. import sys
  8. from traitlets.config.configurable import Configurable
  9. from IPython.utils.path import ensure_dir_exists
  10. from traitlets import Instance
  11. try:
  12. from importlib import reload
  13. except ImportError :
  14. ## deprecated since 3.4
  15. from imp import reload
  16. #-----------------------------------------------------------------------------
  17. # Main class
  18. #-----------------------------------------------------------------------------
  19. class ExtensionManager(Configurable):
  20. """A class to manage IPython extensions.
  21. An IPython extension is an importable Python module that has
  22. a function with the signature::
  23. def load_ipython_extension(ipython):
  24. # Do things with ipython
  25. This function is called after your extension is imported and the
  26. currently active :class:`InteractiveShell` instance is passed as
  27. the only argument. You can do anything you want with IPython at
  28. that point, including defining new magic and aliases, adding new
  29. components, etc.
  30. You can also optionally define an :func:`unload_ipython_extension(ipython)`
  31. function, which will be called if the user unloads or reloads the extension.
  32. The extension manager will only call :func:`load_ipython_extension` again
  33. if the extension is reloaded.
  34. You can put your extension modules anywhere you want, as long as
  35. they can be imported by Python's standard import mechanism. However,
  36. to make it easy to write extensions, you can also put your extensions
  37. in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
  38. is added to ``sys.path`` automatically.
  39. """
  40. shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
  41. def __init__(self, shell=None, **kwargs):
  42. super(ExtensionManager, self).__init__(shell=shell, **kwargs)
  43. self.shell.observe(
  44. self._on_ipython_dir_changed, names=('ipython_dir',)
  45. )
  46. self.loaded = set()
  47. @property
  48. def ipython_extension_dir(self):
  49. return os.path.join(self.shell.ipython_dir, u'extensions')
  50. def _on_ipython_dir_changed(self, change):
  51. ensure_dir_exists(self.ipython_extension_dir)
  52. def load_extension(self, module_str):
  53. """Load an IPython extension by its module name.
  54. Returns the string "already loaded" if the extension is already loaded,
  55. "no load function" if the module doesn't have a load_ipython_extension
  56. function, or None if it succeeded.
  57. """
  58. if module_str in self.loaded:
  59. return "already loaded"
  60. with self.shell.builtin_trap:
  61. if module_str not in sys.modules:
  62. try:
  63. sys.modules[module_str] = __import__('IPython.extensions.' + module_str)
  64. except ImportError:
  65. __import__(module_str)
  66. mod = sys.modules[module_str]
  67. if self._call_load_ipython_extension(mod):
  68. self.loaded.add(module_str)
  69. else:
  70. return "no load function"
  71. def unload_extension(self, module_str):
  72. """Unload an IPython extension by its module name.
  73. This function looks up the extension's name in ``sys.modules`` and
  74. simply calls ``mod.unload_ipython_extension(self)``.
  75. Returns the string "no unload function" if the extension doesn't define
  76. a function to unload itself, "not loaded" if the extension isn't loaded,
  77. otherwise None.
  78. """
  79. if module_str not in self.loaded:
  80. return "not loaded"
  81. if module_str in sys.modules:
  82. mod = sys.modules[module_str]
  83. if self._call_unload_ipython_extension(mod):
  84. self.loaded.discard(module_str)
  85. else:
  86. return "no unload function"
  87. def reload_extension(self, module_str):
  88. """Reload an IPython extension by calling reload.
  89. If the module has not been loaded before,
  90. :meth:`InteractiveShell.load_extension` is called. Otherwise
  91. :func:`reload` is called and then the :func:`load_ipython_extension`
  92. function of the module, if it exists is called.
  93. """
  94. from IPython.utils.syspathcontext import prepended_to_syspath
  95. if (module_str in self.loaded) and (module_str in sys.modules):
  96. self.unload_extension(module_str)
  97. mod = sys.modules[module_str]
  98. with prepended_to_syspath(self.ipython_extension_dir):
  99. reload(mod)
  100. if self._call_load_ipython_extension(mod):
  101. self.loaded.add(module_str)
  102. else:
  103. self.load_extension(module_str)
  104. def _call_load_ipython_extension(self, mod):
  105. if hasattr(mod, 'load_ipython_extension'):
  106. mod.load_ipython_extension(self.shell)
  107. return True
  108. def _call_unload_ipython_extension(self, mod):
  109. if hasattr(mod, 'unload_ipython_extension'):
  110. mod.unload_ipython_extension(self.shell)
  111. return True
  112. def install_extension(self, url, filename=None):
  113. """Download and install an IPython extension.
  114. If filename is given, the file will be so named (inside the extension
  115. directory). Otherwise, the name from the URL will be used. The file must
  116. have a .py or .zip extension; otherwise, a ValueError will be raised.
  117. Returns the full path to the installed file.
  118. """
  119. # Ensure the extension directory exists
  120. ensure_dir_exists(self.ipython_extension_dir)
  121. if os.path.isfile(url):
  122. src_filename = os.path.basename(url)
  123. copy = copyfile
  124. else:
  125. # Deferred imports
  126. try:
  127. from urllib.parse import urlparse # Py3
  128. from urllib.request import urlretrieve
  129. except ImportError:
  130. from urlparse import urlparse
  131. from urllib import urlretrieve
  132. src_filename = urlparse(url).path.split('/')[-1]
  133. copy = urlretrieve
  134. if filename is None:
  135. filename = src_filename
  136. if os.path.splitext(filename)[1] not in ('.py', '.zip'):
  137. raise ValueError("The file must have a .py or .zip extension", filename)
  138. filename = os.path.join(self.ipython_extension_dir, filename)
  139. copy(url, filename)
  140. return filename