syspathcontext.py 2.1 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. #-----------------------------------------------------------------------------
  14. # Imports
  15. #-----------------------------------------------------------------------------
  16. import sys
  17. from IPython.utils.py3compat import cast_bytes_py2
  18. #-----------------------------------------------------------------------------
  19. # Code
  20. #-----------------------------------------------------------------------------
  21. class appended_to_syspath(object):
  22. """A context for appending a directory to sys.path for a second."""
  23. def __init__(self, dir):
  24. self.dir = cast_bytes_py2(dir, sys.getdefaultencoding())
  25. def __enter__(self):
  26. if self.dir not in sys.path:
  27. sys.path.append(self.dir)
  28. self.added = True
  29. else:
  30. self.added = False
  31. def __exit__(self, type, value, traceback):
  32. if self.added:
  33. try:
  34. sys.path.remove(self.dir)
  35. except ValueError:
  36. pass
  37. # Returning False causes any exceptions to be re-raised.
  38. return False
  39. class prepended_to_syspath(object):
  40. """A context for prepending a directory to sys.path for a second."""
  41. def __init__(self, dir):
  42. self.dir = cast_bytes_py2(dir, sys.getdefaultencoding())
  43. def __enter__(self):
  44. if self.dir not in sys.path:
  45. sys.path.insert(0,self.dir)
  46. self.added = True
  47. else:
  48. self.added = False
  49. def __exit__(self, type, value, traceback):
  50. if self.added:
  51. try:
  52. sys.path.remove(self.dir)
  53. except ValueError:
  54. pass
  55. # Returning False causes any exceptions to be re-raised.
  56. return False