Remove python2 specific code

This commit is contained in:
Nick Hall 2015-03-14 19:11:09 +00:00
parent 3299deda11
commit e0608f0ec4
96 changed files with 306 additions and 1036 deletions

View File

@ -34,12 +34,8 @@ import os
import sys
import time
import io
if sys.version_info[0] < 3:
from urlparse import urlparse
from urllib2 import urlopen, url2pathname
else:
from urllib.parse import urlparse
from urllib.request import urlopen, url2pathname
from urllib.parse import urlparse
from urllib.request import urlopen, url2pathname
import tempfile
#-------------------------------------------------------------------------
#
@ -142,10 +138,7 @@ class CLIDbManager(object):
current DB.
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
else:
from bsddb import dbshelve, db
from bsddb3 import dbshelve, db
from gramps.gen.db import META, PERSON_TBL
from gramps.gen.db.dbconst import BDBVERSFN

View File

@ -24,7 +24,6 @@ import os
import unittest
import re
import io
import sys
import subprocess
from gramps.gen.constfunc import cuni
@ -41,13 +40,6 @@ test_ged = """0 HEAD
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__)
min1r = os.path.join(ddir, "min1r.ged")
out_ged = os.path.join(ddir, "test_out.ged")
@ -129,9 +121,6 @@ class Test(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):
from gramps.cli.clidbman import CLIDbManager
from gramps.gen.config import set as setconfig, get as getconfig

View File

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

View File

@ -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.
#
#-------------------------------------------------------------------------
# test for sys.frozen to detect a py2exe executable on Windows
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))
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(
conv_to_unicode(__file__)), os.pardir))
sys.path.insert(0, ROOT_DIR)
git_revision = get_git_revision(ROOT_DIR)

View File

@ -51,15 +51,9 @@ WINDOWS = ["Windows", "win32"]
#
#-------------------------------------------------------------------------
#python 2 and 3 support, use correct conversion to unicode
if sys.version_info[0] < 3:
conv_to_unicode_direct = unicode
STRTYPE = basestring
UNITYPE = unicode
else:
conv_to_unicode_direct = str
STRTYPE = str
UNITYPE = str
conv_to_unicode_direct = str
STRTYPE = str
UNITYPE = str
cuni = conv_to_unicode_direct
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)
@ -69,16 +63,10 @@ def uni_to_gui(x):
In Py2 we need to convert strings to utf8 before passing them to
Gtk functions.
'''
if sys.version_info[0] < 3 and isinstance(x, UNITYPE):
return x.encode('utf8')
else:
return x
return x
# handle in database is bytes, while internally Gramps wants unicode for py3
if sys.version_info[0] < 3:
handle2internal = lambda x: x
else:
handle2internal = lambda x: conv_to_unicode(x, 'utf-8')
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:
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]
def get_curr_dir():
@ -203,14 +181,4 @@ def get_curr_dir():
an arbitrary unicode character in a path. This function uses the
native GetCurrentDirectory function to return a unicode cwd.
'''
if not (sys.version_info[0] < 3 and win()):
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
return os.getcwd()

View File

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

View File

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

View File

@ -185,12 +185,7 @@ class BSDDBTxn(object):
# test code
if __name__ == "__main__":
print("1")
from ..config import config
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
from bsddb3 import db, dbshelve
print("2")
x = db.DBEnv()
print("3")

View File

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

View File

@ -23,13 +23,6 @@
Declare constants used by database modules
"""
#-------------------------------------------------------------------------
#
# standard python modules
#
#-------------------------------------------------------------------------
import sys
#-------------------------------------------------------------------------
#
# constants
@ -67,12 +60,8 @@ DBLOCKS = 100000 # Maximum number of locks supported
DBOBJECTS = 100000 # Maximum number of simultaneously locked objects
DBUNDO = 1000 # Maximum size of undo buffer
from ..config import config
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
else:
from bsddb.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
DBFLAGS_O = DB_CREATE | DB_AUTO_COMMIT # Default flags for database open
DBFLAGS_R = DB_RDONLY # Flags to open a database read-only
DBFLAGS_D = DB_DUP | DB_DUPSORT # Default flags for duplicate keys

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -28,17 +28,11 @@ methods to upgrade a database from version 13 to current version
# Standard python modules
#
#-------------------------------------------------------------------------
import sys
import os
import re
import time
import logging
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
from bsddb3 import db
#-------------------------------------------------------------------------
#

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -257,7 +257,7 @@ class BasePluginManager(object):
except ValueError as err:
# Python3 on Windows work with unicode in sys.path
# 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
# only 3rd party plugins
if "gramps" in pdata.fpath:
@ -275,20 +275,8 @@ class BasePluginManager(object):
LOG.warning("Plugin error (from '%s'): %s"
% (pdata.mod_name, err))
except ImportError as err:
# Python2 on Windows not work with unicode in sys.path
# but module can be loaded from current directory
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))
LOG.warning("Plugin error (from '%s'): %s"
% (pdata.mod_name, err))
sys.path.pop(0)
else:
print("WARNING: module cannot be loaded")

View File

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

View File

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

View File

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

View File

@ -25,17 +25,6 @@
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

View File

@ -22,17 +22,6 @@
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

View File

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

View File

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

View File

@ -27,10 +27,7 @@ Provide soundex calculation
# Standard python modules
#
#-------------------------------------------------------------------------
import sys
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"
if sys.version_info[0] < 3:
TABLE = string.maketrans('ABCDEFGIJKLMNOPQRSTUVXYZ',
'012301202245501262301202')
else:
TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
b'012301202245501262301202')
TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ',
b'012301202245501262301202')
from .constfunc import conv_to_unicode_direct
@ -59,14 +52,9 @@ def soundex(strval):
conv_to_unicode_direct(strval.upper().strip())).encode('ASCII', 'ignore')
if not strval:
return "Z000"
if sys.version_info[0] < 3:
strval = strval.encode('iso-8859-1') # Really?
str2 = strval[0]
strval = strval.translate(TABLE, IGNORE)
else:
strval = strval.decode('ASCII', 'ignore')
str2 = strval[0]
strval = strval.translate(TABLE)
strval = strval.decode('ASCII', 'ignore')
str2 = strval[0]
strval = strval.translate(TABLE)
if not strval:
return "Z000"
prev = strval[0]

View File

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

View File

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

View File

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

View File

@ -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
LOG = logging.getLogger(".gramps.gen.utils.grampslocale.mac")
LOG.propagate = True
@ -100,8 +100,7 @@ def mac_setup_localization(glocale):
if not answer:
LOG.debug("No prefs found for %s:%s", domain, key)
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)
return answer
except OSError as err:

View File

@ -28,6 +28,7 @@
import os
import sys
import io
import bsddb3 as bsddb
##import logging
##_LOG = logging.getLogger(".GrampsAboutDialog")
@ -58,12 +59,6 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gramps.gen.constfunc import get_env_var
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
#-------------------------------------------------------------------------
#

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,17 +26,8 @@
# python modules
#
#-------------------------------------------------------------------------
from gramps.gen.config import config
import sys
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
from bsddb3 import db as bsddb_db
import pickle
#-------------------------------------------------------------------------
#

View File

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

View File

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

View File

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

View File

@ -30,12 +30,7 @@ from gi.repository import GdkPixbuf
from gi.repository import GObject
import cairo
import sys, os
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
import bsddb3 as bsddb
#-------------------------------------------------------------------------
#

View File

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

View File

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

View File

@ -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
_ = glocale.translation.gettext
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
from io import StringIO
#------------------------------------------------------------------------
#

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -53,7 +53,6 @@ It keeps a FlatNodeMap, and obtains data from database as needed
#-------------------------------------------------------------------------
import logging
import bisect
import sys
import time
_LOG = logging.getLogger(".gui.basetreemodel")
@ -575,11 +574,8 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel):
# use cursor as a context manager
with self.gen_cursor() as cursor:
#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'))
for key, data in cursor]
else:
srt_keys=[(self.sort_func(data), key) for key, data in cursor]
srt_keys=[(self.sort_func(data), key.decode('utf8'))
for key, data in cursor]
srt_keys.sort()
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.
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:
return # row is already displayed
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
"""
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:
return # row is not currently displayed
self.clear_cache(handle)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -139,12 +139,8 @@ class FadeOut(GObject.GObject):
##_LOG.debug('_start_merging: Starting')
generator = self._merge_colors(self._start_color,
Gdk.color_parse(self.ERROR_COLOR))
if sys.version_info[0] < 3:
func = generator.next
else:
func = generator.__next__
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
def start(self, color):
@ -204,20 +200,12 @@ INPUT_FORMATS = {
# ? - Ascii letter, optional
# C - Alpha, optional
if sys.version_info[0] < 3:
INPUT_CHAR_MAP = {
INPUT_ASCII_LETTER: lambda text: text in string.ascii_letters,
INPUT_ALPHA: unicode.isalpha,
INPUT_ALPHANUMERIC: unicode.isalnum,
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,
}
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_OBJECT) = list(range(2))

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -88,21 +88,14 @@ all lines until the next level 2 token is found (in this case, skipping the
#
#-------------------------------------------------------------------------
import os
import sys
import re
import time
import codecs
from xml.parsers.expat import ParserCreate
from collections import defaultdict
import string
if sys.version_info[0] < 3:
from cStringIO import StringIO
else:
from io import StringIO
if sys.version_info[0] < 3:
from urlparse import urlparse
else:
from urllib.parse import urlparse
from io import StringIO
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.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
@ -1123,18 +1111,11 @@ class GedcomInfoDB(object):
self.standard = GedcomDescription("GEDCOM 5.5 standard")
self.standard.set_dest("GEDCOM 5.5")
if sys.version_info[0] < 3:
try:
filepath = os.path.join(DATA_DIR, "gedcom.xml")
ged_file = open(filepath.encode('iso8859-1'), "r")
except:
return
else:
try:
filepath = os.path.join(DATA_DIR, "gedcom.xml")
ged_file = open(filepath, "rb")
except:
return
try:
filepath = os.path.join(DATA_DIR, "gedcom.xml")
ged_file = open(filepath, "rb")
except:
return
parser = GedInfoParser(self)
parser.parse(ged_file)
@ -1240,13 +1221,8 @@ class BaseReader(object):
self.ifile.seek(0)
def readline(self):
if sys.version_info[0] < 3:
line = unicode(self.ifile.readline(),
encoding=self.enc,
errors='replace')
else:
line = self.ifile.readline()
line = line.decode(self.enc, errors='replace')
line = self.ifile.readline()
line = line.decode(self.enc, errors='replace')
return line.translate(STRIP_DICT)
class UTF8Reader(BaseReader):
@ -1263,12 +1239,7 @@ class UTF8Reader(BaseReader):
def readline(self):
line = self.ifile.readline()
if sys.version_info[0] < 3:
line = unicode(line,
encoding=self.enc,
errors='replace')
else:
line = line.decode(self.enc, errors='replace')
line = line.decode(self.enc, errors='replace')
return line.translate(STRIP_DICT)
class UTF16Reader(BaseReader):
@ -1539,10 +1510,7 @@ class AnselReader(BaseReader):
head = '\ufffd' # "Replacement Char"
s = s[1:]
buff.write(head.encode("utf-8"))
if sys.version_info[0] < 3:
ans = unicode(buff.getvalue(), "utf-8")
else:
ans = buff.getvalue().decode("utf-8")
ans = buff.getvalue().decode("utf-8")
buff.close()
return ans

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -80,10 +80,7 @@ import shutil
import codecs
import tarfile
import tempfile
if sys.version_info[0] < 3:
from cStringIO import StringIO
else:
from io import StringIO, BytesIO, TextIOWrapper
from io import StringIO, BytesIO, TextIOWrapper
from textwrap import TextWrapper
from unicodedata import normalize
from collections import defaultdict
@ -7867,14 +7864,9 @@ class NavWebReport(Report):
else:
self.cur_fname = fname + ext
if self.archive:
if sys.version_info[0] < 3:
string_io = StringIO()
of = codecs.EncodedFile(string_io, 'utf-8', self.encoding,
'xmlcharrefreplace')
else:
string_io = BytesIO()
of = TextIOWrapper(string_io, encoding=self.encoding,
errors='xmlcharrefreplace')
string_io = BytesIO()
of = TextIOWrapper(string_io, encoding=self.encoding,
errors='xmlcharrefreplace')
else:
string_io = None
if subdir:
@ -7882,22 +7874,8 @@ class NavWebReport(Report):
if not os.path.isdir(subdir):
os.makedirs(subdir)
fname = os.path.join(self.html_dir, self.cur_fname)
if sys.version_info[0] < 3:
# In python 2.x, the data written by of.write() is genarally of
# 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')
of = open(fname, 'w', encoding=self.encoding,
errors='xmlcharrefreplace')
return (of, string_io)
def close_file(self, of, string_io):
@ -7906,8 +7884,7 @@ class NavWebReport(Report):
"""
if self.archive:
if sys.version_info[0] >= 3:
of.flush()
of.flush()
tarinfo = tarfile.TarInfo(self.cur_fname)
tarinfo.size = len(string_io.getvalue())
tarinfo.mtime = time.time()

View File

@ -373,22 +373,8 @@ class WebCalReport(Report):
if not os.path.isdir(destdir):
os.makedirs(destdir)
if sys.version_info[0] < 3:
# In python 2.x, the data written by of.write() is genarally of
# 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')
of = open(fname, 'w', encoding=self.encoding,
errors='xmlcharrefreplace')
return 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
# holidays will always be on top of event list
if sys.version_info[0] < 3:
day_list.sort()
else:
day_list= sorted(day_list, key=lambda x: (isinstance(x[0], str), x[0]))
day_list= sorted(day_list, key=lambda x: (isinstance(x[0], str), x[0]))
# return to its caller calendar_build()
return day_list

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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