Remove python2 specific code

This commit is contained in:
Nick Hall 2015-03-14 19:11:09 +00:00 committed by Ross Gammon
parent 70c11878f4
commit caac0901cb
96 changed files with 306 additions and 1036 deletions

@ -34,12 +34,8 @@ import os
import sys import sys
import time import time
import io import io
if sys.version_info[0] < 3: from urllib.parse import urlparse
from urlparse import urlparse from urllib.request import urlopen, url2pathname
from urllib2 import urlopen, url2pathname
else:
from urllib.parse import urlparse
from urllib.request import urlopen, url2pathname
import tempfile import tempfile
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -142,10 +138,7 @@ class CLIDbManager(object):
current DB. current DB.
Returns ("Unknown", "Unknown", "Unknown") if invalid DB or other error. Returns ("Unknown", "Unknown", "Unknown") if invalid DB or other error.
""" """
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3: from bsddb3 import dbshelve, db
from bsddb3 import dbshelve, db
else:
from bsddb import dbshelve, db
from gramps.gen.db import META, PERSON_TBL from gramps.gen.db import META, PERSON_TBL
from gramps.gen.db.dbconst import BDBVERSFN from gramps.gen.db.dbconst import BDBVERSFN

@ -24,7 +24,6 @@ import os
import unittest import unittest
import re import re
import io import io
import sys
import subprocess import subprocess
from gramps.gen.constfunc import cuni from gramps.gen.constfunc import cuni
@ -41,13 +40,6 @@ test_ged = """0 HEAD
0 TRLR 0 TRLR
""" """
# see gramps.grampsapp.py
## hack to avoid mentioning 'utf8' encoding everywhere unicode or str is is used
if sys.version_info[0] < 3:
reload(sys)
sys.setdefaultencoding('utf8')
##
ddir = os.path.dirname(__file__) ddir = os.path.dirname(__file__)
min1r = os.path.join(ddir, "min1r.ged") min1r = os.path.join(ddir, "min1r.ged")
out_ged = os.path.join(ddir, "test_out.ged") out_ged = os.path.join(ddir, "test_out.ged")
@ -129,9 +121,6 @@ class Test(unittest.TestCase):
class UnicodeTest(unittest.TestCase): class UnicodeTest(unittest.TestCase):
@unittest.skipIf(sys.version_info[0] < 3 and sys.platform == 'win32',
"Python2 bsddb doesn't handle unicode paths")
def setUp(self): def setUp(self):
from gramps.cli.clidbman import CLIDbManager from gramps.cli.clidbman import CLIDbManager
from gramps.gen.config import set as setconfig, get as getconfig from gramps.gen.config import set as setconfig, get as getconfig

@ -22,13 +22,6 @@
The User class provides basic interaction with the user. The User class provides basic interaction with the user.
""" """
#------------------------------------------------------------------------
#
# Python Modules
#
#------------------------------------------------------------------------
import sys
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# Gramps Modules # Gramps Modules
@ -65,7 +58,6 @@ class User(user.User):
user.User.__init__(self, callback, error) user.User.__init__(self, callback, error)
self.steps = 0; self.steps = 0;
self.current_step = 0; self.current_step = 0;
self._input = raw_input if sys.version_info[0] < 3 else input
def yes(*args): def yes(*args):
return True return True
@ -143,7 +135,7 @@ class User(user.User):
n = reject_label) n = reject_label)
print (text, file = self._fileout) # TODO python3 add flush=True print (text, file = self._fileout) # TODO python3 add flush=True
try: try:
reply = self._input() reply = input()
return reply == "" or reply == accept_label return reply == "" or reply == accept_label
except EOFError: except EOFError:
return False return False

@ -121,13 +121,8 @@ USER_DIRLIST = (USER_HOME, HOME_DIR, VERSION_DIR, ENV_DIR, TEMP_DIR, THUMB_DIR,
# above this one, and that the plugins directory is below the root directory. # above this one, and that the plugins directory is below the root directory.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# test for sys.frozen to detect a py2exe executable on Windows ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(
conv_to_unicode(__file__)), os.pardir))
if sys.version_info[0] < 3 and hasattr(sys, "frozen"):
ROOT_DIR = os.path.abspath(os.path.dirname(unicode(sys.executable)))
else:
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(
conv_to_unicode(__file__)), os.pardir))
sys.path.insert(0, ROOT_DIR) sys.path.insert(0, ROOT_DIR)
git_revision = get_git_revision(ROOT_DIR) git_revision = get_git_revision(ROOT_DIR)

@ -51,15 +51,9 @@ WINDOWS = ["Windows", "win32"]
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
#python 2 and 3 support, use correct conversion to unicode conv_to_unicode_direct = str
if sys.version_info[0] < 3: STRTYPE = str
conv_to_unicode_direct = unicode UNITYPE = str
STRTYPE = basestring
UNITYPE = unicode
else:
conv_to_unicode_direct = str
STRTYPE = str
UNITYPE = str
cuni = conv_to_unicode_direct cuni = conv_to_unicode_direct
def conv_to_unicode(x, y='utf8'): def conv_to_unicode(x, y='utf8'):
return x if x is None or isinstance(x, UNITYPE) else cuni(x, y) if y else cuni(x) return x if x is None or isinstance(x, UNITYPE) else cuni(x, y) if y else cuni(x)
@ -69,16 +63,10 @@ def uni_to_gui(x):
In Py2 we need to convert strings to utf8 before passing them to In Py2 we need to convert strings to utf8 before passing them to
Gtk functions. Gtk functions.
''' '''
if sys.version_info[0] < 3 and isinstance(x, UNITYPE): return x
return x.encode('utf8')
else:
return x
# handle in database is bytes, while internally Gramps wants unicode for py3 # handle in database is bytes, while internally Gramps wants unicode for py3
if sys.version_info[0] < 3: handle2internal = lambda x: conv_to_unicode(x, 'utf-8')
handle2internal = lambda x: x
else:
handle2internal = lambda x: conv_to_unicode(x, 'utf-8')
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -184,16 +172,6 @@ def get_env_var(name, default=None):
if not name or not name in os.environ: if not name or not name in os.environ:
return default return default
if sys.version_info[0] < 3 and win():
name = unicode(name) # make sure string argument is unicode
n = ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0)
if n==0:
return default
# n is number of codepoints
buf = ctypes.create_unicode_buffer(n+1)
ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n)
return buf.value
return os.environ[name] return os.environ[name]
def get_curr_dir(): def get_curr_dir():
@ -203,14 +181,4 @@ def get_curr_dir():
an arbitrary unicode character in a path. This function uses the an arbitrary unicode character in a path. This function uses the
native GetCurrentDirectory function to return a unicode cwd. native GetCurrentDirectory function to return a unicode cwd.
''' '''
if not (sys.version_info[0] < 3 and win()): return os.getcwd()
return os.getcwd()
n = ctypes.windll.kernel32.GetCurrentDirectoryW(0, None)
if n == 0:
return None
buf = ctypes.create_unicode_buffer(n+1)
ctypes.windll.kernel32.GetCurrentDirectoryW(n, buf)
return buf.value

@ -21,9 +21,6 @@
# #
import locale import locale
import sys
from ..constfunc import mac, win, conv_to_unicode
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
""" """
@ -36,11 +33,6 @@ strftime.
Since these routines return values encoded into selected character Since these routines return values encoded into selected character
set, we have to convert to unicode. set, we have to convert to unicode.
""" """
if sys.version_info[0] < 3:
to_uni = conv_to_unicode
else:
#locale returns unicode in python 3
to_uni = lambda x, y: x
codeset = glocale.encoding codeset = glocale.encoding
try: try:
@ -48,34 +40,34 @@ try:
# here only for the upgrade tool, see _datestrings.py __main__ # here only for the upgrade tool, see _datestrings.py __main__
_deprecated_long_months = ( _deprecated_long_months = (
"", "",
to_uni(locale.nl_langinfo(locale.MON_1), codeset), locale.nl_langinfo(locale.MON_1),
to_uni(locale.nl_langinfo(locale.MON_2), codeset), locale.nl_langinfo(locale.MON_2),
to_uni(locale.nl_langinfo(locale.MON_3), codeset), locale.nl_langinfo(locale.MON_3),
to_uni(locale.nl_langinfo(locale.MON_4), codeset), locale.nl_langinfo(locale.MON_4),
to_uni(locale.nl_langinfo(locale.MON_5), codeset), locale.nl_langinfo(locale.MON_5),
to_uni(locale.nl_langinfo(locale.MON_6), codeset), locale.nl_langinfo(locale.MON_6),
to_uni(locale.nl_langinfo(locale.MON_7), codeset), locale.nl_langinfo(locale.MON_7),
to_uni(locale.nl_langinfo(locale.MON_8), codeset), locale.nl_langinfo(locale.MON_8),
to_uni(locale.nl_langinfo(locale.MON_9), codeset), locale.nl_langinfo(locale.MON_9),
to_uni(locale.nl_langinfo(locale.MON_10), codeset), locale.nl_langinfo(locale.MON_10),
to_uni(locale.nl_langinfo(locale.MON_11), codeset), locale.nl_langinfo(locale.MON_11),
to_uni(locale.nl_langinfo(locale.MON_12), codeset), locale.nl_langinfo(locale.MON_12),
) )
_deprecated_short_months = ( _deprecated_short_months = (
"", "",
to_uni(locale.nl_langinfo(locale.ABMON_1), codeset), locale.nl_langinfo(locale.ABMON_1),
to_uni(locale.nl_langinfo(locale.ABMON_2), codeset), locale.nl_langinfo(locale.ABMON_2),
to_uni(locale.nl_langinfo(locale.ABMON_3), codeset), locale.nl_langinfo(locale.ABMON_3),
to_uni(locale.nl_langinfo(locale.ABMON_4), codeset), locale.nl_langinfo(locale.ABMON_4),
to_uni(locale.nl_langinfo(locale.ABMON_5), codeset), locale.nl_langinfo(locale.ABMON_5),
to_uni(locale.nl_langinfo(locale.ABMON_6), codeset), locale.nl_langinfo(locale.ABMON_6),
to_uni(locale.nl_langinfo(locale.ABMON_7), codeset), locale.nl_langinfo(locale.ABMON_7),
to_uni(locale.nl_langinfo(locale.ABMON_8), codeset), locale.nl_langinfo(locale.ABMON_8),
to_uni(locale.nl_langinfo(locale.ABMON_9), codeset), locale.nl_langinfo(locale.ABMON_9),
to_uni(locale.nl_langinfo(locale.ABMON_10), codeset), locale.nl_langinfo(locale.ABMON_10),
to_uni(locale.nl_langinfo(locale.ABMON_11), codeset), locale.nl_langinfo(locale.ABMON_11),
to_uni(locale.nl_langinfo(locale.ABMON_12), codeset), locale.nl_langinfo(locale.ABMON_12),
) )
# Gramps day number: Sunday => 1, Monday => 2, etc # Gramps day number: Sunday => 1, Monday => 2, etc
@ -86,24 +78,24 @@ try:
# see http://docs.python.org/library/locale.html # see http://docs.python.org/library/locale.html
_deprecated_long_days = ( _deprecated_long_days = (
"", "",
to_uni(locale.nl_langinfo(locale.DAY_1), codeset), # Sunday locale.nl_langinfo(locale.DAY_1), # Sunday
to_uni(locale.nl_langinfo(locale.DAY_2), codeset), # Monday locale.nl_langinfo(locale.DAY_2), # Monday
to_uni(locale.nl_langinfo(locale.DAY_3), codeset), # Tuesday locale.nl_langinfo(locale.DAY_3), # Tuesday
to_uni(locale.nl_langinfo(locale.DAY_4), codeset), # Wednesday locale.nl_langinfo(locale.DAY_4), # Wednesday
to_uni(locale.nl_langinfo(locale.DAY_5), codeset), # Thursday locale.nl_langinfo(locale.DAY_5), # Thursday
to_uni(locale.nl_langinfo(locale.DAY_6), codeset), # Friday locale.nl_langinfo(locale.DAY_6), # Friday
to_uni(locale.nl_langinfo(locale.DAY_7), codeset), # Saturday locale.nl_langinfo(locale.DAY_7), # Saturday
) )
_deprecated_short_days = ( _deprecated_short_days = (
"", "",
to_uni(locale.nl_langinfo(locale.ABDAY_1), codeset), # Sunday locale.nl_langinfo(locale.ABDAY_1), # Sunday
to_uni(locale.nl_langinfo(locale.ABDAY_2), codeset), # Monday locale.nl_langinfo(locale.ABDAY_2), # Monday
to_uni(locale.nl_langinfo(locale.ABDAY_3), codeset), # Tuesday locale.nl_langinfo(locale.ABDAY_3), # Tuesday
to_uni(locale.nl_langinfo(locale.ABDAY_4), codeset), # Wednesday locale.nl_langinfo(locale.ABDAY_4), # Wednesday
to_uni(locale.nl_langinfo(locale.ABDAY_5), codeset), # Thursday locale.nl_langinfo(locale.ABDAY_5), # Thursday
to_uni(locale.nl_langinfo(locale.ABDAY_6), codeset), # Friday locale.nl_langinfo(locale.ABDAY_6), # Friday
to_uni(locale.nl_langinfo(locale.ABDAY_7), codeset), # Saturday locale.nl_langinfo(locale.ABDAY_7), # Saturday
) )
tformat = locale.nl_langinfo(locale.D_FMT).replace('%y','%Y') tformat = locale.nl_langinfo(locale.D_FMT).replace('%y','%Y')
@ -116,34 +108,34 @@ except:
_deprecated_long_months = ( _deprecated_long_months = (
"", "",
to_uni(time.strftime('%B',(1,1,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,1,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,2,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,2,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,3,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,3,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,4,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,4,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,5,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,5,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,6,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,6,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,7,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,7,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,8,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,8,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,9,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,9,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,10,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,10,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,11,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,11,1,1,1,1,1,1,1)),
to_uni(time.strftime('%B',(1,12,1,1,1,1,1,1,1)), codeset), time.strftime('%B',(1,12,1,1,1,1,1,1,1)),
) )
_deprecated_short_months = ( _deprecated_short_months = (
"", "",
to_uni(time.strftime('%b',(1,1,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,1,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,2,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,2,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,3,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,3,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,4,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,4,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,5,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,5,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,6,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,6,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,7,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,7,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,8,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,8,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,9,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,9,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,10,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,10,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,11,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,11,1,1,1,1,1,1,1)),
to_uni(time.strftime('%b',(1,12,1,1,1,1,1,1,1)), codeset), time.strftime('%b',(1,12,1,1,1,1,1,1,1)),
) )
# Gramps day number: Sunday => 1, Monday => 2, etc # Gramps day number: Sunday => 1, Monday => 2, etc
@ -157,24 +149,24 @@ except:
# just a dummy. # just a dummy.
_deprecated_long_days = ( _deprecated_long_days = (
"", "",
to_uni(time.strftime('%A',(1,1,1,1,1,1,6,1,1)), codeset), # Sunday time.strftime('%A',(1,1,1,1,1,1,6,1,1)), # Sunday
to_uni(time.strftime('%A',(1,1,1,1,1,1,0,1,1)), codeset), # Monday time.strftime('%A',(1,1,1,1,1,1,0,1,1)), # Monday
to_uni(time.strftime('%A',(1,1,1,1,1,1,1,1,1)), codeset), # Tuesday time.strftime('%A',(1,1,1,1,1,1,1,1,1)), # Tuesday
to_uni(time.strftime('%A',(1,1,1,1,1,1,2,1,1)), codeset), # Wednesday time.strftime('%A',(1,1,1,1,1,1,2,1,1)), # Wednesday
to_uni(time.strftime('%A',(1,1,1,1,1,1,3,1,1)), codeset), # Thursday time.strftime('%A',(1,1,1,1,1,1,3,1,1)), # Thursday
to_uni(time.strftime('%A',(1,1,1,1,1,1,4,1,1)), codeset), # Friday time.strftime('%A',(1,1,1,1,1,1,4,1,1)), # Friday
to_uni(time.strftime('%A',(1,1,1,1,1,1,5,1,1)), codeset), # Saturday time.strftime('%A',(1,1,1,1,1,1,5,1,1)), # Saturday
) )
_deprecated_short_days = ( _deprecated_short_days = (
"", "",
to_uni(time.strftime('%a',(1,1,1,1,1,1,6,1,1)), codeset), # Sunday time.strftime('%a',(1,1,1,1,1,1,6,1,1)), # Sunday
to_uni(time.strftime('%a',(1,1,1,1,1,1,0,1,1)), codeset), # Monday time.strftime('%a',(1,1,1,1,1,1,0,1,1)), # Monday
to_uni(time.strftime('%a',(1,1,1,1,1,1,1,1,1)), codeset), # Tuesday time.strftime('%a',(1,1,1,1,1,1,1,1,1)), # Tuesday
to_uni(time.strftime('%a',(1,1,1,1,1,1,2,1,1)), codeset), # Wednesday time.strftime('%a',(1,1,1,1,1,1,2,1,1)), # Wednesday
to_uni(time.strftime('%a',(1,1,1,1,1,1,3,1,1)), codeset), # Thursday time.strftime('%a',(1,1,1,1,1,1,3,1,1)), # Thursday
to_uni(time.strftime('%a',(1,1,1,1,1,1,4,1,1)), codeset), # Friday time.strftime('%a',(1,1,1,1,1,1,4,1,1)), # Friday
to_uni(time.strftime('%a',(1,1,1,1,1,1,5,1,1)), codeset), # Saturday time.strftime('%a',(1,1,1,1,1,1,5,1,1)), # Saturday
) )
# depending on the locale, the value returned for 20th Feb 2009 could be # depending on the locale, the value returned for 20th Feb 2009 could be

@ -53,11 +53,7 @@ db.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #

@ -185,12 +185,7 @@ class BSDDBTxn(object):
# test code # test code
if __name__ == "__main__": if __name__ == "__main__":
print("1") print("1")
from ..config import config from bsddb3 import db, dbshelve
import sys
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
from bsddb3 import db, dbshelve
else:
from bsddb import db, dbshelve
print("2") print("2")
x = db.DBEnv() x = db.DBEnv()
print("3") print("3")

@ -24,18 +24,10 @@
# Standard python modules # Standard python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys from pickle import dumps, loads
if sys.version_info[0] < 3:
from cPickle import dumps, loads
else:
from pickle import dumps, loads
from ..config import config
try: try:
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3: from bsddb3 import db
from bsddb3 import db
else:
from bsddb import db
except: except:
# FIXME: make this more abstract to deal with other backends # FIXME: make this more abstract to deal with other backends
class db: class db:

@ -23,13 +23,6 @@
Declare constants used by database modules Declare constants used by database modules
""" """
#-------------------------------------------------------------------------
#
# standard python modules
#
#-------------------------------------------------------------------------
import sys
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# constants # constants
@ -67,12 +60,8 @@ DBLOCKS = 100000 # Maximum number of locks supported
DBOBJECTS = 100000 # Maximum number of simultaneously locked objects DBOBJECTS = 100000 # Maximum number of simultaneously locked objects
DBUNDO = 1000 # Maximum size of undo buffer DBUNDO = 1000 # Maximum size of undo buffer
from ..config import config
try: try:
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3: from bsddb3.db import DB_CREATE, DB_AUTO_COMMIT, DB_DUP, DB_DUPSORT, DB_RDONLY
from bsddb3.db import DB_CREATE, DB_AUTO_COMMIT, DB_DUP, DB_DUPSORT, DB_RDONLY
else:
from bsddb.db import DB_CREATE, DB_AUTO_COMMIT, DB_DUP, DB_DUPSORT, DB_RDONLY
DBFLAGS_O = DB_CREATE | DB_AUTO_COMMIT # Default flags for database open DBFLAGS_O = DB_CREATE | DB_AUTO_COMMIT # Default flags for database open
DBFLAGS_R = DB_RDONLY # Flags to open a database read-only DBFLAGS_R = DB_RDONLY # Flags to open a database read-only
DBFLAGS_D = DB_DUP | DB_DUPSORT # Default flags for duplicate keys DBFLAGS_D = DB_DUP | DB_DUPSORT # Default flags for duplicate keys

@ -24,11 +24,7 @@
# Gramps Modules # Gramps Modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import base64 import base64
import time import time
import re import re
@ -1167,12 +1163,7 @@ class DictionaryDb(DbWriteBase, DbReadBase):
# so we need the second tuple give us a reference that we can # so we need the second tuple give us a reference that we can
# combine with the primary_handle to get the main key. # combine with the primary_handle to get the main key.
if sys.version_info[0] < 3: main_key = (handle.decode('utf-8'), pickle.loads(data)[1][1])
#handle should be in python 2 str
main_key = (handle, pickle.loads(data)[1][1])
else:
#python 3 work internally with unicode
main_key = (handle.decode('utf-8'), pickle.loads(data)[1][1])
# The trick is not to remove while inside the cursor, # The trick is not to remove while inside the cursor,
# but collect them all and remove after the cursor is closed # but collect them all and remove after the cursor is closed
@ -1194,7 +1185,7 @@ class DictionaryDb(DbWriteBase, DbReadBase):
if isinstance(key, tuple): if isinstance(key, tuple):
#create a byte string key, first validity check in python 3! #create a byte string key, first validity check in python 3!
for val in key: for val in key:
if sys.version_info[0] >= 3 and isinstance(val, bytes): if isinstance(val, bytes):
raise DbError(_('An attempt is made to save a reference key ' raise DbError(_('An attempt is made to save a reference key '
'which is partly bytecode, this is not allowed.\n' 'which is partly bytecode, this is not allowed.\n'
'Key is %s') % str(key)) 'Key is %s') % str(key))

@ -29,22 +29,14 @@ Read classes for the Gramps databases.
# libraries # libraries
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import time import time
import random import random
import os import os
from sys import maxsize from sys import maxsize
from ..config import config
try: try:
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3: from bsddb3 import db
from bsddb3 import db
else:
from bsddb import db
except: except:
# FIXME: make this more abstract to deal with other backends # FIXME: make this more abstract to deal with other backends
class db: class db:
@ -142,10 +134,7 @@ def __index_surname(surn_list):
NameOriginType.PATRONYMIC, NameOriginType.MATRONYMIC]) ]) NameOriginType.PATRONYMIC, NameOriginType.MATRONYMIC]) ])
else: else:
surn = "" surn = ""
if sys.version_info[0] < 3: return surn
return surn.encode('utf-8')
else:
return surn
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

@ -20,16 +20,11 @@
import unittest import unittest
import os import os
import sys
import tempfile import tempfile
import shutil import shutil
from ...constfunc import UNITYPE from ...constfunc import UNITYPE
from ...config import config from bsddb3 import dbshelve, db
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
from bsddb3 import dbshelve, db
else:
from bsddb import dbshelve, db
from ..read import DbBsddbTreeCursor from ..read import DbBsddbTreeCursor

@ -28,13 +28,8 @@ database.
# Standard python modules # Standard python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import logging import logging
from collections import defaultdict from collections import defaultdict
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

@ -30,19 +30,11 @@ undos and redos.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import time, os import time, os
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
from collections import deque from collections import deque
from ..config import config
try: try:
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3: from bsddb3 import db
from bsddb3 import db
else:
from bsddb import db
except: except:
# FIXME: make this more abstract to deal with other backends # FIXME: make this more abstract to deal with other backends
class db: class db:

@ -28,17 +28,11 @@ methods to upgrade a database from version 13 to current version
# Standard python modules # Standard python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys
import os import os
import re import re
import time import time
import logging import logging
from bsddb3 import db
from ..config import config
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
from bsddb3 import db
else:
from bsddb import db
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -31,10 +31,7 @@ This is used since Gramps version 3.0
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys import sys
if sys.version_info[0] < 3: import pickle
import cPickle as pickle
else:
import pickle
import os import os
import time import time
import bisect import bisect
@ -43,12 +40,8 @@ from functools import wraps
import logging import logging
from sys import maxsize, getfilesystemencoding, version_info from sys import maxsize, getfilesystemencoding, version_info
from ..config import config
try: try:
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3: from bsddb3 import dbshelve, db
from bsddb3 import dbshelve, db
else:
from bsddb import dbshelve, db
except: except:
# FIXME: make this more abstract to deal with other backends # FIXME: make this more abstract to deal with other backends
class db: class db:
@ -277,10 +270,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
__signals__['home-person-changed'] = None __signals__['home-person-changed'] = None
# 4. Signal for change in person group name, parameters are # 4. Signal for change in person group name, parameters are
if sys.version_info[0] < 3: __signals__['person-groupname-rebuild'] = (str, str)
__signals__['person-groupname-rebuild'] = (unicode, unicode)
else:
__signals__['person-groupname-rebuild'] = (str, str)
def __init__(self): def __init__(self):
"""Create a new GrampsDB.""" """Create a new GrampsDB."""
@ -537,11 +527,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
reserved_char = r':,<>"/\|?* ' reserved_char = r':,<>"/\|?* '
replace_char = "-__________" replace_char = "-__________"
title = self.get_dbname() title = self.get_dbname()
if sys.version_info[0] < 3: trans = title.maketrans(reserved_char, replace_char)
from string import maketrans
trans = maketrans(reserved_char, replace_char)
else:
trans = title.maketrans(reserved_char, replace_char)
title = title.translate(trans) title = title.translate(trans)
if not os.access(dirname, os.W_OK): if not os.access(dirname, os.W_OK):
@ -736,7 +722,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
# Check for pickle upgrade # Check for pickle upgrade
versionpath = os.path.join(self.path, cuni(PCKVERSFN)) versionpath = os.path.join(self.path, cuni(PCKVERSFN))
if sys.version_info[0] >= 3 and not os.path.isfile(versionpath) and \ if not os.path.isfile(versionpath) and \
not self.readonly and not self.update_pickle_version: not self.readonly and not self.update_pickle_version:
_LOG.debug("Make backup in case there is a pickle upgrade") _LOG.debug("Make backup in case there is a pickle upgrade")
self.__make_zip_backup(name) self.__make_zip_backup(name)
@ -860,18 +846,12 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
versionpath = os.path.join(name, BDBVERSFN) versionpath = os.path.join(name, BDBVERSFN)
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version = str(db.version()) version = str(db.version())
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
version_file.write(version) version_file.write(version)
_LOG.debug("Updated bsddb version file to %s" % str(db.version())) _LOG.debug("Updated bsddb version file to %s" % str(db.version()))
if self.update_python_version: if self.update_python_version:
versionpath = os.path.join(name, "pythonversion.txt") versionpath = os.path.join(name, "pythonversion.txt")
version = str(version_info[0]) version = str(version_info[0])
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
_LOG.debug("Updated python version file to %s" % version) _LOG.debug("Updated python version file to %s" % version)
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version_file.write(version) version_file.write(version)
@ -887,9 +867,6 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
versionpath = os.path.join(name, cuni(PCKVERSFN)) versionpath = os.path.join(name, cuni(PCKVERSFN))
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version = "Yes" version = "Yes"
if sys.version_info[0] <3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
version_file.write(version) version_file.write(version)
_LOG.debug("Updated pickle version file to %s" % str(version)) _LOG.debug("Updated pickle version file to %s" % str(version))
@ -905,9 +882,6 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
versionpath = os.path.join(name, cuni(SCHVERSFN)) versionpath = os.path.join(name, cuni(SCHVERSFN))
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version = str(_DBVERSION) version = str(_DBVERSION)
if sys.version_info[0] <3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
version_file.write(version) version_file.write(version)
_LOG.debug("Updated schema version file to %s" % str(version)) _LOG.debug("Updated schema version file to %s" % str(version))
else: else:
@ -1243,12 +1217,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
# so we need the second tuple give us a reference that we can # so we need the second tuple give us a reference that we can
# combine with the primary_handle to get the main key. # combine with the primary_handle to get the main key.
if sys.version_info[0] < 3: main_key = (handle.decode('utf-8'), pickle.loads(data)[1][1])
#handle should be in python 2 str
main_key = (handle, pickle.loads(data)[1][1])
else:
#python 3 work internally with unicode
main_key = (handle.decode('utf-8'), pickle.loads(data)[1][1])
# The trick is not to remove while inside the cursor, # The trick is not to remove while inside the cursor,
# but collect them all and remove after the cursor is closed # but collect them all and remove after the cursor is closed
@ -1327,16 +1296,12 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
""" """
if isinstance(key, tuple): if isinstance(key, tuple):
#create a byte string key, first validity check in python 3! #create a byte string key, first validity check in python 3!
if sys.version_info[0] >= 3: for val in key:
for val in key: if isinstance(val, bytes):
if isinstance(val, bytes): raise DbError(_('An attempt is made to save a reference key '
raise DbError(_('An attempt is made to save a reference key ' 'which is partly bytecode, this is not allowed.\n'
'which is partly bytecode, this is not allowed.\n' 'Key is %s') % str(key))
'Key is %s') % str(key)) key = str(key)
if sys.version_info[0] >= 3:
key= str(key)
else:
key = str(tuple(k.encode('utf-8') for k in key))
if isinstance(key, UNITYPE): if isinstance(key, UNITYPE):
key = key.encode('utf-8') key = key.encode('utf-8')
if not self.readonly: if not self.readonly:
@ -1353,10 +1318,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
""" """
if isinstance(key, tuple): if isinstance(key, tuple):
#create a string key #create a string key
if sys.version_info[0] >= 3: key = str(key)
key= str(key)
else:
key = str(tuple(k.encode('utf-8') for k in key))
if isinstance(key, UNITYPE): if isinstance(key, UNITYPE):
key = key.encode('utf-8') key = key.encode('utf-8')
if self.readonly or not key: if self.readonly or not key:
@ -1892,18 +1854,11 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
""" """
name = find_surname_name(person.handle, name = find_surname_name(person.handle,
person.get_primary_name().serialize()) person.get_primary_name().serialize())
if sys.version_info[0] < 3: if isinstance(name, str):
if isinstance(name, unicode): uname = name
uname = name name = name.encode('utf-8')
name = str(name)
else:
uname = unicode(name, 'utf-8')
else: else:
if isinstance(name, str): uname = str(name)
uname = name
name = name.encode('utf-8')
else:
uname = str(name)
try: try:
cursor = self.surnames.cursor(txn=self.txn) cursor = self.surnames.cursor(txn=self.txn)
cursor_position = cursor.set(name) cursor_position = cursor.set(name)
@ -2454,18 +2409,12 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
versionpath = os.path.join(name, BDBVERSFN) versionpath = os.path.join(name, BDBVERSFN)
version = str(db.version()) version = str(db.version())
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
_LOG.debug("Write bsddb version %s" % version) _LOG.debug("Write bsddb version %s" % version)
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version_file.write(version) version_file.write(version)
versionpath = os.path.join(name, "pythonversion.txt") versionpath = os.path.join(name, "pythonversion.txt")
version = str(version_info[0]) version = str(version_info[0])
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
_LOG.debug("Write python version file to %s" % version) _LOG.debug("Write python version file to %s" % version)
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version_file.write(version) version_file.write(version)
@ -2474,18 +2423,12 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
_LOG.debug("Write pickle version file to %s" % "Yes") _LOG.debug("Write pickle version file to %s" % "Yes")
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version = "Yes" version = "Yes"
if sys.version_info[0] <3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
version_file.write(version) version_file.write(version)
versionpath = os.path.join(name, cuni(SCHVERSFN)) versionpath = os.path.join(name, cuni(SCHVERSFN))
_LOG.debug("Write schema version file to %s" % str(_DBVERSION)) _LOG.debug("Write schema version file to %s" % str(_DBVERSION))
with open(versionpath, "w") as version_file: with open(versionpath, "w") as version_file:
version = str(_DBVERSION) version = str(_DBVERSION)
if sys.version_info[0] <3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
version_file.write(version) version_file.write(version)
self.metadata.close() self.metadata.close()

@ -19,16 +19,8 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# #
import sys
import subprocess import subprocess
if sys.version_info[0] < 3:
cuni = unicode
else:
def to_utf8(s):
return s.decode("utf-8", errors = 'replace')
cuni = to_utf8
def get_git_revision(path=""): def get_git_revision(path=""):
stdout = "" stdout = ""
command = "git log -1 --format=%h" command = "git log -1 --format=%h"
@ -43,7 +35,7 @@ def get_git_revision(path=""):
# subprocess worked # subprocess worked
if stdout and len(stdout) > 0: # has output if stdout and len(stdout) > 0: # has output
try: try:
stdout = cuni(stdout) # get a proper string stdout = stdout.decode("utf-8", errors = 'replace')
except UnicodeDecodeError: except UnicodeDecodeError:
pass pass
return "-" + stdout if stdout else "" return "-" + stdout if stdout else ""

@ -31,11 +31,7 @@ Media object for Gramps.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys from urllib.parse import urlparse
if sys.version_info[0] < 3:
from urlparse import urlparse
else:
from urllib.parse import urlparse
import logging import logging
LOG = logging.getLogger(".citation") LOG = logging.getLogger(".citation")

@ -29,11 +29,7 @@ Url class for Gramps.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from warnings import warn from warnings import warn
import sys from urllib.parse import urlparse
if sys.version_info[0] < 3:
from urlparse import urlparse
else:
from urllib.parse import urlparse
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -28,12 +28,7 @@ Mime utility functions for the MS Windows platform
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys from winreg import *
if sys.version_info[0] < 3:
from _winreg import *
else:
from winreg import *
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -24,9 +24,7 @@
# Python modules # Python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys
import types import types
import logging import logging
LOG = logging.getLogger(".Gramplets") LOG = logging.getLogger(".Gramplets")
@ -324,11 +322,7 @@ class Gramplet(object):
LOG.debug("gramplet updater: %s : One time, done!" % self.gui.title) LOG.debug("gramplet updater: %s : One time, done!" % self.gui.title)
return False return False
# FIXME: find out why Data Entry has this error, or just ignore it # FIXME: find out why Data Entry has this error, or just ignore it
from ..config import config import bsddb3 as bsddb
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
import bsddb3 as bsddb
else:
import bsddb
try: try:
retval = next(self._generator) retval = next(self._generator)
if not retval: if not retval:

@ -257,7 +257,7 @@ class BasePluginManager(object):
except ValueError as err: except ValueError as err:
# Python3 on Windows work with unicode in sys.path # Python3 on Windows work with unicode in sys.path
# but they are mbcs encode for checking validity # but they are mbcs encode for checking validity
if (sys.version_info[0] >= 3) and win(): if win():
# we don't want to load Gramps core plugin like this # we don't want to load Gramps core plugin like this
# only 3rd party plugins # only 3rd party plugins
if "gramps" in pdata.fpath: if "gramps" in pdata.fpath:
@ -275,20 +275,8 @@ class BasePluginManager(object):
LOG.warning("Plugin error (from '%s'): %s" LOG.warning("Plugin error (from '%s'): %s"
% (pdata.mod_name, err)) % (pdata.mod_name, err))
except ImportError as err: except ImportError as err:
# Python2 on Windows not work with unicode in sys.path LOG.warning("Plugin error (from '%s'): %s"
# but module can be loaded from current directory % (pdata.mod_name, err))
if (sys.version_info[0] < 3) and win():
try:
oldwd = os.getcwd()
os.chdir(pdata.fpath)
module = __import__(pdata.mod_name)
os.chdir(oldwd)
except ImportError as err:
LOG.warning("Plugin error (from '%s'): %s"
% (pdata.mod_name, err))
else:
LOG.warning("Plugin error (from '%s'): %s"
% (pdata.mod_name, err))
sys.path.pop(0) sys.path.pop(0)
else: else:
print("WARNING: module cannot be loaded") print("WARNING: module cannot be loaded")

@ -841,8 +841,7 @@ class PluginData(object):
def _set_gramplet_title(self, gramplet_title): def _set_gramplet_title(self, gramplet_title):
if not self._ptype == GRAMPLET: if not self._ptype == GRAMPLET:
raise ValueError('gramplet_title may only be set for GRAMPLET plugins') raise ValueError('gramplet_title may only be set for GRAMPLET plugins')
if not (sys.version_info[0] < 3 and isinstance(gramplet_title, unicode) if not isinstance(gramplet_title, str):
or isinstance(gramplet_title, str)):
raise ValueError('gramplet_title is type %s, string or unicode required' % type(gramplet_title)) raise ValueError('gramplet_title is type %s, string or unicode required' % type(gramplet_title))
self._gramplet_title = gramplet_title self._gramplet_title = gramplet_title
@ -1098,10 +1097,7 @@ class PluginRegister(object):
continue continue
lenpd = len(self.__plugindata) lenpd = len(self.__plugindata)
full_filename = os.path.join(dir, filename) full_filename = os.path.join(dir, filename)
if sys.version_info[0] < 3: fd = io.open(full_filename, "r", encoding='utf-8')
fd = open(full_filename, "r")
else:
fd = io.open(full_filename, "r", encoding='utf-8')
stream = fd.read() stream = fd.read()
fd.close() fd.close()
if os.path.exists(os.path.join(os.path.dirname(full_filename), if os.path.exists(os.path.join(os.path.dirname(full_filename),

@ -30,11 +30,7 @@
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import os import os
import sys from io import BytesIO
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import BytesIO
import tempfile import tempfile
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
import sys import sys
@ -381,10 +377,7 @@ class GVDocBase(BaseDoc, GVDoc):
BaseDoc.__init__(self, None, paper_style) BaseDoc.__init__(self, None, paper_style)
self._filename = None self._filename = None
if sys.version_info[0] < 3: self._dot = BytesIO()
self._dot = StringIO()
else:
self._dot = BytesIO()
self._paper = paper_style self._paper = paper_style
get_option_by_name = options.menu.get_option_by_name get_option_by_name = options.menu.get_option_by_name
@ -610,10 +603,7 @@ class GVDotDoc(GVDocBase):
if self._filename[-3:] != ".gv": if self._filename[-3:] != ".gv":
self._filename += ".gv" self._filename += ".gv"
if sys.version_info[0] < 3: dotfile = open(self._filename, "wb")
dotfile = open(self._filename, "w")
else:
dotfile = open(self._filename, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
@ -648,10 +638,7 @@ class GVPsDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
@ -704,10 +691,7 @@ class GVSvgDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
# Generate the SVG file. # Generate the SVG file.
@ -741,10 +725,7 @@ class GVSvgzDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
# Generate the SVGZ file. # Generate the SVGZ file.
@ -778,10 +759,7 @@ class GVPngDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
# Generate the PNG file. # Generate the PNG file.
@ -815,10 +793,7 @@ class GVJpegDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
# Generate the JPEG file. # Generate the JPEG file.
@ -852,10 +827,7 @@ class GVGifDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
# Generate the GIF file. # Generate the GIF file.
@ -892,10 +864,7 @@ class GVPdfGvDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()
fname = self._filename fname = self._filename
@ -929,10 +898,7 @@ class GVPdfGsDoc(GVDocBase):
# Create a temporary dot file # Create a temporary dot file
(handle, tmp_dot) = tempfile.mkstemp(".gv" ) (handle, tmp_dot) = tempfile.mkstemp(".gv" )
if sys.version_info[0] < 3: dotfile = os.fdopen(handle, "wb")
dotfile = os.fdopen(handle, "w")
else:
dotfile = os.fdopen(handle, "wb")
dotfile.write(self._dot.getvalue()) dotfile.write(self._dot.getvalue())
dotfile.close() dotfile.close()

@ -30,10 +30,7 @@ General utility functions useful for the generic plugin system
import sys import sys
import os import os
import datetime import datetime
if sys.version_info[0] < 3: from io import StringIO, BytesIO
from StringIO import StringIO
else:
from io import StringIO, BytesIO
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -178,10 +175,7 @@ class Zipfile(object):
def available_updates(): def available_updates():
whattypes = config.get('behavior.check-for-update-types') whattypes = config.get('behavior.check-for-update-types')
if sys.version_info[0] < 3: from urllib.request import urlopen
from urllib2 import urlopen
else:
from urllib.request import urlopen
LOG.debug("Checking for updated addons...") LOG.debug("Checking for updated addons...")
langs = glocale.get_language_list() langs = glocale.get_language_list()
langs.append("en") langs.append("en")
@ -265,10 +259,7 @@ def load_addon_file(path, callback=None):
""" """
Load an addon from a particular path (from URL or file system). Load an addon from a particular path (from URL or file system).
""" """
if sys.version_info[0] < 3: from urllib.request import urlopen
from urllib2 import urlopen
else:
from urllib.request import urlopen
import tarfile import tarfile
import io import io
if (path.startswith("http://") or if (path.startswith("http://") or
@ -289,10 +280,7 @@ def load_addon_file(path, callback=None):
return False return False
try: try:
content = fp.read() content = fp.read()
if sys.version_info[0] < 3: buffer = BytesIO(content)
buffer = StringIO(content)
else:
buffer = BytesIO(content)
except: except:
if callback: if callback:
callback(_("Error in reading '%s'") % path) callback(_("Error in reading '%s'") % path)

@ -25,17 +25,6 @@
Proxy class for the Gramps databases. Apply filter Proxy class for the Gramps databases. Apply filter
""" """
#-------------------------------------------------------------------------
#
# Python libraries
#
#-------------------------------------------------------------------------
import sys
if sys.version_info[0] < 3:
from itertools import imap as map
else:
pass #python 3 has map behaving as imap
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# GRAMPS libraries # GRAMPS libraries

@ -22,17 +22,6 @@
Proxy class for the Gramps databases. Filter out all living people. Proxy class for the Gramps databases. Filter out all living people.
""" """
#-------------------------------------------------------------------------
#
# Python libraries
#
#-------------------------------------------------------------------------
import sys
if sys.version_info[0] < 3:
from itertools import ifilter as filter
else:
pass #python 3 has filter
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# GRAMPS libraries # GRAMPS libraries

@ -28,11 +28,6 @@ Proxy class for the Gramps databases. Filter out all data marked private.
# Python modules # Python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys
if sys.version_info[0] < 3:
from itertools import ifilter as filter
else:
pass #python 3 has filter
import types import types
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

@ -29,9 +29,8 @@
import os import os
import time import time
import io import io
import sys
import logging import logging
from xml.parsers.expat import ParserCreate from xml.parsers.expat import ParserCreate
try: try:
import fcntl import fcntl
@ -184,9 +183,7 @@ class RecentFiles(object):
""" """
Saves the current Gramps RecentFiles collection to the associated file. Saves the current Gramps RecentFiles collection to the associated file.
""" """
with (open(os.path.expanduser(GRAMPS_FILENAME), 'w') with open(os.path.expanduser(GRAMPS_FILENAME), 'w', encoding='utf8') \
if sys.version_info[0] < 3 else
open(os.path.expanduser(GRAMPS_FILENAME), 'w', encoding='utf8'))\
as xml_file: as xml_file:
if use_lock: if use_lock:
fcntl.lockf(xml_file,fcntl.LOCK_EX) fcntl.lockf(xml_file,fcntl.LOCK_EX)
@ -224,9 +221,7 @@ class RecentParser(object):
return # it's the first time gramps has ever been run return # it's the first time gramps has ever been run
try: try:
# Python3's expat wants bytes, Python2's wants a string. with open(fname, "rb") as xml_file:
fmode = "r" if sys.version_info[0] < 3 else "rb"
with open(fname, fmode) as xml_file:
if use_lock: if use_lock:
fcntl.lockf(xml_file,fcntl.LOCK_SH) fcntl.lockf(xml_file,fcntl.LOCK_SH)

@ -27,10 +27,7 @@ Provide soundex calculation
# Standard python modules # Standard python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys
import unicodedata import unicodedata
if sys.version_info[0] < 3:
import string
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -38,12 +35,8 @@ if sys.version_info[0] < 3:
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
IGNORE = "HW~!@#$%^&*()_+=-`[]\|;:'/?.,<>\" \t\f\v" IGNORE = "HW~!@#$%^&*()_+=-`[]\|;:'/?.,<>\" \t\f\v"
if sys.version_info[0] < 3: TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
TABLE = string.maketrans('ABCDEFGIJKLMNOPQRSTUVXYZ', b'012301202245501262301202')
'012301202245501262301202')
else:
TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
b'012301202245501262301202')
from .constfunc import conv_to_unicode_direct from .constfunc import conv_to_unicode_direct
@ -59,14 +52,9 @@ def soundex(strval):
conv_to_unicode_direct(strval.upper().strip())).encode('ASCII', 'ignore') conv_to_unicode_direct(strval.upper().strip())).encode('ASCII', 'ignore')
if not strval: if not strval:
return "Z000" return "Z000"
if sys.version_info[0] < 3: strval = strval.decode('ASCII', 'ignore')
strval = strval.encode('iso-8859-1') # Really? str2 = strval[0]
str2 = strval[0] strval = strval.translate(TABLE)
strval = strval.translate(TABLE, IGNORE)
else:
strval = strval.decode('ASCII', 'ignore')
str2 = strval[0]
strval = strval.translate(TABLE)
if not strval: if not strval:
return "Z000" return "Z000"
prev = strval[0] prev = strval[0]

@ -32,10 +32,7 @@ This package implements access to Gramps configuration.
import os import os
import sys import sys
import time import time
if sys.version_info[0] < 3: import configparser
import ConfigParser as configparser
else:
import configparser
import errno import errno
import copy import copy
import logging import logging
@ -259,10 +256,7 @@ class ConfigManager(object):
if filename and os.path.exists(filename): if filename and os.path.exists(filename):
parser = configparser.RawConfigParser() parser = configparser.RawConfigParser()
try: # see bugs 5356, 5490, 5591, 5651, 5718, etc. try: # see bugs 5356, 5490, 5591, 5651, 5718, etc.
if sys.version_info[0] >= 3 : parser.read(filename, encoding='utf8')
parser.read(filename, encoding='utf8')
else:
parser.readfp(io.open(filename, encoding="utf-8"))
except Exception as err: except Exception as err:
msg1 = _("WARNING: could not parse file %s because %s, recreating it:\n") msg1 = _("WARNING: could not parse file %s because %s, recreating it:\n")
logging.warn(msg1 % (filename, str(err))) logging.warn(msg1 % (filename, str(err)))
@ -275,12 +269,11 @@ class ConfigManager(object):
self.data[name] = {} self.data[name] = {}
for opt in parser.options(sec): for opt in parser.options(sec):
raw_value = parser.get(sec, opt).strip() raw_value = parser.get(sec, opt).strip()
if sys.version_info[0] >= 3: if raw_value[:2] == "u'":
if raw_value[:2] == "u'": raw_value = raw_value[1:]
raw_value = raw_value[1:] elif raw_value.startswith('['):
elif raw_value.startswith('['): raw_value = raw_value.replace(", u'", ", '")
raw_value = raw_value.replace(", u'", ", '") raw_value = raw_value.replace("[u'", "['")
raw_value = raw_value.replace("[u'", "['")
setting = opt.lower() setting = opt.lower()
if oldstyle: if oldstyle:
####################### Upgrade from oldstyle < 3.2 ####################### Upgrade from oldstyle < 3.2

@ -847,9 +847,7 @@ class GrampsLocale(object):
#ICU can digest strings and unicode #ICU can digest strings and unicode
return self.collator.getCollationKey(string).getByteArray() return self.collator.getCollationKey(string).getByteArray()
else: else:
if sys.version_info[0] < 3 and isinstance(string, unicode): if isinstance(string, bytes):
string = string.encode("utf-8", "replace")
if sys.version_info[0] >= 3 and isinstance(string, bytes):
string = string.decode("utf-8", "replace") string = string.decode("utf-8", "replace")
try: try:
key = locale.strxfrm(string) key = locale.strxfrm(string)
@ -936,13 +934,7 @@ class GrampsLocale(object):
# Translations Classes # Translations Classes
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
if sys.version_info < (3,0): class Lexeme(str):
_LexemeBaseStr = unicode
_isstring = lambda s: isinstance(s, basestring)
else:
_LexemeBaseStr = str
_isstring = lambda s: isinstance(s, str)
class Lexeme(_LexemeBaseStr):
r""" r"""
Created with :meth:`~GrampsTranslations.lexgettext` Created with :meth:`~GrampsTranslations.lexgettext`
@ -1039,12 +1031,12 @@ class Lexeme(_LexemeBaseStr):
""" """
def __new__(cls, iterable, *args, **kwargs): def __new__(cls, iterable, *args, **kwargs):
if _isstring(iterable): if isinstance(iterable, str):
newobj = _LexemeBaseStr.__new__(cls, iterable, *args, **kwargs) newobj = str.__new__(cls, iterable, *args, **kwargs)
else: else:
od = collections.OrderedDict(iterable) od = collections.OrderedDict(iterable)
l = list(od.values()) or [""] l = list(od.values()) or [""]
newobj = _LexemeBaseStr.__new__(cls, l[0], *args, **kwargs) newobj = str.__new__(cls, l[0], *args, **kwargs)
newobj._forms = od newobj._forms = od
return newobj return newobj
@ -1085,10 +1077,7 @@ class GrampsTranslations(gettext.GNUTranslations):
# and that's not what we want. # and that's not what we want.
if len(msgid.strip()) == 0: if len(msgid.strip()) == 0:
return msgid return msgid
if sys.version_info[0] < 3: return gettext.GNUTranslations.gettext(self, msgid)
return gettext.GNUTranslations.ugettext(self, msgid)
else:
return gettext.GNUTranslations.gettext(self, msgid)
def ngettext(self, singular, plural, num): def ngettext(self, singular, plural, num):
""" """
@ -1106,12 +1095,7 @@ class GrampsTranslations(gettext.GNUTranslations):
:returns: Translation or the original. :returns: Translation or the original.
:rtype: unicode :rtype: unicode
""" """
if sys.version_info[0] < 3: return gettext.GNUTranslations.ngettext(self, singular, plural, num)
return gettext.GNUTranslations.ungettext(self, singular,
plural, num)
else:
return gettext.GNUTranslations.ngettext(self, singular,
plural, num)
def sgettext(self, msgid, sep='|'): def sgettext(self, msgid, sep='|'):
""" """

@ -24,7 +24,6 @@ Parses the lds.xml file to build the temple/code maps
from ..const import DATA_DIR from ..const import DATA_DIR
import os import os
import sys
import logging import logging
from xml.parsers.expat import ParserCreate from xml.parsers.expat import ParserCreate
@ -51,10 +50,7 @@ class LdsTemples(object):
lds_filename = os.path.join(DATA_DIR, "lds.xml") lds_filename = os.path.join(DATA_DIR, "lds.xml")
try: try:
if sys.version_info[0] < 3: xml_file = open(os.path.expanduser(lds_filename), 'rb')
xml_file = open(os.path.expanduser(lds_filename))
else:
xml_file = open(os.path.expanduser(lds_filename), 'rb')
parser = ParserCreate() parser = ParserCreate()
parser.StartElementHandler = self.__start_element parser.StartElementHandler = self.__start_element
parser.EndElementHandler = self.__end_element parser.EndElementHandler = self.__end_element

@ -75,7 +75,7 @@ locale, leaving $LANGUAGE unset (which is the same as setting it to
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import sys, os, subprocess, locale import os, subprocess, locale
import logging import logging
LOG = logging.getLogger(".gramps.gen.utils.grampslocale.mac") LOG = logging.getLogger(".gramps.gen.utils.grampslocale.mac")
LOG.propagate = True LOG.propagate = True
@ -100,8 +100,7 @@ def mac_setup_localization(glocale):
if not answer: if not answer:
LOG.debug("No prefs found for %s:%s", domain, key) LOG.debug("No prefs found for %s:%s", domain, key)
return None return None
if not sys.version_info[0] < 3: answer = answer.decode("utf-8")
answer = answer.decode("utf-8")
LOG.debug("Found %s for defaults %s:%s", answer.strip(), domain, key) LOG.debug("Found %s for defaults %s:%s", answer.strip(), domain, key)
return answer return answer
except OSError as err: except OSError as err:

@ -28,6 +28,7 @@
import os import os
import sys import sys
import io import io
import bsddb3 as bsddb
##import logging ##import logging
##_LOG = logging.getLogger(".GrampsAboutDialog") ##_LOG = logging.getLogger(".GrampsAboutDialog")
@ -58,12 +59,6 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
from gramps.gen.constfunc import get_env_var from gramps.gen.constfunc import get_env_var
from .display import display_url from .display import display_url
from gramps.gen.config import config
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
import bsddb3 as bsddb
else:
import bsddb
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -24,11 +24,7 @@
# standard python modules # standard python modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import os import os
from xml.sax.saxutils import escape from xml.sax.saxutils import escape
from time import strftime as strftime from time import strftime as strftime
@ -229,15 +225,12 @@ class ClipWrapper(object):
} }
return pickle.dumps(data) return pickle.dumps(data)
else: else:
if sys.version_info[0] < 3: if isinstance(self._obj, bytes):
return str(self._obj) return self._obj
else: else:
if isinstance(self._obj, bytes): ## don't know if this happens in Gramps, theoretically possible
return self._obj asuni = str(self._obj)
else: return asuni.encode('utf-8')
## don't know if this happens in Gramps, theoretically possible
asuni = str(self._obj)
return asuni.encode('utf-8')
def is_valid(self): def is_valid(self):
return True return True

@ -31,15 +31,11 @@ creating, and deleting of databases.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys
import time import time
import copy import copy
import shutil import shutil
import subprocess import subprocess
if sys.version_info[0] < 3: from urllib.parse import urlparse
from urlparse import urlparse
else:
from urllib.parse import urlparse
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -852,7 +848,7 @@ def find_revisions(name):
get_next = False get_next = False
if os.path.isfile(name): if os.path.isfile(name):
for line in proc.stdout: for line in proc.stdout:
if sys.version_info[0] >= 3 and not isinstance(line, UNITYPE): if not isinstance(line, UNITYPE):
# we assume utf-8 ... # we assume utf-8 ...
line = line.decode('utf-8') line = line.decode('utf-8')
match = rev.match(line) match = rev.match(line)

@ -27,11 +27,7 @@
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys from io import StringIO
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext

@ -19,8 +19,6 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# #
import sys
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# GTK libraries # GTK libraries
@ -57,10 +55,7 @@ class BackRefModel(Gtk.ListStore):
self.sref_list = sref_list self.sref_list = sref_list
self.count = 0 self.count = 0
self.loading = False self.loading = False
if sys.version_info[0] < 3: self.idle = GLib.idle_add(self.load_model().__next__)
self.idle = GLib.idle_add(self.load_model().next)
else:
self.idle = GLib.idle_add(self.load_model().__next__)
def destroy(self): def destroy(self):
if self.loading: if self.loading:

@ -26,11 +26,7 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -25,17 +25,9 @@
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys import pickle
if sys.version_info[0] < 3: from urllib.parse import urlparse
import cPickle as pickle from urllib.request import url2pathname
else:
import pickle
if sys.version_info[0] < 3:
from urlparse import urlparse
from urllib import url2pathname
else:
from urllib.parse import urlparse
from urllib.request import url2pathname
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -24,11 +24,7 @@
# python # python
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -32,11 +32,7 @@ mechanism for the user to edit address information.
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -26,17 +26,8 @@
# python modules # python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.config import config from bsddb3 import db as bsddb_db
import sys import pickle
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
from bsddb3 import db as bsddb_db
else:
from bsddb import db as bsddb_db
import sys
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -34,11 +34,7 @@ to edit information about a particular Person.
from copy import copy from copy import copy
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext _ = glocale.translation.sgettext
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -33,11 +33,7 @@ mechanism for the user to edit address information.
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -25,11 +25,7 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import logging import logging
_LOG = logging.getLogger(".objectentries") _LOG = logging.getLogger(".objectentries")

@ -30,12 +30,7 @@ from gi.repository import GdkPixbuf
from gi.repository import GObject from gi.repository import GObject
import cairo import cairo
import sys, os import sys, os
import bsddb3 as bsddb
from gramps.gen.config import config
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
import bsddb3 as bsddb
else:
import bsddb
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -30,11 +30,7 @@ the create/deletion of dialog windows.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys from io import StringIO
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -28,7 +28,6 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import traceback import traceback
import os import os
import sys
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -302,10 +301,7 @@ class PluginStatus(ManagedWindow):
""" """
Reloads the addons from the wiki into the list. Reloads the addons from the wiki into the list.
""" """
if sys.version_info[0] < 3: from urllib.request import urlopen
from urllib2 import urlopen
else:
from urllib.request import urlopen
from ..utils import ProgressMeter from ..utils import ProgressMeter
URL = "%s%s" % (URL_WIKISTRING, WIKI_EXTRAPLUGINS_RAWDATA) URL = "%s%s" % (URL_WIKISTRING, WIKI_EXTRAPLUGINS_RAWDATA)
try: try:

@ -31,11 +31,7 @@ This module provides the functions to build the quick report context menu's
#------------------------------------------------------------------------ #------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import sys from io import StringIO
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #

@ -29,11 +29,7 @@ Provide a simplified table creation interface
# Standard python modules # Standard python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -28,7 +28,6 @@ Handles generation and access to thumbnails used in GRAMPS.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys
import logging import logging
try: try:
from hashlib import md5 from hashlib import md5
@ -144,9 +143,8 @@ def __build_thumb_path(path, rectangle=None, size=SIZE_NORMAL):
extra = "" extra = ""
if rectangle is not None: if rectangle is not None:
extra = "?" + str(rectangle) extra = "?" + str(rectangle)
prehash = path+extra prehash = path + extra
if sys.version_info[0] >= 3: prehash = prehash.encode('utf-8')
prehash =prehash.encode('utf-8')
md5_hash = md5(prehash) md5_hash = md5(prehash)
if size == SIZE_LARGE: if size == SIZE_LARGE:
base_dir = THUMB_LARGE base_dir = THUMB_LARGE

@ -32,7 +32,6 @@ from random import Random
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import os import os
import sys
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -139,10 +138,7 @@ class TipParser(object):
self.mylist = [] self.mylist = []
self.skip = False self.skip = False
if sys.version_info[0] < 3: xml_file = open(TIP_DATA, 'rb')
xml_file = open(TIP_DATA)
else:
xml_file = open(TIP_DATA, 'rb')
self.tlist = [] self.tlist = []
parser = ParserCreate() parser = ParserCreate()
parser.StartElementHandler = self.startElement parser.StartElementHandler = self.startElement

@ -34,11 +34,7 @@
import cairo import cairo
#import math #import math
#import colorsys #import colorsys
#import sys #import pickle
#if sys.version_info[0] < 3:
# import cPickle as pickle
#else:
# import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -35,13 +35,9 @@ Manages the main window and the pluggable views
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from collections import defaultdict from collections import defaultdict
import os import os
import sys
import time import time
import datetime import datetime
if sys.version_info[0] < 3: from io import StringIO
from cStringIO import StringIO
else:
from io import StringIO
import posixpath import posixpath
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

@ -26,11 +26,7 @@
# Standard python modules # Standard python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys from io import StringIO
if sys.version_info[0] < 3:
from cStringIO import StringIO
else:
from io import StringIO
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -29,11 +29,7 @@ Provide the base classes for GRAMPS' DataView classes
# python modules # python modules
# #
#---------------------------------------------------------------- #----------------------------------------------------------------
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import time import time
import logging import logging

@ -27,7 +27,6 @@ Provide the base class for GRAMPS' DataView classes
# python modules # python modules
# #
#---------------------------------------------------------------- #----------------------------------------------------------------
import sys
import logging import logging
_LOG = logging.getLogger('.pageview') _LOG = logging.getLogger('.pageview')
@ -223,10 +222,7 @@ class PageView(DbGUIElement):
creates it. The copy is handled through the drag and drop creates it. The copy is handled through the drag and drop
system. system.
""" """
if sys.version_info[0] < 3: import pickle
import cPickle as pickle
else:
import pickle
from ..clipboard import ClipboardWindow, obj2target from ..clipboard import ClipboardWindow, obj2target
handled = False handled = False
for handle in handles: for handle in handles:

@ -53,7 +53,6 @@ It keeps a FlatNodeMap, and obtains data from database as needed
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import logging import logging
import bisect import bisect
import sys
import time import time
_LOG = logging.getLogger(".gui.basetreemodel") _LOG = logging.getLogger(".gui.basetreemodel")
@ -575,11 +574,8 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel):
# use cursor as a context manager # use cursor as a context manager
with self.gen_cursor() as cursor: with self.gen_cursor() as cursor:
#loop over database and store the sort field, and the handle #loop over database and store the sort field, and the handle
if sys.version_info[0] >= 3: srt_keys=[(self.sort_func(data), key.decode('utf8'))
srt_keys=[(self.sort_func(data), key.decode('utf8')) for key, data in cursor]
for key, data in cursor]
else:
srt_keys=[(self.sort_func(data), key) for key, data in cursor]
srt_keys.sort() srt_keys.sort()
return srt_keys return srt_keys
@ -647,8 +643,7 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel):
Add a row. This is called after object with handle is created. Add a row. This is called after object with handle is created.
Row is only added if search/filter data is such that it must be shown Row is only added if search/filter data is such that it must be shown
""" """
if sys.version_info[0] >= 3: assert isinstance(handle, str)
assert isinstance(handle, str)
if self.node_map.get_path_from_handle(handle) is not None: if self.node_map.get_path_from_handle(handle) is not None:
return # row is already displayed return # row is already displayed
data = self.map(handle) data = self.map(handle)
@ -668,8 +663,7 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel):
""" """
Delete a row, called after the object with handle is deleted Delete a row, called after the object with handle is deleted
""" """
if sys.version_info[0] >= 3: assert isinstance(handle, str)
assert isinstance(handle, str)
if self.node_map.get_path_from_handle(handle) is None: if self.node_map.get_path_from_handle(handle) is None:
return # row is not currently displayed return # row is not currently displayed
self.clear_cache(handle) self.clear_cache(handle)

@ -33,7 +33,6 @@ This module provides the model that is used for all hierarchical treeviews.
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import time import time
import sys
import logging import logging
_LOG = logging.getLogger(".gui.treebasemodel") _LOG = logging.getLogger(".gui.treebasemodel")
@ -784,8 +783,7 @@ class TreeBaseModel(GObject.GObject, Gtk.TreeModel):
""" """
Add a row to the model. Add a row to the model.
""" """
if sys.version_info[0] >= 3: assert isinstance(handle, str)
assert isinstance(handle, str)
if self._get_node(handle) is not None: if self._get_node(handle) is not None:
return # row already exists return # row already exists
cput = time.clock() cput = time.clock()
@ -808,8 +806,7 @@ class TreeBaseModel(GObject.GObject, Gtk.TreeModel):
""" """
Delete a row from the model. Delete a row from the model.
""" """
if sys.version_info[0] >= 3: assert isinstance(handle, str)
assert isinstance(handle, str)
cput = time.clock() cput = time.clock()
node = self._get_node(handle) node = self._get_node(handle)
if node is None: if node is None:
@ -840,8 +837,7 @@ class TreeBaseModel(GObject.GObject, Gtk.TreeModel):
""" """
Update a row in the model. Update a row in the model.
""" """
if sys.version_info[0] >= 3: assert isinstance(handle, str)
assert isinstance(handle, str)
if self._get_node(handle) is None: if self._get_node(handle) is None:
return # row not currently displayed return # row not currently displayed

@ -43,10 +43,7 @@ import cairo
import math import math
import colorsys import colorsys
import sys import sys
if sys.version_info[0] < 3: import pickle
import cPickle as pickle
else:
import pickle
from cgi import escape from cgi import escape
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

@ -41,11 +41,7 @@ from gi.repository import PangoCairo
import cairo import cairo
import math import math
import colorsys import colorsys
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
from cgi import escape from cgi import escape
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

@ -41,11 +41,7 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import time import time
import os import os
import sys import configparser
if sys.version_info[0] < 3:
import ConfigParser as configparser
else:
import configparser
import io import io
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

@ -35,11 +35,7 @@ from gi.repository import Pango
import time import time
import os import os
import io import io
import sys import configparser
if sys.version_info[0] < 3:
import ConfigParser as configparser
else:
import configparser
import logging import logging

@ -32,7 +32,6 @@ __all__ = ["MonitoredCheckbox", "MonitoredEntry",
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import logging import logging
_LOG = logging.getLogger(".widgets.monitoredwidgets") _LOG = logging.getLogger(".widgets.monitoredwidgets")
import sys
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -139,11 +138,7 @@ class MonitoredEntry(object):
self.obj.connect(signal, callback, *data) self.obj.connect(signal, callback, *data)
def _on_change(self, obj): def _on_change(self, obj):
if sys.version_info[0] < 3: self.set_val(obj.get_text())
self.set_val(cuni(obj.get_text(), 'utf-8'))
else:
#all is unicode
self.set_val(obj.get_text())
if self.changed: if self.changed:
self.changed(obj) self.changed(obj)

@ -27,7 +27,6 @@ __all__ = ["ShortlistComboEntry"]
# Python modules # Python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys
import logging import logging
_LOG = logging.getLogger(".widgets.shortlistcomboentry") _LOG = logging.getLogger(".widgets.shortlistcomboentry")
@ -52,20 +51,11 @@ from .validatedcomboentry import ValidatedComboEntry
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
if sys.version_info[0] < 3: _GTYPE = {
_GTYPE = { str: GObject.TYPE_STRING,
str: GObject.TYPE_STRING, int: GObject.TYPE_INT64,
unicode: GObject.TYPE_STRING, float: GObject.TYPE_FLOAT,
int: GObject.TYPE_INT, }
long: GObject.TYPE_INT64,
float: GObject.TYPE_FLOAT,
}
else:
_GTYPE = {
str: GObject.TYPE_STRING,
int: GObject.TYPE_INT64,
float: GObject.TYPE_FLOAT,
}
(COLUMN_ITEM, (COLUMN_ITEM,
COLUMN_IS_SEP,) = list(range(2)) COLUMN_IS_SEP,) = list(range(2))

@ -139,12 +139,8 @@ class FadeOut(GObject.GObject):
##_LOG.debug('_start_merging: Starting') ##_LOG.debug('_start_merging: Starting')
generator = self._merge_colors(self._start_color, generator = self._merge_colors(self._start_color,
Gdk.color_parse(self.ERROR_COLOR)) Gdk.color_parse(self.ERROR_COLOR))
if sys.version_info[0] < 3:
func = generator.next
else:
func = generator.__next__
self._background_timeout_id = ( self._background_timeout_id = (
GLib.timeout_add(FadeOut.MERGE_COLORS_DELAY, func)) GLib.timeout_add(FadeOut.MERGE_COLORS_DELAY, generator.__next__))
self._countdown_timeout_id = -1 self._countdown_timeout_id = -1
def start(self, color): def start(self, color):
@ -204,20 +200,12 @@ INPUT_FORMATS = {
# ? - Ascii letter, optional # ? - Ascii letter, optional
# C - Alpha, optional # C - Alpha, optional
if sys.version_info[0] < 3: INPUT_CHAR_MAP = {
INPUT_CHAR_MAP = { INPUT_ASCII_LETTER: lambda text: text in string.ascii_letters,
INPUT_ASCII_LETTER: lambda text: text in string.ascii_letters, INPUT_ALPHA: str.isalpha,
INPUT_ALPHA: unicode.isalpha, INPUT_ALPHANUMERIC: str.isalnum,
INPUT_ALPHANUMERIC: unicode.isalnum, INPUT_DIGIT: str.isdigit,
INPUT_DIGIT: unicode.isdigit, }
}
else:
INPUT_CHAR_MAP = {
INPUT_ASCII_LETTER: lambda text: text in string.ascii_letters,
INPUT_ALPHA: str.isalpha,
INPUT_ALPHANUMERIC: str.isalnum,
INPUT_DIGIT: str.isdigit,
}
(COL_TEXT, (COL_TEXT,
COL_OBJECT) = list(range(2)) COL_OBJECT) = list(range(2))

@ -68,11 +68,7 @@ except ImportError:
from md5 import md5 from md5 import md5
import zipfile import zipfile
import time import time
import sys from io import StringIO
if sys.version_info[0] < 3:
from cStringIO import StringIO
else:
from io import StringIO
from math import pi, cos, sin, degrees, radians from math import pi, cos, sin, degrees, radians
from xml.sax.saxutils import escape from xml.sax.saxutils import escape
@ -1018,8 +1014,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc):
not_extension, extension = os.path.splitext(file_name) not_extension, extension = os.path.splitext(file_name)
file_name_hash = file_name file_name_hash = file_name
if sys.version_info[0] >= 3: file_name_hash = file_name_hash.encode('utf-8')
file_name_hash = file_name_hash.encode('utf-8')
odf_name = md5(file_name_hash).hexdigest() + extension odf_name = md5(file_name_hash).hexdigest() + extension
media_list_item = (file_name, odf_name) media_list_item = (file_name, odf_name)
@ -1186,8 +1181,6 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc):
""" """
Add a zip file to an archive Add a zip file to an archive
""" """
if sys.version_info[0] < 3:
name = name.encode('utf-8')
zipinfo = zipfile.ZipInfo(name) zipinfo = zipfile.ZipInfo(name)
zipinfo.date_time = t zipinfo.date_time = t
zipinfo.compress_type = zipfile.ZIP_DEFLATED zipinfo.compress_type = zipfile.ZIP_DEFLATED

@ -30,11 +30,7 @@ SVG document generator.
# python modules # python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import sys from io import StringIO
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -31,14 +31,10 @@
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext _ = glocale.translation.sgettext
import csv import csv
if sys.version_info[0] < 3: from io import StringIO
from cStringIO import StringIO
else:
from io import StringIO
import codecs import codecs
#------------------------------------------------------------------------ #------------------------------------------------------------------------
@ -155,15 +151,8 @@ class UnicodeWriter(object):
self.encoder = codecs.getencoder(encoding) self.encoder = codecs.getencoder(encoding)
def writerow(self, row): def writerow(self, row):
if sys.version_info[0] < 3: self.writer.writerow(row)
self.writer.writerow([s.encode('utf-8') for s in row]) data = self.queue.getvalue()
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode('utf-8')
else:
self.writer.writerow(row)
data = self.queue.getvalue()
#in python3, StringIO self.queue returns unicode!
#data now contains the csv data in unicode #data now contains the csv data in unicode
# ... and reencode it into the target encoding # ... and reencode it into the target encoding
data, length = self.encoder(data) data, length = self.encoder(data)

@ -32,12 +32,8 @@
import time import time
import shutil import shutil
import os import os
import sys
import tarfile import tarfile
if sys.version_info[0] < 3: from io import StringIO, BytesIO
from cStringIO import StringIO
else:
from io import StringIO, BytesIO
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
@ -213,10 +209,7 @@ class PackageWriter(object):
# select_clicked() # select_clicked()
# Write XML now # Write XML now
if sys.version_info[0] < 3: g = BytesIO()
g = StringIO()
else:
g = BytesIO()
gfile = XmlWriter(self.db, self.user, 2) gfile = XmlWriter(self.db, self.user, 2)
gfile.write_handle(g) gfile.write_handle(g)
tarinfo = tarfile.TarInfo('data.gramps') tarinfo = tarfile.TarInfo('data.gramps')

@ -29,10 +29,7 @@ Provide a python evaluation window
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import sys import sys
if sys.version_info[0] < 3: from io import StringIO
from cStringIO import StringIO
else:
from io import StringIO
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import traceback import traceback

@ -29,14 +29,9 @@ Show uncollected objects in a window.
# standard python modules # standard python modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import sys
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
from gramps.gen.config import config from bsddb3.db import DBError
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
from bsddb3.db import DBError
else:
from bsddb.db import DBError
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #

@ -21,13 +21,6 @@
"Import from GEDCOM" "Import from GEDCOM"
#------------------------------------------------------------------------
#
# python modules
#
#------------------------------------------------------------------------
import sys
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# Set up logging # Set up logging
@ -53,11 +46,8 @@ from gramps.plugins.lib import libgedcom
# a quick turnround, without having to restart Gramps. # a quick turnround, without having to restart Gramps.
module = __import__("gramps.plugins.lib.libgedcom", module = __import__("gramps.plugins.lib.libgedcom",
fromlist=["gramps.plugins.lib"]) # why o why ?? as above! fromlist=["gramps.plugins.lib"]) # why o why ?? as above!
if sys.version_info[0] < 3: import imp
reload (module) imp.reload(module)
else:
import imp
imp.reload(module)
from gramps.gen.config import config from gramps.gen.config import config
from gramps.gen.constfunc import STRTYPE from gramps.gen.constfunc import STRTYPE
@ -108,10 +98,7 @@ def importData(database, filename, user):
assert(isinstance(code_set, STRTYPE)) assert(isinstance(code_set, STRTYPE))
try: try:
if sys.version_info[0] < 3: ifile = open(filename, "rb")
ifile = open(filename, "rU")
else:
ifile = open(filename, "rb")
stage_one = libgedcom.GedcomStageOne(ifile) stage_one = libgedcom.GedcomStageOne(ifile)
stage_one.parse() stage_one.parse()

@ -29,7 +29,6 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import re import re
import time import time
import sys
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@ -54,14 +53,7 @@ from gramps.gen.lib import (Attribute, AttributeType, ChildRef, Citation,
Place, Source) Place, Source)
from gramps.gen.db import DbTxn from gramps.gen.db import DbTxn
from gramps.gen.constfunc import STRTYPE, cuni, conv_to_unicode from gramps.gen.constfunc import STRTYPE, cuni, conv_to_unicode
if sys.version_info[0] < 3: from html.entities import name2codepoint
from htmlentitydefs import name2codepoint
else:
from html.entities import name2codepoint
if sys.version_info[0] < 3:
unich = lambda x: unichr(x)
else:
unich = lambda x: chr(x)
_date_parse = re.compile('([kmes~?<>]+)?([0-9/]+)([J|H|F])?(\.\.)?([0-9/]+)?([J|H|F])?') _date_parse = re.compile('([kmes~?<>]+)?([0-9/]+)([J|H|F])?(\.\.)?([0-9/]+)?([J|H|F])?')
_text_parse = re.compile('0\((.*)\)') _text_parse = re.compile('0\((.*)\)')
@ -906,9 +898,9 @@ class GeneWebParser(object):
for match in charref_re.finditer(s): for match in charref_re.finditer(s):
try: try:
if match.group(2): # HEX if match.group(2): # HEX
nchar = unich(int(match.group(3),16)) nchar = chr(int(match.group(3),16))
else: # Decimal else: # Decimal
nchar = unich(int(match.group(3))) nchar = chr(int(match.group(3)))
s = s.replace(match.group(0), nchar) s = s.replace(match.group(0), nchar)
except UnicodeDecodeError: except UnicodeDecodeError:
pass pass
@ -918,7 +910,7 @@ class GeneWebParser(object):
for match in entref_re.finditer(s): for match in entref_re.finditer(s):
try: try:
if match.group(2) in name2codepoint: if match.group(2) in name2codepoint:
nchar = unich(name2codepoint[match.group(2)]) nchar = chr(name2codepoint[match.group(2)])
s = s.replace(match.group(0), nchar) s = s.replace(match.group(0), nchar)
except UnicodeDecodeError: except UnicodeDecodeError:
pass pass

@ -380,21 +380,18 @@ class LineParser(object):
try: try:
if use_gzip: if use_gzip:
if sys.version_info[0] == 2: import io
ofile = gzip.open(filename, "rb") # Bug 6255. TextIOWrapper is required for python3 to
else: # present file contents as text, otherwise they
import io # are read as binary. However due to a missing
# Bug 6255. TextIOWrapper is required for python3 to # method (read1) in early python3 versions this
# present file contents as text, otherwise they # try block will fail.
# are read as binary. However due to a missing # Gramps will still import XML files using python
# method (read1) in early python3 versions this # versions < 3.3.0 but the file progress meter
# try block will fail. # will not work properly, going immediately to
# Gramps will still import XML files using python # 100%.
# versions < 3.3.0 but the file progress meter # It should work correctly from version 3.3.
# will not work properly, going immediately to ofile = io.TextIOWrapper(gzip.open(filename, "rb"))
# 100%.
# It should work correctly from version 3.3.
ofile = io.TextIOWrapper(gzip.open(filename, "rb"))
else: else:
ofile = open(filename, "r") ofile = open(filename, "r")
@ -465,10 +462,7 @@ class ImportOpenFileContextManager:
if use_gzip: if use_gzip:
xml_file = gzip.open(filename, "rb") xml_file = gzip.open(filename, "rb")
else: else:
if sys.version_info[0] < 3: xml_file = open(filename, "rb")
xml_file = open(filename, "r")
else:
xml_file = open(filename, "rb")
except IOError as msg: except IOError as msg:
self.user.notify_error(_("%s could not be opened") % filename, str(msg)) self.user.notify_error(_("%s could not be opened") % filename, str(msg))
xml_file = None xml_file = None

@ -88,21 +88,14 @@ all lines until the next level 2 token is found (in this case, skipping the
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys
import re import re
import time import time
import codecs import codecs
from xml.parsers.expat import ParserCreate from xml.parsers.expat import ParserCreate
from collections import defaultdict from collections import defaultdict
import string import string
if sys.version_info[0] < 3: from io import StringIO
from cStringIO import StringIO from urllib.parse import urlparse
else:
from io import StringIO
if sys.version_info[0] < 3:
from urlparse import urlparse
else:
from urllib.parse import urlparse
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@ -143,11 +136,6 @@ from gramps.gen.constfunc import cuni, conv_to_unicode, STRTYPE, UNITYPE, win
from gramps.plugins.lib.libplaceimport import PlaceImport from gramps.plugins.lib.libplaceimport import PlaceImport
from gramps.gen.display.place import displayer as place_displayer from gramps.gen.display.place import displayer as place_displayer
# string.whitespace in some configuration is changed if it is imported
# after setting locale (adding '0xa0')
if win() and sys.version_info[0] < 3:
string.whitespace = ' \t\n\r\v\f'
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# constants # constants
@ -1123,18 +1111,11 @@ class GedcomInfoDB(object):
self.standard = GedcomDescription("GEDCOM 5.5 standard") self.standard = GedcomDescription("GEDCOM 5.5 standard")
self.standard.set_dest("GEDCOM 5.5") self.standard.set_dest("GEDCOM 5.5")
if sys.version_info[0] < 3: try:
try: filepath = os.path.join(DATA_DIR, "gedcom.xml")
filepath = os.path.join(DATA_DIR, "gedcom.xml") ged_file = open(filepath, "rb")
ged_file = open(filepath.encode('iso8859-1'), "r") except:
except: return
return
else:
try:
filepath = os.path.join(DATA_DIR, "gedcom.xml")
ged_file = open(filepath, "rb")
except:
return
parser = GedInfoParser(self) parser = GedInfoParser(self)
parser.parse(ged_file) parser.parse(ged_file)
@ -1240,13 +1221,8 @@ class BaseReader(object):
self.ifile.seek(0) self.ifile.seek(0)
def readline(self): def readline(self):
if sys.version_info[0] < 3: line = self.ifile.readline()
line = unicode(self.ifile.readline(), line = line.decode(self.enc, errors='replace')
encoding=self.enc,
errors='replace')
else:
line = self.ifile.readline()
line = line.decode(self.enc, errors='replace')
return line.translate(STRIP_DICT) return line.translate(STRIP_DICT)
class UTF8Reader(BaseReader): class UTF8Reader(BaseReader):
@ -1263,12 +1239,7 @@ class UTF8Reader(BaseReader):
def readline(self): def readline(self):
line = self.ifile.readline() line = self.ifile.readline()
if sys.version_info[0] < 3: line = line.decode(self.enc, errors='replace')
line = unicode(line,
encoding=self.enc,
errors='replace')
else:
line = line.decode(self.enc, errors='replace')
return line.translate(STRIP_DICT) return line.translate(STRIP_DICT)
class UTF16Reader(BaseReader): class UTF16Reader(BaseReader):
@ -1539,10 +1510,7 @@ class AnselReader(BaseReader):
head = '\ufffd' # "Replacement Char" head = '\ufffd' # "Replacement Char"
s = s[1:] s = s[1:]
buff.write(head.encode("utf-8")) buff.write(head.encode("utf-8"))
if sys.version_info[0] < 3: ans = buff.getvalue().decode("utf-8")
ans = unicode(buff.getvalue(), "utf-8")
else:
ans = buff.getvalue().decode("utf-8")
buff.close() buff.close()
return ans return ans

@ -27,7 +27,6 @@ from xml.parsers import expat
import datetime import datetime
import math import math
import os import os
import sys
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@ -325,10 +324,7 @@ class _Xml2Obj:
parser.StartElementHandler = self.start_element parser.StartElementHandler = self.start_element
parser.EndElementHandler = self.end_element parser.EndElementHandler = self.end_element
# Parse the XML File # Parse the XML File
if sys.version_info[0] < 3: parser.Parse(open(filename, 'rb').read(), 1)
parser.Parse(open(filename, 'r').read(), 1)
else:
parser.Parse(open(filename, 'rb').read(), 1)
return self.root return self.root
#------------------------------------------------------------------------ #------------------------------------------------------------------------

@ -30,11 +30,7 @@
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys from io import StringIO
if sys.version_info[0] < 3:
from cStringIO import StringIO
else:
from io import StringIO
import time import time
from collections import defaultdict from collections import defaultdict

@ -20,16 +20,9 @@
"Download a GEDCOM file from a phpGedView server" "Download a GEDCOM file from a phpGedView server"
import sys import http.client as hcl
if sys.version_info[0] < 3: from urllib.request import Request, urlopen
import httplib as hcl from urllib.error import URLError
else:
import http.client as hcl
if sys.version_info[0] < 3:
from urllib2 import URLError, urlopen, Request
else:
from urllib.request import Request, urlopen
from urllib.error import URLError
from gi.repository import Gtk from gi.repository import Gtk
import os import os
from tempfile import mkstemp from tempfile import mkstemp

@ -33,11 +33,7 @@ This is the research tool, not the low-level data ingerity check.
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import os import os
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
try: try:
from hashlib import md5 from hashlib import md5
except ImportError: except ImportError:
@ -548,7 +544,7 @@ class VerifyResults(ManagedWindow):
pass pass
def load_ignored(self, db_filename): def load_ignored(self, db_filename):
if sys.version_info[0] >= 3 and isinstance(db_filename, UNITYPE): if isinstance(db_filename, UNITYPE):
db_filename = db_filename.encode('utf-8') db_filename = db_filename.encode('utf-8')
md5sum = md5(db_filename) md5sum = md5(db_filename)
## a new Gramps major version means recreating the .vfm file. ## a new Gramps major version means recreating the .vfm file.

@ -31,11 +31,7 @@ Can use the Webkit or Gecko ( Mozilla ) library
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys from urllib.parse import urlunsplit
if sys.version_info[0] < 3:
from urlparse import urlunsplit
else:
from urllib.parse import urlunsplit
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -32,17 +32,10 @@ Media View.
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import os import os
import sys from urllib.parse import urlparse
if sys.version_info[0] < 3: from urllib.request import url2pathname
from urlparse import urlparse import pickle
from urllib2 import url2pathname
else:
from urllib.parse import urlparse
from urllib.request import url2pathname
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# GTK/Gnome modules # GTK/Gnome modules

@ -29,12 +29,8 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from cgi import escape from cgi import escape
import math import math
import sys
import os import os
if sys.version_info[0] < 3: import pickle
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -31,12 +31,7 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext _ = glocale.translation.sgettext
ngettext = glocale.translation.ngettext # else "nearby" comments are ignored ngettext = glocale.translation.ngettext # else "nearby" comments are ignored
import cgi import cgi
import pickle
import sys
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #

@ -80,10 +80,7 @@ import shutil
import codecs import codecs
import tarfile import tarfile
import tempfile import tempfile
if sys.version_info[0] < 3: from io import StringIO, BytesIO, TextIOWrapper
from cStringIO import StringIO
else:
from io import StringIO, BytesIO, TextIOWrapper
from textwrap import TextWrapper from textwrap import TextWrapper
from unicodedata import normalize from unicodedata import normalize
from collections import defaultdict from collections import defaultdict
@ -7867,14 +7864,9 @@ class NavWebReport(Report):
else: else:
self.cur_fname = fname + ext self.cur_fname = fname + ext
if self.archive: if self.archive:
if sys.version_info[0] < 3: string_io = BytesIO()
string_io = StringIO() of = TextIOWrapper(string_io, encoding=self.encoding,
of = codecs.EncodedFile(string_io, 'utf-8', self.encoding, errors='xmlcharrefreplace')
'xmlcharrefreplace')
else:
string_io = BytesIO()
of = TextIOWrapper(string_io, encoding=self.encoding,
errors='xmlcharrefreplace')
else: else:
string_io = None string_io = None
if subdir: if subdir:
@ -7882,22 +7874,8 @@ class NavWebReport(Report):
if not os.path.isdir(subdir): if not os.path.isdir(subdir):
os.makedirs(subdir) os.makedirs(subdir)
fname = os.path.join(self.html_dir, self.cur_fname) fname = os.path.join(self.html_dir, self.cur_fname)
if sys.version_info[0] < 3: of = open(fname, 'w', encoding=self.encoding,
# In python 2.x, the data written by of.write() is genarally of errors='xmlcharrefreplace')
# type 'str' (i.e. 8-bit strings), except for cases where (at
# least) one of the objects being converted by a '%' operator is
# unicode (e.g. the "Generated by" line or the _META3 line), in
# which case the data being written is of type 'unicode' (See
# http://docs.python.org/2/library/stdtypes.html#string-
# formatting). The data written to the file is encoded according
# to self.encoding
of = codecs.EncodedFile(open(fname, 'w'), 'utf-8',
self.encoding, 'xmlcharrefreplace')
else:
# In python 3, the data that is written by of.write() is always
# of type 'str' (i.e. unicode text).
of = open(fname, 'w', encoding=self.encoding,
errors='xmlcharrefreplace')
return (of, string_io) return (of, string_io)
def close_file(self, of, string_io): def close_file(self, of, string_io):
@ -7906,8 +7884,7 @@ class NavWebReport(Report):
""" """
if self.archive: if self.archive:
if sys.version_info[0] >= 3: of.flush()
of.flush()
tarinfo = tarfile.TarInfo(self.cur_fname) tarinfo = tarfile.TarInfo(self.cur_fname)
tarinfo.size = len(string_io.getvalue()) tarinfo.size = len(string_io.getvalue())
tarinfo.mtime = time.time() tarinfo.mtime = time.time()

@ -373,22 +373,8 @@ class WebCalReport(Report):
if not os.path.isdir(destdir): if not os.path.isdir(destdir):
os.makedirs(destdir) os.makedirs(destdir)
if sys.version_info[0] < 3: of = open(fname, 'w', encoding=self.encoding,
# In python 2.x, the data written by of.write() is genarally of errors='xmlcharrefreplace')
# type 'str' (i.e. 8-bit strings), except for cases where (at
# least) one of the objects being converted by a '%' operator is
# unicode (e.g. the "Generated by" line or the _META3 line), in
# which case the data being written is of type 'unicode' (See
# http://docs.python.org/2/library/stdtypes.html#string-
# formatting). The data written to the file is encoded according
# to self.encoding
of = codecs.EncodedFile(open(fname, 'w'), 'utf-8',
self.encoding, 'xmlcharrefreplace')
else:
# In python 3, the data that is written by of.write() is always
# of type 'str' (i.e. unicode text).
of = open(fname, 'w', encoding=self.encoding,
errors='xmlcharrefreplace')
return of return of
def close_file(self, of): def close_file(self, of):
@ -1740,10 +1726,7 @@ def get_day_list(event_date, holiday_list, bday_anniv_list):
# sort them based on number of years # sort them based on number of years
# holidays will always be on top of event list # holidays will always be on top of event list
if sys.version_info[0] < 3: day_list= sorted(day_list, key=lambda x: (isinstance(x[0], str), x[0]))
day_list.sort()
else:
day_list= sorted(day_list, key=lambda x: (isinstance(x[0], str), x[0]))
# return to its caller calendar_build() # return to its caller calendar_build()
return day_list return day_list

@ -17,15 +17,9 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# #
import sys from urllib.request import (Request, urlopen, HTTPCookieProcessor,
if sys.version_info[0] < 3: build_opener, install_opener)
from urllib2 import (urlopen, Request, HTTPCookieProcessor, from urllib.parse import urlencode
build_opener, install_opener)
from urllib import urlencode
else:
from urllib.request import (Request, urlopen, HTTPCookieProcessor,
build_opener, install_opener)
from urllib.parse import urlencode
class Connection(object): class Connection(object):
""" """

@ -34,11 +34,7 @@ from gramps.gen.utils.id import create_id, create_uid
from gramps.webapp.grampsdb.profile import Profile from gramps.webapp.grampsdb.profile import Profile
from gramps.gen.constfunc import cuni from gramps.gen.constfunc import cuni
import sys import pickle
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import base64 import base64
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------

@ -1897,12 +1897,8 @@ class Reader:
arraycode = 'BH'[self.bitdepth>8] arraycode = 'BH'[self.bitdepth>8]
# Like :meth:`group` but producing an array.array object for # Like :meth:`group` but producing an array.array object for
# each row. # each row.
if sys.version_info[0] < 3: pixels = map(lambda *row: array(arraycode, row),
pixels = itertools.imap(lambda *row: array(arraycode, row), *[iter(self.deinterlace(raw))]*self.width*self.planes)
*[iter(self.deinterlace(raw))]*self.width*self.planes)
else:
pixels = map(lambda *row: array(arraycode, row),
*[iter(self.deinterlace(raw))]*self.width*self.planes)
else: else:
pixels = self.iterboxed(self.iterstraight(raw)) pixels = self.iterboxed(self.iterstraight(raw))
meta = dict() meta = dict()

@ -29,12 +29,8 @@ Each object can be operated on with the following actions:
""" """
import os import os
import sys
import time import time
if sys.version_info[0] < 3: import pickle
import cPickle as pickle
else:
import pickle
import base64 import base64
#------------------------------------------------------------------------ #------------------------------------------------------------------------

@ -26,10 +26,7 @@
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import time import time
import sys import sys
if sys.version_info[0] < 3: import pickle
import cPickle as pickle
else:
import pickle
import base64 import base64
import collections import collections

@ -28,7 +28,6 @@ from gramps.gen.plug import BasePluginManager
from gramps.cli.user import User as GUser # gramps user from gramps.cli.user import User as GUser # gramps user
import os import os
import sys
# Example for running a report: # Example for running a report:
# ------------------------------ # ------------------------------
@ -93,12 +92,8 @@ def import_file(db, filename, user):
return False return False
def download(url, filename=None): def download(url, filename=None):
if sys.version_info[0] < 3: from urllib.request import Request, urlopen
from urllib2 import urlopen, Request from urllib.parse import urlsplit
from urlparse import urlsplit
else:
from urllib.request import Request, urlopen
from urllib.parse import urlsplit
import shutil import shutil
def getFilename(url,openUrl): def getFilename(url,openUrl):
if 'Content-Disposition' in openUrl.info(): if 'Content-Disposition' in openUrl.info():

@ -27,10 +27,7 @@
import sys import sys
import re import re
import datetime import datetime
if sys.version_info[0] < 3: from html.parser import HTMLParser
from HTMLParser import HTMLParser
else:
from html.parser import HTMLParser
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #