Make holiday refresh script Python 3 compatible

urllib2 is renamed and reworked in Python 3, handle this change by
importing urlopen and HTTPError directly.

Resolve the print issues, by using print() everywhere.

Python3 reads bytes when reading from urlopen() therefore convert it to
a string with .decode('utf-8')
This commit is contained in:
Jelle van der Waa 2016-09-03 20:24:15 +02:00 committed by Paul Beckingham
parent 4136ffc245
commit 5ddef40d82

View file

@ -25,8 +25,13 @@
## ##
################################################################################ ################################################################################
import os, sys, re, time, datetime, json, argparse, urllib2 import os, sys, re, time, datetime, json, argparse
if sys.version_info >= (3,0):
from urllib.request import urlopen
from urllib.error import HTTPError
else:
from urllib2 import urlopen, HTTPError
def enumerate(path): def enumerate(path):
if not os.path.exists(path): if not os.path.exists(path):
@ -49,10 +54,10 @@ def update_locales(locales, regions):
def update_single_year(locales, regions, year): def update_single_year(locales, regions, year):
for locale in locales: for locale in locales:
print holidata(locale, year) print(holidata(locale, year))
try: try:
url = holidata(locale, year) url = holidata(locale, year)
lines = urllib2.urlopen(url).read() lines = urlopen(url).read().decode('utf-8')
with open("holidays.%s" % locale, "w") as fh: with open("holidays.%s" % locale, "w") as fh:
fh.write('# Holiday data provided by Holidata.net\n') fh.write('# Holiday data provided by Holidata.net\n')
@ -70,11 +75,11 @@ def update_single_year(locales, regions, year):
fh.write(' %s = %s\n' % (day, desc)) fh.write(' %s = %s\n' % (day, desc))
except urllib2.HTTPError as e: except HTTPError as e:
if e.code == 404: if e.code == 404:
print "Holidata.net does not have data for %s, for %d." % (locale, year) print("Holidata.net does not have data for %s, for %d." % (locale, year))
else: else:
print e.code, e.read() print(e.code, e.read())
def main(args): def main(args):
@ -103,5 +108,5 @@ if __name__ == "__main__":
try: try:
main(args) main(args)
except Exception as msg: except Exception as msg:
print 'Error:', msg print('Error:', msg)