_unix.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. from __future__ import with_statement
  2. import os
  3. import re
  4. import sys
  5. import pytz
  6. import subprocess
  7. _systemconfig_tz = re.compile(r'^Time Zone: (.*)$', re.MULTILINE)
  8. def _tz_from_env(tzenv):
  9. if tzenv[0] == ':':
  10. tzenv = tzenv[1:]
  11. # TZ specifies a file
  12. if os.path.exists(tzenv):
  13. with open(tzenv, 'rb') as tzfile:
  14. return pytz.tzfile.build_tzinfo('local', tzfile)
  15. # TZ specifies a zoneinfo zone.
  16. try:
  17. tz = pytz.timezone(tzenv)
  18. # That worked, so we return this:
  19. return tz
  20. except pytz.UnknownTimeZoneError:
  21. raise pytz.UnknownTimeZoneError(
  22. "tzlocal() does not support non-zoneinfo timezones like %s. \n"
  23. "Please use a timezone in the form of Continent/City")
  24. def _get_localzone(_root='/'):
  25. """Tries to find the local timezone configuration.
  26. This method prefers finding the timezone name and passing that to pytz,
  27. over passing in the localtime file, as in the later case the zoneinfo
  28. name is unknown.
  29. The parameter _root makes the function look for files like /etc/localtime
  30. beneath the _root directory. This is primarily used by the tests.
  31. In normal usage you call the function without parameters.
  32. """
  33. tzenv = os.environ.get('TZ')
  34. if tzenv:
  35. return _tz_from_env(tzenv)
  36. # This is actually a pretty reliable way to test for the local time
  37. # zone on operating systems like OS X. On OS X especially this is the
  38. # only one that actually works.
  39. try:
  40. link_dst = os.readlink('/etc/localtime')
  41. except OSError:
  42. pass
  43. else:
  44. pos = link_dst.find('/zoneinfo/')
  45. if pos >= 0:
  46. zone_name = link_dst[pos + 10:]
  47. try:
  48. return pytz.timezone(zone_name)
  49. except pytz.UnknownTimeZoneError:
  50. pass
  51. # If we are on OS X now we are pretty sure that the rest of the
  52. # code will fail and just fall through until it hits the reading
  53. # of /etc/localtime and using it without name. At this point we
  54. # can invoke systemconfig which internally invokes ICU. ICU itself
  55. # does the same thing we do (readlink + compare file contents) but
  56. # since it knows where the zone files are that should be a bit
  57. # better than reimplementing the logic here.
  58. if sys.platform == 'darwin':
  59. c = subprocess.Popen(['systemsetup', '-gettimezone'],
  60. stdout=subprocess.PIPE)
  61. sys_result = c.communicate()[0]
  62. c.wait()
  63. tz_match = _systemconfig_tz.search(sys_result)
  64. if tz_match is not None:
  65. zone_name = tz_match.group(1)
  66. try:
  67. return pytz.timezone(zone_name)
  68. except pytz.UnknownTimeZoneError:
  69. pass
  70. # Now look for distribution specific configuration files
  71. # that contain the timezone name.
  72. tzpath = os.path.join(_root, 'etc/timezone')
  73. if os.path.exists(tzpath):
  74. with open(tzpath, 'rb') as tzfile:
  75. data = tzfile.read()
  76. # Issue #3 in tzlocal was that /etc/timezone was a zoneinfo file.
  77. # That's a misconfiguration, but we need to handle it gracefully:
  78. if data[:5] != 'TZif2':
  79. etctz = data.strip().decode()
  80. # Get rid of host definitions and comments:
  81. if ' ' in etctz:
  82. etctz, dummy = etctz.split(' ', 1)
  83. if '#' in etctz:
  84. etctz, dummy = etctz.split('#', 1)
  85. return pytz.timezone(etctz.replace(' ', '_'))
  86. # CentOS has a ZONE setting in /etc/sysconfig/clock,
  87. # OpenSUSE has a TIMEZONE setting in /etc/sysconfig/clock and
  88. # Gentoo has a TIMEZONE setting in /etc/conf.d/clock
  89. # We look through these files for a timezone:
  90. zone_re = re.compile('\s*ZONE\s*=\s*\"')
  91. timezone_re = re.compile('\s*TIMEZONE\s*=\s*\"')
  92. end_re = re.compile('\"')
  93. for filename in ('etc/sysconfig/clock', 'etc/conf.d/clock'):
  94. tzpath = os.path.join(_root, filename)
  95. if not os.path.exists(tzpath):
  96. continue
  97. with open(tzpath, 'rt') as tzfile:
  98. for line in tzfile:
  99. # Look for the ZONE= setting.
  100. match = zone_re.match(line)
  101. if match is None:
  102. # No ZONE= setting. Look for the TIMEZONE= setting.
  103. match = timezone_re.match(line)
  104. if match is not None:
  105. # Some setting existed
  106. line = line[match.end():]
  107. etctz = line[:end_re.search(line).start()]
  108. # We found a timezone
  109. return pytz.timezone(etctz.replace(' ', '_'))
  110. # No explicit setting existed. Use localtime
  111. for filename in ('etc/localtime', 'usr/local/etc/localtime'):
  112. tzpath = os.path.join(_root, filename)
  113. if not os.path.exists(tzpath):
  114. continue
  115. with open(tzpath, 'rb') as tzfile:
  116. return pytz.tzfile.build_tzinfo('local', tzfile)
  117. raise pytz.UnknownTimeZoneError('Can not find any timezone configuration')