autocall.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # encoding: utf-8
  2. """
  3. Autocall capabilities for IPython.core.
  4. Authors:
  5. * Brian Granger
  6. * Fernando Perez
  7. * Thomas Kluyver
  8. Notes
  9. -----
  10. """
  11. #-----------------------------------------------------------------------------
  12. # Copyright (C) 2008-2011 The IPython Development Team
  13. #
  14. # Distributed under the terms of the BSD License. The full license is in
  15. # the file COPYING, distributed as part of this software.
  16. #-----------------------------------------------------------------------------
  17. #-----------------------------------------------------------------------------
  18. # Imports
  19. #-----------------------------------------------------------------------------
  20. #-----------------------------------------------------------------------------
  21. # Code
  22. #-----------------------------------------------------------------------------
  23. class IPyAutocall(object):
  24. """ Instances of this class are always autocalled
  25. This happens regardless of 'autocall' variable state. Use this to
  26. develop macro-like mechanisms.
  27. """
  28. _ip = None
  29. rewrite = True
  30. def __init__(self, ip=None):
  31. self._ip = ip
  32. def set_ip(self, ip):
  33. """ Will be used to set _ip point to current ipython instance b/f call
  34. Override this method if you don't want this to happen.
  35. """
  36. self._ip = ip
  37. class ExitAutocall(IPyAutocall):
  38. """An autocallable object which will be added to the user namespace so that
  39. exit, exit(), quit or quit() are all valid ways to close the shell."""
  40. rewrite = False
  41. def __call__(self):
  42. self._ip.ask_exit()
  43. class ZMQExitAutocall(ExitAutocall):
  44. """Exit IPython. Autocallable, so it needn't be explicitly called.
  45. Parameters
  46. ----------
  47. keep_kernel : bool
  48. If True, leave the kernel alive. Otherwise, tell the kernel to exit too
  49. (default).
  50. """
  51. def __call__(self, keep_kernel=False):
  52. self._ip.keepkernel_on_exit = keep_kernel
  53. self._ip.ask_exit()