utils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. import datetime
  5. import os
  6. import subprocess
  7. import platform
  8. def yesno(prompt, default=None):
  9. """
  10. Prompt the user for a yes or no.
  11. Can optionally specify a default value, which will only be
  12. used if they enter a blank line.
  13. Unrecognised input (anything other than "y", "n", "yes",
  14. "no" or "") will return None.
  15. """
  16. answer = raw_input(prompt).strip().lower()
  17. if answer == "y" or answer == "yes":
  18. return True
  19. elif answer == "n" or answer == "no":
  20. return False
  21. elif answer == "":
  22. return default
  23. else:
  24. return None
  25. # http://stackoverflow.com/a/5164027
  26. def prettydate(d):
  27. diff = datetime.datetime.utcnow() - d
  28. s = diff.seconds
  29. if diff.days > 7 or diff.days < 0:
  30. return d.strftime('%d %b %y')
  31. elif diff.days == 1:
  32. return '1 day ago'
  33. elif diff.days > 1:
  34. return '{0} days ago'.format(diff.days)
  35. elif s <= 1:
  36. return 'just now'
  37. elif s < 60:
  38. return '{0} seconds ago'.format(s)
  39. elif s < 120:
  40. return '1 minute ago'
  41. elif s < 3600:
  42. return '{0} minutes ago'.format(s / 60)
  43. elif s < 7200:
  44. return '1 hour ago'
  45. else:
  46. return '{0} hours ago'.format(s / 3600)
  47. def mkdir(path, permissions=0o700):
  48. if not os.path.exists(path):
  49. os.mkdir(path)
  50. os.chmod(path, permissions)
  51. return path
  52. def docker_url():
  53. return os.environ.get('DOCKER_HOST')
  54. def split_buffer(reader, separator):
  55. """
  56. Given a generator which yields strings and a separator string,
  57. joins all input, splits on the separator and yields each chunk.
  58. Unlike string.split(), each chunk includes the trailing
  59. separator, except for the last one if none was found on the end
  60. of the input.
  61. """
  62. buffered = str('')
  63. separator = str(separator)
  64. for data in reader:
  65. buffered += data
  66. while True:
  67. index = buffered.find(separator)
  68. if index == -1:
  69. break
  70. yield buffered[:index + 1]
  71. buffered = buffered[index + 1:]
  72. if len(buffered) > 0:
  73. yield buffered
  74. def call_silently(*args, **kwargs):
  75. """
  76. Like subprocess.call(), but redirects stdout and stderr to /dev/null.
  77. """
  78. with open(os.devnull, 'w') as shutup:
  79. return subprocess.call(*args, stdout=shutup, stderr=shutup, **kwargs)
  80. def is_mac():
  81. return platform.system() == 'Darwin'
  82. def is_ubuntu():
  83. return platform.system() == 'Linux' and platform.linux_distribution()[0] == 'Ubuntu'