Make script compatible Python 2 and Python 3
setuptools does not run 2to3 on the scripts so we must ensure the code is compatible with both versions. issue7057 review40951003
This commit is contained in:
1 parent
cc52b962b5
commit
eb8fe98468
1 file changed
+17
-9
@@ -1,14 +1,18 @@
|
||||
#!/usr/bin/env python
|
||||
# This file is part of Tryton. The COPYRIGHT file at the top level of
|
||||
# this repository contains the full copyright notices and license terms.
|
||||
from __future__ import print_function
|
||||
import csv
|
||||
import os
|
||||
import sys
|
||||
import urllib2
|
||||
try:
|
||||
from urllib.request import urlopen
|
||||
except ImportError:
|
||||
from urllib2 import urlopen
|
||||
import zipfile
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from io import BytesIO
|
||||
from io import BytesIO, StringIO
|
||||
|
||||
try:
|
||||
from progressbar import ProgressBar, Bar, ETA, SimpleProgress
|
||||
@@ -27,17 +31,17 @@ def clean(code):
|
||||
Zip = Model.get('country.zip')
|
||||
Zip._proxy.delete(
|
||||
[z.id for z in Zip.find([('country.code', '=', code)])], {})
|
||||
print >> sys.stderr, '.'
|
||||
print('.', file=sys.stderr)
|
||||
|
||||
|
||||
def fetch(code):
|
||||
sys.stderr.write('Fetching')
|
||||
url = 'http://download.geonames.org/export/zip/%s.zip' % code
|
||||
responce = urllib2.urlopen(url)
|
||||
responce = urlopen(url)
|
||||
data = responce.read()
|
||||
with zipfile.ZipFile(BytesIO(data)) as zf:
|
||||
data = zf.read('%s.txt' % code)
|
||||
print >> sys.stderr, '.'
|
||||
print('.', file=sys.stderr)
|
||||
return data
|
||||
|
||||
|
||||
@@ -45,7 +49,7 @@ def import_(data):
|
||||
Zip = Model.get('country.zip')
|
||||
Country = Model.get('country.country')
|
||||
Subdivision = Model.get('country.subdivision')
|
||||
print >> sys.stderr, 'Importing'
|
||||
print('Importing', file=sys.stderr)
|
||||
|
||||
def get_country(code):
|
||||
country = countries.get(code)
|
||||
@@ -72,8 +76,12 @@ def import_(data):
|
||||
widgets=[SimpleProgress(), Bar(), ETA()])
|
||||
else:
|
||||
pbar = iter
|
||||
for row in pbar(list(csv.DictReader(BytesIO(data),
|
||||
fieldnames=_fieldnames, delimiter='\t'))):
|
||||
if sys.version_info < (3,):
|
||||
f = BytesIO(data)
|
||||
else:
|
||||
f = StringIO(data.decode('utf-8'))
|
||||
for row in pbar(list(csv.DictReader(
|
||||
f, fieldnames=_fieldnames, delimiter='\t'))):
|
||||
country = get_country(row['country'])
|
||||
subdivision = get_subdivision(row['country'], row['code1'])
|
||||
Zip(country=country, subdivision=subdivision, zip=row['postal'],
|
||||
@@ -87,7 +95,7 @@ def main(database, codes, config_file=None):
|
||||
config.set_trytond(database, config_file=config_file)
|
||||
|
||||
for code in codes:
|
||||
print >> sys.stderr, code
|
||||
print(code, file=sys.stderr)
|
||||
code = code.upper()
|
||||
clean(code)
|
||||
import_(fetch(code))
|
||||
|
||||
Reference in new issue
Block a user