Skip to content

Commit

Permalink
Port to Python 3
Browse files Browse the repository at this point in the history
* remove call to sys.setdefaultencoding
  default encoding is 'utf-8' by default in Python 3

* remove use of statvfs
  statvfs does not exist in python 3

* TODO was fixed in af6ce2e

* Remove unused function

* flake fixes

* Fix unicode encoding error

* Use a list to iterate over, supporting Python 3

* Encode 'str' instance into 'utf-8'

Co-authored-by: Aniket21mathur <[email protected]>
  • Loading branch information
2 people authored and quozl committed Aug 13, 2019
1 parent 1f96fad commit aa18879
Show file tree
Hide file tree
Showing 84 changed files with 284 additions and 296 deletions.
2 changes: 1 addition & 1 deletion Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ lint:

test: lint check-po
PYTHONPATH=$(pkgdatadir)/extensions:$(PYTHONPATH) \
python -m sugar3.test.discover $(top_srcdir)/tests
python3 -m sugar3.test.discover $(top_srcdir)/tests
4 changes: 2 additions & 2 deletions bin/sugar-backlight-setup
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3

# Copyright (C) 2015 Martin Abente Lahaye <[email protected]>
#
Expand Down Expand Up @@ -60,7 +60,7 @@ def _main():
try:
SugarBacklightSetup()
except Exception as err:
print 'Could not create device link: %s' % str(err)
print('Could not create device link: %s' % str(err))
sys.exit(1)

if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion bin/sugar-control-panel
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
# Copyright (C) 2008, Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
Expand Down
8 changes: 4 additions & 4 deletions bin/sugar-erase-bundle
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
import os
import sys

Expand All @@ -8,8 +8,8 @@ DBusGMainLoop(set_as_default=True)
from jarabe.model import bundleregistry

def cmd_help():
print 'Usage: sugar-erase-bundle bundle_id [...] \n\n\
Erase activity bundles\n'
print('Usage: sugar-erase-bundle bundle_id [...] \n\n\
Erase activity bundles\n')

if len(sys.argv) < 2:
cmd_help()
Expand All @@ -19,7 +19,7 @@ for name in sys.argv[1:]:
registry = bundleregistry.get_registry()
bundle = registry.get_bundle(name)
if not bundle:
print 'Cannot find %s bundle.' % name
print('Cannot find %s bundle.' % name)
continue

registry.uninstall(bundle, delete_profile=True)
8 changes: 4 additions & 4 deletions bin/sugar-install-bundle
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
import os
import sys

Expand All @@ -9,8 +9,8 @@ DBusGMainLoop(set_as_default=True)


def cmd_help():
print 'Usage: sugar-install-bundle activitybundle.xo [...] \n\n\
Install activity bundles\n'
print('Usage: sugar-install-bundle activitybundle.xo [...] \n\n\
Install activity bundles\n')

if len(sys.argv) < 2:
cmd_help()
Expand All @@ -24,4 +24,4 @@ for name in sys.argv[1:]:
# by triggering a GFileMonitor ATTRIBUTE_CHANGED event.
os.utime(path, None)

print "%s: '%s' installed." % (sys.argv[0], name)
print("%s: '%s' installed." % (sys.argv[0], name))
6 changes: 3 additions & 3 deletions bin/sugar-launch
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3

# Copyright (C) 2007, Red Hat, Inc.
#
Expand Down Expand Up @@ -35,12 +35,12 @@ parser.add_argument("-u", "--uri",
help='URI to load')

args = parser.parse_args()
print args.bundle_id
print(args.bundle_id)
bus = dbus.SessionBus()
proxy = bus.get_object('org.laptop.Shell', '/org/laptop/Shell')
path = dbus.Interface(proxy, 'org.laptop.Shell').GetBundlePath(args.bundle_id)
if not path:
print 'Cannot find %s bundle.' % args.bundle_id
print('Cannot find %s bundle.' % args.bundle_id)
sys.exit(1)

activity = ActivityBundle(path)
Expand Down
2 changes: 1 addition & 1 deletion bin/sugar.in
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,4 @@ cat > "$debug_file_path" << EOF
EOF
fi

exec python2 -m jarabe.main
exec python3 -m jarabe.main
2 changes: 1 addition & 1 deletion configure.ac
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ AM_INIT_AUTOMAKE([1.9 foreign dist-xz no-dist-gzip])

AM_MAINTAINER_MODE

PYTHON=python2
PYTHON=python3
AM_PATH_PYTHON

AC_PATH_PROG([EMPY], [empy])
Expand Down
18 changes: 9 additions & 9 deletions extensions/cpsection/aboutcomputer/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def get_aboutcomputer():


def print_aboutcomputer():
print get_aboutcomputer()
print(get_aboutcomputer())


def _get_serial_number():
Expand Down Expand Up @@ -74,7 +74,7 @@ def print_serial_number():
serial_no = get_serial_number()
if serial_no is None:
serial_no = _not_available
print serial_no
print(serial_no)


def get_build_number():
Expand All @@ -87,12 +87,12 @@ def get_build_number():
try:
popen = subprocess.Popen(['lsb_release', '-ds'],
stdout=subprocess.PIPE)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
else:
build_no, stderr_ = popen.communicate()
build_no = build_no.strip()
build_no = build_no.strip().decode()

if build_no is None or not build_no:
build_no = _not_available
Expand All @@ -101,7 +101,7 @@ def get_build_number():


def print_build_number():
print get_build_number()
print(get_build_number())


def get_firmware_number():
Expand Down Expand Up @@ -154,7 +154,7 @@ def get_secondary_licenses():


def print_firmware_number():
print get_firmware_number()
print(get_firmware_number())


def get_wireless_firmware():
Expand Down Expand Up @@ -206,15 +206,15 @@ def get_wireless_firmware():
return _not_available

if len(firmware_info) == 1:
return firmware_info.values()[0]
return list(firmware_info.values())[0]

return ', '.join(['%(interface)s: %(info)s' %
{'interface': interface, 'info': info}
for interface, info in firmware_info.items()])
for interface, info in list(firmware_info.items())])


def print_wireless_firmware():
print get_wireless_firmware()
print(get_wireless_firmware())


def _read_file(path):
Expand Down
20 changes: 10 additions & 10 deletions extensions/cpsection/aboutme/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def get_nick():


def print_nick():
print get_nick()
print(get_nick())


def set_nick(nick):
Expand All @@ -48,8 +48,8 @@ def set_nick(nick):
"""
if not nick:
raise ValueError(_('You must enter a name.'))
if not isinstance(nick, unicode):
nick = unicode(nick, 'utf-8')
if not isinstance(nick, str):
nick = str(nick, 'utf-8')
settings = Gio.Settings('org.sugarlabs.user')
settings.set_string('nick', nick)
return 1
Expand All @@ -74,14 +74,14 @@ def print_color():
fill_tuple = (color, hue)

if stroke_tuple is not None:
print ('stroke: color=%s hue=%s') % (stroke_tuple[0],
stroke_tuple[1])
print(('stroke: color=%s hue=%s') % (stroke_tuple[0],
stroke_tuple[1]))
else:
print ('stroke: %s') % (tmp[0])
print(('stroke: %s') % (tmp[0]))
if fill_tuple is not None:
print ('fill: color=%s hue=%s') % (fill_tuple[0], fill_tuple[1])
print(('fill: color=%s hue=%s') % (fill_tuple[0], fill_tuple[1]))
else:
print ('fill: %s') % (tmp[1])
print(('fill: %s') % (tmp[1]))


def set_color(stroke, fill, stroke_modifier='medium', fill_modifier='medium'):
Expand All @@ -93,10 +93,10 @@ def set_color(stroke, fill, stroke_modifier='medium', fill_modifier='medium'):
"""

if stroke_modifier not in _MODIFIERS or fill_modifier not in _MODIFIERS:
print (_('Error in specified color modifiers.'))
print((_('Error in specified color modifiers.')))
return
if stroke not in _COLORS or fill not in _COLORS:
print (_('Error in specified colors.'))
print((_('Error in specified colors.')))
return

if stroke_modifier == fill_modifier:
Expand Down
6 changes: 3 additions & 3 deletions extensions/cpsection/aboutme/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def __init__(self, model, alerts):

self._nick_entry.connect('changed', self.__nick_changed_cb)

for picker in self._pickers.values():
for picker in list(self._pickers.values()):
picker.connect('color-changed', self.__color_changed_cb)

self._gender_pickers.connect('gender-changed',
Expand Down Expand Up @@ -353,7 +353,7 @@ def undo(self):
save_age(self._saved_age)

def _update_pickers(self, color):
for picker in self._pickers.values():
for picker in list(self._pickers.values()):
picker.props.color = color
self._gender_pickers.update_color(color)
self._age_pickers.update_color(color)
Expand Down Expand Up @@ -381,7 +381,7 @@ def __nick_timeout_cb(self, widget):
return False
try:
self._model.set_nick(widget.get_text())
except ValueError, detail:
except ValueError as detail:
self._nick_alert.props.msg = detail
self._nick_valid = False
self._nick_alert.show()
Expand Down
9 changes: 4 additions & 5 deletions extensions/cpsection/backup/backends/volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

import os
import shutil
import statvfs
import tarfile
import logging
from datetime import datetime
Expand All @@ -28,8 +27,8 @@
from sugar3 import profile
from jarabe.journal import model

from backend_tools import Backend, PreConditionsError, PreConditionsChoose
from backend_tools import get_valid_file_name
from .backend_tools import Backend, PreConditionsError, PreConditionsChoose
from .backend_tools import get_valid_file_name

DIR_SIZE = 4096
DS_SOURCE_NAME = 'datastore'
Expand Down Expand Up @@ -209,7 +208,7 @@ def verify_preconditions(self, option=None):
raise PreConditionsError(_('Not enough space in disk'))

def _do_continue(self):
tarinfo = self._tarfile.next()
tarinfo = next(self._tarfile)
if tarinfo is not None:
self._tarfile.extract(tarinfo, path='/')
self._bytes += DIR_SIZE if tarinfo.isdir() else tarinfo.size
Expand Down Expand Up @@ -244,7 +243,7 @@ def cancel(self):

def _get_volume_space(path):
stat = os.statvfs(path)
return stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
return stat[0] * stat[4]


def _get_datastore_size():
Expand Down
4 changes: 2 additions & 2 deletions extensions/cpsection/backup/backupmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(self):
module = _load_module(module_name)
if module is not None:
if hasattr(module, 'get_name'):
logging.error('FOUND BACKEND %s', module.get_name())
logging.debug('FOUND BACKEND %s', module.get_name())
self._backends.append(module)

def get_backends(self):
Expand All @@ -66,7 +66,7 @@ def need_stop_activities(self):
def _load_module(module):
try:
module = import_module('%s.%s' % (BACKENDS_MODULE, module))
except ImportError, e:
except ImportError as e:
module = None
logging.error('ImportError: %s' % (e))
return module
8 changes: 4 additions & 4 deletions extensions/cpsection/backup/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@

from jarabe.controlpanel.sectionview import SectionView

from backupmanager import BackupManager
from backupmanager import OPERATION_BACKUP, OPERATION_RESTORE
from backends.backend_tools import PreConditionsError
from backends.backend_tools import PreConditionsChoose
from .backupmanager import BackupManager
from .backupmanager import OPERATION_BACKUP, OPERATION_RESTORE
from .backends.backend_tools import PreConditionsError
from .backends.backend_tools import PreConditionsChoose


class BackupView(SectionView):
Expand Down
4 changes: 2 additions & 2 deletions extensions/cpsection/datetime/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def read_all_timezones(fn=_zone_tab):
timezones.append(line[2])
timezones.sort()

for offset in xrange(-12, 15):
for offset in range(-12, 15):
if offset < 0:
tz = 'UTC%d' % offset
elif offset > 0:
Expand All @@ -67,7 +67,7 @@ def get_timezone():


def print_timezone():
print get_timezone()
print(get_timezone())


def fix_UTC_time_zone(timezone):
Expand Down
6 changes: 3 additions & 3 deletions extensions/cpsection/frame/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def get_corner_delay():


def print_corner_delay():
print get_corner_delay()
print(get_corner_delay())


def set_corner_delay(delay):
Expand All @@ -44,7 +44,7 @@ def get_edge_delay():


def print_edge_delay():
print get_edge_delay()
print(get_edge_delay())


def set_edge_delay(delay):
Expand All @@ -63,7 +63,7 @@ def get_trigger_size():


def print_trigger_size():
print '{}px'.format(get_trigger_size())
print('{}px'.format(get_trigger_size()))


def set_trigger_size(size):
Expand Down
5 changes: 0 additions & 5 deletions extensions/cpsection/keyboard/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,6 @@

_iso_639_1_to_2 = {}

# TODO: This cpsection adds checks for xklavier in bin/sugar-session and
# src/jarabe/controlpanel/gui.py. We should get rid of these checks
# once python-xklavier has been packaged for all major distributions
# For more information, see: http://dev.sugarlabs.org/ticket/407


def _build_ISO_639_dictionary():
""" The keyboard section of the control panel requires a conversion
Expand Down
Loading

0 comments on commit aa18879

Please sign in to comment.