unix.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. from __future__ import with_statement
  2. import os
  3. import re
  4. import pytz
  5. _cache_tz = None
  6. def _tz_from_env(tzenv):
  7. if tzenv[0] == ':':
  8. tzenv = tzenv[1:]
  9. # TZ specifies a file
  10. if os.path.exists(tzenv):
  11. with open(tzenv, 'rb') as tzfile:
  12. return pytz.tzfile.build_tzinfo('local', tzfile)
  13. # TZ specifies a zoneinfo zone.
  14. try:
  15. tz = pytz.timezone(tzenv)
  16. # That worked, so we return this:
  17. return tz
  18. except pytz.UnknownTimeZoneError:
  19. raise pytz.UnknownTimeZoneError(
  20. "tzlocal() does not support non-zoneinfo timezones like %s. \n"
  21. "Please use a timezone in the form of Continent/City")
  22. def _get_localzone(_root='/'):
  23. """Tries to find the local timezone configuration.
  24. This method prefers finding the timezone name and passing that to pytz,
  25. over passing in the localtime file, as in the later case the zoneinfo
  26. name is unknown.
  27. The parameter _root makes the function look for files like /etc/localtime
  28. beneath the _root directory. This is primarily used by the tests.
  29. In normal usage you call the function without parameters."""
  30. tzenv = os.environ.get('TZ')
  31. if tzenv:
  32. try:
  33. return _tz_from_env(tzenv)
  34. except pytz.UnknownTimeZoneError:
  35. pass
  36. # Now look for distribution specific configuration files
  37. # that contain the timezone name.
  38. tzpath = os.path.join(_root, 'etc/timezone')
  39. if os.path.exists(tzpath):
  40. with open(tzpath, 'rb') as tzfile:
  41. data = tzfile.read()
  42. # Issue #3 was that /etc/timezone was a zoneinfo file.
  43. # That's a misconfiguration, but we need to handle it gracefully:
  44. if data[:5] != 'TZif2':
  45. etctz = data.strip().decode()
  46. # Get rid of host definitions and comments:
  47. if ' ' in etctz:
  48. etctz, dummy = etctz.split(' ', 1)
  49. if '#' in etctz:
  50. etctz, dummy = etctz.split('#', 1)
  51. return pytz.timezone(etctz.replace(' ', '_'))
  52. # CentOS has a ZONE setting in /etc/sysconfig/clock,
  53. # OpenSUSE has a TIMEZONE setting in /etc/sysconfig/clock and
  54. # Gentoo has a TIMEZONE setting in /etc/conf.d/clock
  55. # We look through these files for a timezone:
  56. zone_re = re.compile('\s*ZONE\s*=\s*\"')
  57. timezone_re = re.compile('\s*TIMEZONE\s*=\s*\"')
  58. end_re = re.compile('\"')
  59. for filename in ('etc/sysconfig/clock', 'etc/conf.d/clock'):
  60. tzpath = os.path.join(_root, filename)
  61. if not os.path.exists(tzpath):
  62. continue
  63. with open(tzpath, 'rt') as tzfile:
  64. data = tzfile.readlines()
  65. for line in data:
  66. # Look for the ZONE= setting.
  67. match = zone_re.match(line)
  68. if match is None:
  69. # No ZONE= setting. Look for the TIMEZONE= setting.
  70. match = timezone_re.match(line)
  71. if match is not None:
  72. # Some setting existed
  73. line = line[match.end():]
  74. etctz = line[:end_re.search(line).start()]
  75. # We found a timezone
  76. return pytz.timezone(etctz.replace(' ', '_'))
  77. # systemd distributions use symlinks that include the zone name,
  78. # see manpage of localtime(5) and timedatectl(1)
  79. tzpath = os.path.join(_root, 'etc/localtime')
  80. if os.path.exists(tzpath) and os.path.islink(tzpath):
  81. tzpath = os.path.realpath(tzpath)
  82. start = tzpath.find("/")+1
  83. while start is not 0:
  84. tzpath = tzpath[start:]
  85. try:
  86. return pytz.timezone(tzpath)
  87. except pytz.UnknownTimeZoneError:
  88. pass
  89. start = tzpath.find("/")+1
  90. # No explicit setting existed. Use localtime
  91. for filename in ('etc/localtime', 'usr/local/etc/localtime'):
  92. tzpath = os.path.join(_root, filename)
  93. if not os.path.exists(tzpath):
  94. continue
  95. with open(tzpath, 'rb') as tzfile:
  96. return pytz.tzfile.build_tzinfo('local', tzfile)
  97. raise pytz.UnknownTimeZoneError('Can not find any timezone configuration')
  98. def get_localzone():
  99. """Get the computers configured local timezone, if any."""
  100. global _cache_tz
  101. if _cache_tz is None:
  102. _cache_tz = _get_localzone()
  103. return _cache_tz
  104. def reload_localzone():
  105. """Reload the cached localzone. You need to call this if the timezone has changed."""
  106. global _cache_tz
  107. _cache_tz = _get_localzone()
  108. return _cache_tz