Commit 4409d6a6 authored by Andreas Tille's avatar Andreas Tille
Browse files

Use 2to3 to port to Python3

parent 6eadd639
Loading
Loading
Loading
Loading
+8 −0
Original line number Diff line number Diff line
cycle (0.3.1-15) UNRELEASED; urgency=medium

  * Team upload.
  * Use 2to3 to port to Python3
    Closes: #939181

 -- Andreas Tille <tille@debian.org>  Fri, 06 Sep 2019 14:57:13 +0200

cycle (0.3.1-14) unstable; urgency=medium

  * Team upload.
+561 −0
Original line number Diff line number Diff line
Description: Use 2to3 to port to Python3
Bug-Debian: https://bugs.debian.org/939181
Author: Andreas Tille <tille@debian.org>
Last-Update: Fri, 06 Sep 2019 14:57:13 +0200

--- a/cal_year.py
+++ b/cal_year.py
@@ -10,6 +10,7 @@ import wx
 import wx.calendar
 import calendar
 import operator
+from functools import reduce
 
 class Val:
     pass
@@ -349,7 +350,7 @@ def min_max(i):
 def calc_fert(year):
     """    year"""
 
-    for k in cycle.mark.keys():
+    for k in list(cycle.mark.keys()):
 	cycle.mark[k]=cycle.mark[k] & ~MARK_FERT &\
 	~MARK_OVUL & ~MARK_PROG & ~MARK_SAFESEX & ~MARK_BIRTH &\
 	~MARK_T22_28 & ~MARK_NEXT_TABLET
@@ -406,7 +407,7 @@ def calc_fert(year):
     cycle.prog_begin=[]
     d=d+wx.DateSpan.Days( cycle.period )
     while d.GetYear()<=year:
-	if cycle.tablet<>[] and cycle.tablet[-1]<=d and \
+	if cycle.tablet!=[] and cycle.tablet[-1]<=d and \
 	    cycle.begin[-1]<=cycle.tablet[-1]: return
 	if d.GetYear()==year: 
 	    #	    cycle.prog_begin.append(d)
@@ -484,7 +485,7 @@ def reset_mark(year):
     for k in cycle.tablet:
 	if k.GetYear()==year:
 	    add_mark(k, MARK_TABLET, year)
-    for k in cycle.note.keys():
+    for k in list(cycle.note.keys()):
 	if str(year)==k[0:4]:
 	    d=wx.DateTimeFromDMY(int(k[6:8]), int(k[4:6])-1, int(k[0:4]))
 	    add_mark(d, MARK_NOTE, year)
@@ -494,7 +495,7 @@ def info(day):
     """     ."""
 
     s=day.Format('%d %B')
-    if cycle.tablet<>[]:
+    if cycle.tablet!=[]:
 	for d in cycle.tablet:
 	    if day.IsBetween(d, d+wx.DateSpan.Days(28)):
 		t=(day-d+wx.TimeSpan.Hours(1)).GetDays()+1
@@ -524,7 +525,7 @@ def info(day):
 	else:
 	    #   
 	    while d<=day:
-		if cycle.tablet<>[] and cycle.tablet[-1]<=d and \
+		if cycle.tablet!=[] and cycle.tablet[-1]<=d and \
 		    cycle.begin[-1]<=cycle.tablet[-1]: return s
 		d=d+wx.DateSpan.Days(cycle.period)
 	    find=2
@@ -568,17 +569,17 @@ def get_note(date):
 
 def remove_note(date):
     d=date.Format('%Y%m%d')
-    if cycle.note.has_key(d):
+    if d in cycle.note:
 	del cycle.note[d]
 
 #-------------------- Report --------------------
 def report_year(year):
     if cycle.first_week_day == 0:
 	calendar.setfirstweekday(calendar.MONDAY)
-	days = range(1,7) + [0]
+	days = list(range(1,7)) + [0]
     else:
 	calendar.setfirstweekday(calendar.SUNDAY)
-	days = range(7)
+	days = list(range(7))
     #sp=' '
     s='<html><body><H3 align=center>%s</H3><pre>' % year
     dn = ''
@@ -620,7 +621,7 @@ def report_year(year):
     
 
     s+='</pre></body></html>'
-    print s
+    print(s)
     return s
 
 def report_year_ical(year, fileobj):
--- a/cycle.py
+++ b/cycle.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/python3
 # coding: koi8-r
 #====================================================
 #	Cycle - calendar for women
@@ -22,13 +22,13 @@ from set_dir import *
 #from prn import *
 
 import gettext
-import __builtin__
+import builtins
 lang_find=False
 if not '__WXMSW__' in wx.PlatformInfo:
     for lang_env_var in ('LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG'):
 	if lang_find:
 	    break
-	if os.environ.has_key(lang_env_var):
+	if lang_env_var in os.environ:
 	    env_language=os.environ[lang_env_var]
 	    for s_lang in env_language.split(':'): # if set more languages
 		os.environ[lang_env_var]=s_lang
@@ -37,9 +37,9 @@ if not '__WXMSW__' in wx.PlatformInfo:
 		    lang=[ dl[0][0:2] ]
 		    l=gettext.translation('cycle', msg_dir, lang)
 		    if wx.USE_UNICODE:
-			__builtin__.__dict__['_'] = lambda s: l.ugettext(s)
+			builtins.__dict__['_'] = lambda s: l.ugettext(s)
 		    else:
-			__builtin__.__dict__['_'] = lambda s: l.ugettext(s).encode(dl[1])
+			builtins.__dict__['_'] = lambda s: l.ugettext(s).encode(dl[1])
 		    _('try decode this string')
 		    lang_find=True
 		    break #language was found
@@ -51,16 +51,16 @@ else: #for MS Windows
         lang=[ dl[0][0:2] ]
 	l=gettext.translation('cycle', msg_dir, lang)
 	if wx.USE_UNICODE:
-	    __builtin__.__dict__['_'] = lambda s: l.ugettext(s)
+	    builtins.__dict__['_'] = lambda s: l.ugettext(s)
 	else:
-	    __builtin__.__dict__['_'] = lambda s: l.ugettext(s).encode(dl[1])
+	    builtins.__dict__['_'] = lambda s: l.ugettext(s).encode(dl[1])
 	_('try decode this string')
 	lang_find=True
     except:
         pass
 
 if not lang_find:
-    __builtin__.__dict__['_'] = lambda s: s
+    builtins.__dict__['_'] = lambda s: s
     lang=[""]
 
 
--- a/dialogs.py
+++ b/dialogs.py
@@ -14,7 +14,7 @@ warnings.filterwarnings("ignore",
 import os
 import wx
 import wx.html
-import cPickle
+import pickle
 from cal_year import cycle , Val
 from save_load import Load_Cycle, get_f_name, set_color_default
 from set_dir import *
@@ -188,8 +188,8 @@ def get_users():
             if tmp == magic_str:
                 tmp=fd.read(100)
                 n=tmp.find("===") #find end string
-                if n <> -1:
-                    users.append((cPickle.loads(tmp[:n]), f))
+                if n != -1:
+                    users.append((pickle.loads(tmp[:n]), f))
                 else: # old format, user_name=file_name
                     users.append((f,f))
         #if not users:
@@ -484,7 +484,7 @@ class Colours_Dlg(wx.Dialog):
 	wx.Dialog.__init__(self,parent,-1, _('Colours settings'))
 
 	self.col_set = cycle.colour_set.copy()
-	self.col_id = cycle.colour_set.keys()
+	self.col_id = list(cycle.colour_set.keys())
 	self.data = wx.ColourData()
 	self.data.SetChooseFull(True)
 	self.buttons = {}
--- a/msg/msgfmt.py
+++ b/msg/msgfmt.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#!/usr/bin/python3
 # -*- coding: iso-8859-1 -*-
 # Written by Martin v. Lwis <loewis@informatik.hu-berlin.de>
 
@@ -38,9 +38,9 @@ MESSAGES = {}
 
 
 def usage(code, msg=''):
-    print >> sys.stderr, __doc__
+    print(__doc__, file=sys.stderr)
     if msg:
-        print >> sys.stderr, msg
+        print(msg, file=sys.stderr)
     sys.exit(code)
 
 
@@ -56,7 +56,7 @@ def add(id, str, fuzzy):
 def generate():
     "Return the generated output."
     global MESSAGES
-    keys = MESSAGES.keys()
+    keys = list(MESSAGES.keys())
     # the keys are sorted in the .mo file
     keys.sort()
     offsets = []
@@ -83,7 +83,7 @@ def generate():
         voffsets += [l2, o2+valuestart]
     offsets = koffsets + voffsets
     output = struct.pack("Iiiiiii",
-                         0x950412deL,       # Magic
+                         0x950412de,       # Magic
                          0,                 # Version
                          len(keys),         # # of entries
                          7*4,               # start of key index
@@ -110,8 +110,8 @@ def make(filename, outfile):
 
     try:
         lines = open(infile).readlines()
-    except IOError, msg:
-        print >> sys.stderr, msg
+    except IOError as msg:
+        print(msg, file=sys.stderr)
         sys.exit(1)
     
     section = None
@@ -154,9 +154,9 @@ def make(filename, outfile):
         elif section == STR:
             msgstr += l
         else:
-            print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
-                  'before:'
-            print >> sys.stderr, l
+            print('Syntax error on %s:%d' % (infile, lno), \
+                  'before:', file=sys.stderr)
+            print(l, file=sys.stderr)
             sys.exit(1)
     # Add last entry
     if section == STR:
@@ -167,8 +167,8 @@ def make(filename, outfile):
 
     try:
         open(outfile,"wb").write(output)
-    except IOError,msg:
-        print >> sys.stderr, msg
+    except IOError as msg:
+        print(msg, file=sys.stderr)
                       
 
 
@@ -176,7 +176,7 @@ def main():
     try:
         opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
                                    ['help', 'version', 'output-file='])
-    except getopt.error, msg:
+    except getopt.error as msg:
         usage(1, msg)
 
     outfile = None
@@ -185,14 +185,14 @@ def main():
         if opt in ('-h', '--help'):
             usage(0)
         elif opt in ('-V', '--version'):
-            print >> sys.stderr, "msgfmt.py", __version__
+            print("msgfmt.py", __version__, file=sys.stderr)
             sys.exit(0)
         elif opt in ('-o', '--output-file'):
             outfile = arg
     # do it
     if not args:
-        print >> sys.stderr, 'No input file given'
-        print >> sys.stderr, "Try `msgfmt --help' for more information."
+        print('No input file given', file=sys.stderr)
+        print("Try `msgfmt --help' for more information.", file=sys.stderr)
         return
 
     for filename in args:
--- a/msg/pygettext.py
+++ b/msg/pygettext.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#!/usr/bin/python3
 # -*- coding: iso-8859-1 -*-
 # Originally written by Barry Warsaw <barry@zope.com>
 #
@@ -164,6 +164,7 @@ import getopt
 import token
 import tokenize
 import operator
+from functools import reduce
 
 __version__ = '1.5'
 
@@ -197,9 +198,9 @@ msgstr ""
 
 
 def usage(code, msg=''):
-    print >> sys.stderr, __doc__ % globals()
+    print(__doc__ % globals(), file=sys.stderr)
     if msg:
-        print >> sys.stderr, msg
+        print(msg, file=sys.stderr)
     sys.exit(code)
 
 
@@ -265,7 +266,7 @@ def containsAny(str, set):
 def _visit_pyfiles(list, dirname, names):
     """Helper for getFilesForName()."""
     # get extension for python source files
-    if not globals().has_key('_py_ext'):
+    if '_py_ext' not in globals():
         global _py_ext
         _py_ext = [triple[0] for triple in imp.get_suffixes()
                    if triple[2] == imp.PY_SOURCE][0]
@@ -423,13 +424,13 @@ class TokenEater:
         elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
                            token.NEWLINE, tokenize.NL]:
             # warn if we see anything else than STRING or whitespace
-            print >> sys.stderr, _(
+            print(_(
                 '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"'
                 ) % {
                 'token': tstring,
                 'file': self.__curfile,
                 'lineno': self.__lineno
-                }
+                }, file=sys.stderr)
             self.__state = self.__waiting
 
     def __addentry(self, msg, lineno=None, isdocstring=0):
@@ -448,15 +449,15 @@ class TokenEater:
         timestamp = time.ctime(time.time())
         # The time stamp in the header doesn't have the same format as that
         # generated by xgettext...
-        print >> fp, pot_header % {'time': timestamp, 'version': __version__}
+        print(pot_header % {'time': timestamp, 'version': __version__}, file=fp)
         # Sort the entries.  First sort each particular entry's keys, then
         # sort all the entries by their first item.
         reverse = {}
-        for k, v in self.__messages.items():
-            keys = v.keys()
+        for k, v in list(self.__messages.items()):
+            keys = list(v.keys())
             keys.sort()
             reverse.setdefault(tuple(keys), []).append((k, v))
-        rkeys = reverse.keys()
+        rkeys = list(reverse.keys())
         rkeys.sort()
         for rkey in rkeys:
             rentries = reverse[rkey]
@@ -466,12 +467,12 @@ class TokenEater:
                 # If the entry was gleaned out of a docstring, then add a
                 # comment stating so.  This is to aid translators who may wish
                 # to skip translating some unimportant docstrings.
-                if reduce(operator.__add__, v.values()):
+                if reduce(operator.__add__, list(v.values())):
                     isdocstring = 1
                 # k is the message string, v is a dictionary-set of (filename,
                 # lineno) tuples.  We want to sort the entries in v first by
                 # file name and then by line number.
-                v = v.keys()
+                v = list(v.keys())
                 v.sort()
                 if not options.writelocations:
                     pass
@@ -479,8 +480,8 @@ class TokenEater:
                 elif options.locationstyle == options.SOLARIS:
                     for filename, lineno in v:
                         d = {'filename': filename, 'lineno': lineno}
-                        print >>fp, _(
-                            '# File: %(filename)s, line: %(lineno)d') % d
+                        print(_(
+                            '# File: %(filename)s, line: %(lineno)d') % d, file=fp)
                 elif options.locationstyle == options.GNU:
                     # fit as many locations on one line, as long as the
                     # resulting line length doesn't exceeds 'options.width'
@@ -491,14 +492,14 @@ class TokenEater:
                         if len(locline) + len(s) <= options.width:
                             locline = locline + s
                         else:
-                            print >> fp, locline
+                            print(locline, file=fp)
                             locline = "#:" + s
                     if len(locline) > 2:
-                        print >> fp, locline
+                        print(locline, file=fp)
                 if isdocstring:
-                    print >> fp, '#, docstring'
-                print >> fp, 'msgid', normalize(k)
-                print >> fp, 'msgstr ""\n'
+                    print('#, docstring', file=fp)
+                print('msgid', normalize(k), file=fp)
+                print('msgstr ""\n', file=fp)
 
 
 
@@ -514,7 +515,7 @@ def main():
              'style=', 'verbose', 'version', 'width=', 'exclude-file=',
              'docstrings', 'no-docstrings',
              ])
-    except getopt.error, msg:
+    except getopt.error as msg:
         usage(1, msg)
 
     # for holding option values
@@ -572,7 +573,7 @@ def main():
         elif opt in ('-v', '--verbose'):
             options.verbose = 1
         elif opt in ('-V', '--version'):
-            print _('pygettext.py (xgettext for Python) %s') % __version__
+            print(_('pygettext.py (xgettext for Python) %s') % __version__)
             sys.exit(0)
         elif opt in ('-w', '--width'):
             try:
@@ -605,8 +606,8 @@ def main():
             options.toexclude = fp.readlines()
             fp.close()
         except IOError:
-            print >> sys.stderr, _(
-                "Can't read --exclude-file: %s") % options.excludefilename
+            print(_(
+                "Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr)
             sys.exit(1)
     else:
         options.toexclude = []
@@ -625,21 +626,21 @@ def main():
     for filename in args:
         if filename == '-':
             if options.verbose:
-                print _('Reading standard input')
+                print(_('Reading standard input'))
             fp = sys.stdin
             closep = 0
         else:
             if options.verbose:
-                print _('Working on %s') % filename
+                print(_('Working on %s') % filename)
             fp = open(filename)
             closep = 1
         try:
             eater.set_filename(filename)
             try:
                 tokenize.tokenize(fp.readline, eater)
-            except tokenize.TokenError, e:
-                print >> sys.stderr, '%s: %s, line %d, column %d' % (
-                    e[0], filename, e[1][0], e[1][1])
+            except tokenize.TokenError as e:
+                print('%s: %s, line %d, column %d' % (
+                    e[0], filename, e[1][0], e[1][1]), file=sys.stderr)
         finally:
             if closep:
                 fp.close()
@@ -663,7 +664,7 @@ def main():
 if __name__ == '__main__':
     main()
     # some more test strings
-    _(u'a unicode string')
+    _('a unicode string')
     # this one creates a warning
     _('*** Seen unexpected token "%(token)s"') % {'token': 'test'}
     _('more' 'than' 'one' 'string')
--- a/p_rotor.py
+++ b/p_rotor.py
@@ -80,11 +80,11 @@ class newrotor(object):
         for c in map(ord, buf):
             if do_decrypt:
                 # Apply decrypt rotors and xor in reverse order
-                for i in xrange(nr-1,-1,-1):
+                for i in range(nr-1,-1,-1):
                     c = pos[i] ^ rotors[i][c]
             else:
                 # Apply xor and ecrypt rotors
-                for i in xrange(nr):
+                for i in range(nr):
                     c = rotors[i][c ^ pos[i]]
             append(c)
 
@@ -96,7 +96,7 @@ class newrotor(object):
             #        Masking with 0xff simulates this behavior.
             #
             pnew = 0 # (pnew >= size) works as "carry bit"
-            for i in xrange(nr):
+            for i in range(nr):
                 pnew = ((pos[i] + (pnew >= size)) & 0xff) + rotors[i][size]
                 pos[i] = pnew % size
 
@@ -146,7 +146,7 @@ class newrotor(object):
                 # Generate identity permutation for 8-bit bytes plus an
                 # (unused) increment value
                 self.size = size = 256
-                id_rotor = range(size+1)
+                id_rotor = list(range(size+1))
 
                 # Generate nr "random" initial positions and "random"
                 # en/decrypt rotors from id_rotor.
@@ -155,7 +155,7 @@ class newrotor(object):
                 E = []
                 D = []
                 positions = []
-                for i in xrange(nr):
+                for i in range(nr):
                     i = size
                     positions.append(rand(i))
                     erotor = id_rotor[:]
--- a/save_load.py
+++ b/save_load.py
@@ -12,7 +12,7 @@ warnings.filterwarnings("ignore",
                         message='.*rotor module', module=__name__)
 
 import wx
-import os, os.path , cPickle, hashlib
+import os, os.path , pickle, hashlib
 import cal_year
 try:
     import rotor
@@ -40,15 +40,15 @@ def Save_Cycle(name='cycle', passwd='123
     for d in cal_year.cycle.tablet:
 	objSave.append(['tablet',[d.GetDay(), d.GetMonth(), d.GetYear()]])
 
-    for d in cal_year.cycle.colour_set.keys():
+    for d in list(cal_year.cycle.colour_set.keys()):
 	objSave.append(['colour', [d, cal_year.cycle.colour_set[d].Get()] ])
 
-    tmp=rt.encrypt( 'Cycle'+cPickle.dumps(objSave) )
-    tmp="UserName="+cPickle.dumps(name)+"==="+tmp
+    tmp=rt.encrypt( 'Cycle'+pickle.dumps(objSave) )
+    tmp="UserName="+pickle.dumps(name)+"==="+tmp
     p, f_name=get_f_name(file)
 
     if not os.path.exists(p):
-	os.mkdir(p,0700)
+	os.mkdir(p,0o700)
     f=open(f_name,"wb")
     f.write(tmp)
     f.close()
@@ -75,7 +75,7 @@ def Load_Cycle(name='cycle', passwd='123
 	    return False
 	else:
 	    tmp=tmp[5:] #remove control word 'Cycle'
-	    objLoad=cPickle.loads(tmp)
+	    objLoad=pickle.loads(tmp)
 	    set_color_default()
 	    for type, d in objLoad:
 #		print "Load: ", type, d
@@ -100,7 +100,7 @@ def Load_Cycle(name='cycle', passwd='123
 		    cal_year.cycle.note=d.copy()
 		elif type=='colour': # d=['item', (r,g,b)]
 		    c = wx.Colour(d[1][0], d[1][1], d[1][2])
-		    if cal_year.cycle.colour_set.has_key(d[0]):
+		    if d[0] in cal_year.cycle.colour_set:
 			cal_year.cycle.colour_set[d[0]] = c
 		    else:
 			cal_yaar.cycle.colour_set.update({d[0]:c})
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/python3
 
 from distutils.core import setup
 
+1 −0
Original line number Diff line number Diff line
@@ -10,3 +10,4 @@
06b_enter_your_name.patch
07_wxpython3.0.patch
wxclientsize.patch
2to3.patch