From 8689d0b79ad47225e1de8e98af891ed64bced5b4 Mon Sep 17 00:00:00 2001 From: "Ian Y. Choi" Date: Thu, 8 Jun 2017 00:53:31 +0900 Subject: [PATCH] Python 3 support in zanata_userinfo.py * UTF-8 characters need to be handled differently with Python 2 and 3. In Python 2 unicode strings must be encoded into ASCII strings. Python 3 is naturely unicode-aware and there is no need to encode unicode strings before passing the CSV writer. * CSV writer in Python3 expects a file is open as non-binary mode. In Python 2, binary mode is expected. * Move the encoding logic to CSV writer. It is a bit tricky to have encoded strings (i.e., byte string) in regular data structure. Co-Authored-By: Akihiro Motoki Change-Id: I9d678d86b540d8b188ec0bf3240628a288f7ad3c Implements: blueprint python35-support --- tools/zanata/zanata_userinfo.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tools/zanata/zanata_userinfo.py b/tools/zanata/zanata_userinfo.py index eb37e9a..4f06f86 100755 --- a/tools/zanata/zanata_userinfo.py +++ b/tools/zanata/zanata_userinfo.py @@ -21,6 +21,7 @@ import os import sys from oslo_log import log as logging +import six import yaml from ZanataUtils import IniConfig from ZanataUtils import ZanataRestService @@ -129,7 +130,7 @@ def get_zanata_userdata(zc, verify, role, language_teams): user_data = accounts.get_account_data(user_id) if user_data: - user['name'] = user_data['name'].encode('utf-8') + user['name'] = user_data['name'] user['email'] = user_data['email'] return users @@ -144,13 +145,18 @@ def write_userdata_to_file(users, output_file): def _write_userdata_to_csvfile(userdata, output_file): - with open(output_file, 'wb') as csvfile: + mode = 'wb' if six.PY2 else 'w' + with open(output_file, mode) as csvfile: writer = csv.writer(csvfile) writer.writerow(['user_id', 'lang_code', 'lang', 'name', 'email']) for data in userdata: - writer.writerow([data['user_id'], data['lang_code'], - data['lang'], data['name'], data['email']]) + d = [data['user_id'], data['lang_code'], + data['lang'], data['name'], data['email']] + if six.PY2: + # In Python2 we need to encode unicode strings into strings. + d = [s.encode('utf-8') for s in d] + writer.writerow(d) def _comma_separated_list(s):