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. from IPython.utils.syspathcontext import prepended_to_syspath
  61. with self.shell.builtin_trap:
  62. if module_str not in sys.modules:
  63. with prepended_to_syspath(self.ipython_extension_dir):
  64. __import__(module_str)
  65. mod = sys.modules[module_str]
  66. if self._call_load_ipython_extension(mod):
  67. self.loaded.add(module_str)
  68. else:
  69. return "no load function"
  70. def unload_extension(self, module_str):
  71. """Unload an IPython extension by its module name.
  72. This function looks up the extension's name in ``sys.modules`` and
  73. simply calls ``mod.unload_ipython_extension(self)``.
  74. Returns the string "no unload function" if the extension doesn't define
  75. a function to unload itself, "not loaded" if the extension isn't loaded,
  76. otherwise None.
  77. """
  78. if module_str not in self.loaded:
  79. return "not loaded"
  80. if module_str in sys.modules:
  81. mod = sys.modules[module_str]
  82. if self._call_unload_ipython_extension(mod):
  83. self.loaded.discard(module_str)
  84. else:
  85. return "no unload function"
  86. def reload_extension(self, module_str):
  87. """Reload an IPython extension by calling reload.
  88. If the module has not been loaded before,
  89. :meth:`InteractiveShell.load_extension` is called. Otherwise
  90. :func:`reload` is called and then the :func:`load_ipython_extension`
  91. function of the module, if it exists is called.
  92. """
  93. from IPython.utils.syspathcontext import prepended_to_syspath
  94. if (module_str in self.loaded) and (module_str in sys.modules):
  95. self.unload_extension(module_str)
  96. mod = sys.modules[module_str]
  97. with prepended_to_syspath(self.ipython_extension_dir):
  98. reload(mod)
  99. if self._call_load_ipython_extension(mod):
  100. self.loaded.add(module_str)
  101. else:
  102. self.load_extension(module_str)
  103. def _call_load_ipython_extension(self, mod):
  104. if hasattr(mod, 'load_ipython_extension'):
  105. mod.load_ipython_extension(self.shell)
  106. return True
  107. def _call_unload_ipython_extension(self, mod):
  108. if hasattr(mod, 'unload_ipython_extension'):
  109. mod.unload_ipython_extension(self.shell)
  110. return True
  111. def install_extension(self, url, filename=None):
  112. """Download and install an IPython extension.
  113. If filename is given, the file will be so named (inside the extension
  114. directory). Otherwise, the name from the URL will be used. The file must
  115. have a .py or .zip extension; otherwise, a ValueError will be raised.
  116. Returns the full path to the installed file.
  117. """
  118. # Ensure the extension directory exists
  119. ensure_dir_exists(self.ipython_extension_dir)
  120. if os.path.isfile(url):
  121. src_filename = os.path.basename(url)
  122. copy = copyfile
  123. else:
  124. # Deferred imports
  125. try:
  126. from urllib.parse import urlparse # Py3
  127. from urllib.request import urlretrieve
  128. except ImportError:
  129. from urlparse import urlparse
  130. from urllib import urlretrieve
  131. src_filename = urlparse(url).path.split('/')[-1]
  132. copy = urlretrieve
  133. if filename is None:
  134. filename = src_filename
  135. if os.path.splitext(filename)[1] not in ('.py', '.zip'):
  136. raise ValueError("The file must have a .py or .zip extension", filename)
  137. filename = os.path.join(self.ipython_extension_dir, filename)
  138. copy(url, filename)
  139. return filename