syspathcontext.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # encoding: utf-8
  2. """
  3. Context managers for adding things to sys.path temporarily.
  4. Authors:
  5. * Brian Granger
  6. """
  7. #-----------------------------------------------------------------------------
  8. # Copyright (C) 2008-2011 The IPython Development Team
  9. #
  10. # Distributed under the terms of the BSD License. The full license is in
  11. # the file COPYING, distributed as part of this software.
  12. #-----------------------------------------------------------------------------
  13. import sys
  14. import warnings
  15. class appended_to_syspath(object):
  16. """
  17. Deprecated since IPython 8.1, no replacements.
  18. A context for appending a directory to sys.path for a second."""
  19. def __init__(self, dir):
  20. warnings.warn(
  21. "`appended_to_syspath` is deprecated since IPython 8.1, and has no replacements",
  22. DeprecationWarning,
  23. stacklevel=2,
  24. )
  25. self.dir = dir
  26. def __enter__(self):
  27. if self.dir not in sys.path:
  28. sys.path.append(self.dir)
  29. self.added = True
  30. else:
  31. self.added = False
  32. def __exit__(self, type, value, traceback):
  33. if self.added:
  34. try:
  35. sys.path.remove(self.dir)
  36. except ValueError:
  37. pass
  38. # Returning False causes any exceptions to be re-raised.
  39. return False
  40. class prepended_to_syspath(object):
  41. """A context for prepending a directory to sys.path for a second."""
  42. def __init__(self, dir):
  43. self.dir = dir
  44. def __enter__(self):
  45. if self.dir not in sys.path:
  46. sys.path.insert(0,self.dir)
  47. self.added = True
  48. else:
  49. self.added = False
  50. def __exit__(self, type, value, traceback):
  51. if self.added:
  52. try:
  53. sys.path.remove(self.dir)
  54. except ValueError:
  55. pass
  56. # Returning False causes any exceptions to be re-raised.
  57. return False