utils.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # -*- coding: utf-8 -*-
  2. """
  3. OS-related utils for python2/python3 compatibility
  4. """
  5. from __future__ import unicode_literals, division, print_function
  6. import sys
  7. import os
  8. if sys.version_info.major >= 3:
  9. # Python 3
  10. def path_exists(path):
  11. """Returns True if the given file or directory exists. May raise
  12. exceptions, for instance if you don't have permission to stat()
  13. the given path.
  14. """
  15. try:
  16. os.stat(path)
  17. return True
  18. except FileNotFoundError:
  19. return False
  20. def makedirs(name, mode=0o777, exist_ok=False):
  21. """No-op wrapper around os.makedirs()"""
  22. return os.makedirs(name, mode=mode, exist_ok=exist_ok)
  23. else:
  24. # Python 2
  25. def path_exists(path):
  26. """Returns True if the given file or directory exists. May raise
  27. exceptions, for instance if you don't have permission to stat()
  28. the given path.
  29. """
  30. try:
  31. os.stat(path)
  32. return True
  33. except OSError as e:
  34. if e.errno == os.errno.ENOENT:
  35. return False
  36. else:
  37. raise
  38. def makedirs(name, mode=0o777, exist_ok=False):
  39. """Wrapper around os.makedirs() to support the python3-style "exist_ok"
  40. argument.
  41. """
  42. if not exist_ok:
  43. return os.makedirs(name, mode=mode)
  44. # Emulate exist_ok behaviour
  45. try:
  46. return os.makedirs(name, mode=mode)
  47. except OSError as e:
  48. if e.errno == os.errno.EEXIST:
  49. return
  50. else:
  51. raise