Fix python3 syntax errors

Closes #278550

authorJulien Cristau <julien.cristau@logilab.fr>
changesetf9fd7e96e9bd
branchdefault
phasepublic
hiddenno
parent revision#33bd3d623d2b [daemon] change umask after creating pid file
child revision#27c1d560b6ec [pkg] prepare 0.63.1
files modified by this revision
cli.py
daemon.py
dbf.py
optparser.py
test/data/module.py
test/data/module2.py
test/data/noendingnewline.py
test/data/nonregr.py
test/data/sub/momo.py
urllib2ext.py
# HG changeset patch
# User Julien Cristau <julien.cristau@logilab.fr>
# Date 1417181030 -3600
# Fri Nov 28 14:23:50 2014 +0100
# Node ID f9fd7e96e9bd6ced3d78b5c580a2c068154f200e
# Parent 33bd3d623d2b90e07bba247bef52c844467ad0a5
Fix python3 syntax errors

Closes #278550

diff --git a/cli.py b/cli.py
@@ -31,19 +31,21 @@
1              self.CMD_MAP['ronfle'] = _("Sommeil")
2              CLIHelper.__init__(self)
3 
4          help_do_pionce = ("pionce", "pionce duree", _("met ton corps en veille"))
5          def do_pionce(self):
6 -            print 'nap is good'
7 +            print('nap is good')
8 
9          help_do_ronfle = ("ronfle", "ronfle volume", _("met les autres en veille"))
10          def do_ronfle(self):
11 -            print 'fuuuuuuuuuuuu rhhhhhrhrhrrh'
12 +            print('fuuuuuuuuuuuu rhhhhhrhrhrrh')
13 
14      cl = BookShell()
15  """
16 
17 +from __future__ import print_function
18 +
19  __docformat__ = "restructuredtext en"
20 
21  from six.moves import builtins, input
22 
23  if not hasattr(builtins, '_'):
@@ -64,11 +66,11 @@
24              except IOError:
25                  pass
26              import atexit
27              atexit.register(readline.write_history_file, histfile)
28      except:
29 -        print 'readline is not available :-('
30 +        print('readline is not available :-(')
31 
32 
33  class Completer :
34      """Readline completer."""
35 
@@ -155,49 +157,49 @@
36              self.commands[self.CMD_PREFIX + command] = command
37              self._command_help[command] = help_method
38          return self.commands.keys()
39 
40      def _print_help(self, cmd, syntax, explanation):
41 -        print _('Command %s') % cmd
42 -        print _('Syntax: %s') % syntax
43 -        print '\t', explanation
44 -        print
45 +        print(_('Command %s') % cmd)
46 +        print(_('Syntax: %s') % syntax)
47 +        print('\t', explanation)
48 +        print()
49 
50 
51      # predefined commands #####################################################
52 
53      def do_help(self, command=None) :
54          """base input of the help system"""
55          if command in self._command_help:
56              self._print_help(*self._command_help[command])
57          elif command is None or command not in self._topics:
58 -            print _("Use help <topic> or help <command>.")
59 -            print _("Available topics are:")
60 +            print(_("Use help <topic> or help <command>."))
61 +            print(_("Available topics are:"))
62              topics = sorted(self._topics.keys())
63              for topic in topics:
64 -                print '\t', topic
65 -            print
66 -            print _("Available commands are:")
67 +                print('\t', topic)
68 +            print()
69 +            print(_("Available commands are:"))
70              commands = self.commands.keys()
71              commands.sort()
72              for command in commands:
73 -                print '\t', command[len(self.CMD_PREFIX):]
74 +                print('\t', command[len(self.CMD_PREFIX):])
75 
76          else:
77 -            print _('Available commands about %s:') % command
78 +            print(_('Available commands about %s:') % command)
79              print
80              for command_help_method in self._topics[command]:
81                  try:
82                      if callable(command_help_method):
83                          self._print_help(*command_help_method())
84                      else:
85                          self._print_help(*command_help_method)
86                  except:
87                      import traceback
88                      traceback.print_exc()
89 -                    print 'ERROR in help method %s'% (
90 -                        command_help_method.__name__)
91 +                    print('ERROR in help method %s'% (
92 +                        command_help_method.__name__))
93 
94      help_do_help = ("help", "help [topic|command]",
95                      _("print help message for the given topic/command or \
96  available topics when no argument"))
97 
diff --git a/daemon.py b/daemon.py
@@ -49,11 +49,11 @@
98      os.setgid(passwd.pw_gid)
99      os.setuid(passwd.pw_uid)
100      os.environ['HOME'] = passwd.pw_dir
101 
102 
103 -def daemonize(pidfile=None, uid=None, umask=077):
104 +def daemonize(pidfile=None, uid=None, umask=0o77):
105      """daemonize a Unix process. Set paranoid umask by default.
106 
107      Return 1 in the original process, 2 in the first fork, and None for the
108      second fork (eg daemon process).
109      """
diff --git a/dbf.py b/dbf.py
@@ -28,10 +28,11 @@
110  :date: 13/07/2007
111 
112  http://www.physics.ox.ac.uk/users/santoso/Software.Repository.html
113  page says code is "available as is without any warranty or support".
114  """
115 +from __future__ import print_function
116 
117  import struct
118  import os, os.path
119  import sys
120  import csv
@@ -77,11 +78,11 @@
121          return result
122 
123      def open(self, db_name):
124          filesize = os.path.getsize(db_name)
125          if filesize <= 68:
126 -            raise IOError, 'The file is not large enough to be a dbf file'
127 +            raise IOError('The file is not large enough to be a dbf file')
128 
129          self.fdb = open(db_name, 'rb')
130 
131          self.memo_file = ''
132          if os.path.isfile(db_name[0:-1] + 't'):
@@ -150,11 +151,11 @@
133      def get_record_with_names(self, rec_no):
134          """
135          This function accept record number from 0 to N-1
136          """
137          if rec_no < 0 or rec_no > self.num_records:
138 -            raise Exception, 'Unable to extract data outside the range'
139 +            raise Exception('Unable to extract data outside the range')
140 
141          offset = self.header['Record Size'] * rec_no
142          data = self.db_data[offset:offset+self.row_len]
143          record = self._assign_ids(struct.unpack(self.row_format, data), self.row_ids)
144 
@@ -225,6 +226,6 @@
145      return  rec
146 
147  if __name__=='__main__':
148      rec = readDbf('dbf/sptable.dbf')
149      for line in rec:
150 -        print '%s %s' % (line['GENUS'].strip(), line['SPECIES'].strip())
151 +        print('%s %s' % (line['GENUS'].strip(), line['SPECIES'].strip()))
diff --git a/optparser.py b/optparser.py
@@ -27,10 +27,12 @@
152  >>> run, options, args = parser.parse_command(sys.argv[1:])
153  >>> return run(options, args[1:])
154 
155  With mymod.build that defines two functions run and add_options
156  """
157 +from __future__ import print_function
158 +
159  __docformat__ = "restructuredtext en"
160 
161  from warnings import warn
162  warn('lgc.optparser module is deprecated, use lgc.clcommands instead', DeprecationWarning,
163       stacklevel=2)
@@ -53,13 +55,13 @@
164              "mod_or_funcs has to be a module name or a tuple of functions"
165          self._commands[name] = (mod_or_funcs, help)
166 
167      def print_main_help(self):
168          optparse.OptionParser.print_help(self)
169 -        print '\ncommands:'
170 +        print('\ncommands:')
171          for cmdname, (_, help) in self._commands.items():
172 -            print '% 10s - %s' % (cmdname, help)
173 +            print('% 10s - %s' % (cmdname, help))
174 
175      def parse_command(self, args):
176          if len(args) == 0:
177              self.print_main_help()
178              sys.exit(1)
@@ -76,11 +78,11 @@
179          self.prog = '%s %s' % (self.prog, cmd)
180          mod_or_f, help = self._commands[cmd]
181          # optparse inserts self.description between usage and options help
182          self.description = help
183          if isinstance(mod_or_f, str):
184 -            exec 'from %s import run, add_options' % mod_or_f
185 +            exec('from %s import run, add_options' % mod_or_f)
186          else:
187              run, add_options = mod_or_f
188          add_options(self)
189          (options, args) = self.parse_args(args)
190          if not (self.min_args <= len(args) <= self.max_args):
diff --git a/test/data/module.py b/test/data/module.py
@@ -1,9 +1,9 @@
191  # -*- coding: Latin-1 -*-
192  """test module for astng
193  """
194 -
195 +from __future__ import print_function
196 
197  from logilab.common import modutils, Execute as spawn
198  from logilab.common.astutils import *
199  import os.path
200 
@@ -19,11 +19,11 @@
201              del MY_DICT[i]
202              continue
203          else:
204              break
205      else:
206 -        print '!!!'
207 +        print('!!!')
208 
209  class YO:
210      """hehe"""
211      a=1
212      def __init__(self):
@@ -34,11 +34,11 @@
213          except (NameError, TypeError):
214              raise XXXError()
215          except:
216              raise
217 
218 -#print '*****>',YO.__dict__
219 +#print('*****>',YO.__dict__)
220  class YOUPI(YO):
221      class_attr = None
222 
223      def __init__(self):
224          self.member = None
@@ -49,13 +49,13 @@
225          try:
226              MY_DICT = {}
227              local = None
228              autre = [a for a, b in MY_DICT if b]
229              if b in autre:
230 -                print 'yo',
231 +                print('yo', end=' ')
232              elif a in autre:
233 -                print 'hehe'
234 +                print('hehe')
235              global_access(local, val=autre)
236          finally:
237              return local
238 
239      def static_method():
@@ -63,25 +63,7 @@
240          assert MY_DICT, '???'
241      static_method = staticmethod(static_method)
242 
243      def class_method(cls):
244          """class method test"""
245 -        exec a in b
246 +        exec(a, b)
247      class_method = classmethod(class_method)
248 -
249 -
250 -def nested_args(a, (b, c, d)):
251 -    """nested arguments test"""
252 -    print a, b, c, d
253 -    while 1:
254 -        if a:
255 -            break
256 -        a += +1
257 -    else:
258 -        b += -2
259 -    if c:
260 -        d = a and b or c
261 -    else:
262 -        c = a and b or d
263 -    map(lambda x, y: (y, x), a)
264 -
265 -redirect = nested_args
diff --git a/test/data/module2.py b/test/data/module2.py
@@ -35,18 +35,18 @@
266 
267  del YO.member
268 
269  del YO
270  [SYN1, SYN2] = Concrete0, Concrete1
271 -assert `1`
272 +assert '1'
273  b = 1 | 2 & 3 ^ 8
274 -exec 'c = 3'
275 -exec 'c = 3' in {}, {}
276 +exec('c = 3')
277 +exec('c = 3', {}, {})
278 
279  def raise_string(a=2, *args, **kwargs):
280      raise 'pas glop'
281 -    raise Exception, 'yo'
282 +    raise Exception('yo')
283      yield 'coucou'
284 
285  a = b + 2
286  c = b * 2
287  c = b / 2
diff --git a/test/data/noendingnewline.py b/test/data/noendingnewline.py
@@ -1,6 +1,6 @@
288 -
289 +from __future__ import print_function
290 
291  import unittest
292 
293 
294  class TestCase(unittest.TestCase):
@@ -18,19 +18,19 @@
295 
296 
297      def xxx(self):
298          if False:
299              pass
300 -            print 'a'
301 +            print('a')
302 
303          if False:
304              pass
305              pass
306 
307          if False:
308              pass
309 -            print 'rara'
310 +            print('rara')
311 
312 
313  if __name__ == '__main__':
314 -    print 'test2'
315 +    print('test2')
316      unittest.main()
diff --git a/test/data/nonregr.py b/test/data/nonregr.py
@@ -1,5 +1,7 @@
317 +from __future__ import print_function
318 +
319  try:
320      enumerate = enumerate
321  except NameError:
322 
323      def enumerate(iterable):
@@ -9,6 +11,6 @@
324              yield i, val
325              i += 1
326 
327  def toto(value):
328      for k, v in value:
329 -        print v.get('yo')
330 +        print(v.get('yo'))
diff --git a/test/data/sub/momo.py b/test/data/sub/momo.py
@@ -1,1 +1,3 @@
331 -print 'yo'
332 +from __future__ import print_function
333 +
334 +print('yo')
diff --git a/urllib2ext.py b/urllib2ext.py
@@ -1,5 +1,7 @@
335 +from __future__ import print_function
336 +
337  import logging
338  import urllib2
339 
340  import kerberos as krb
341 
@@ -82,6 +84,6 @@
342      cj = cookielib.CookieJar()
343      ch = urllib2.HTTPCookieProcessor(cj)
344      # test with url sys.argv[1]
345      h = HTTPGssapiAuthHandler()
346      response = urllib2.build_opener(h, ch).open(sys.argv[1])
347 -    print '\nresponse: %s\n--------------\n' % response.code, response.info()
348 +    print('\nresponse: %s\n--------------\n' % response.code, response.info())