summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRémi Cardona <remi.cardona@free.fr>2014-09-17 23:34:31 +0200
committerRémi Cardona <remi.cardona@free.fr>2014-09-17 23:34:31 +0200
commit30937b08ed70f51fa5785b419bda47f122157c3c (patch)
tree072cf154c24de1ae151d20093ca9a3cc64a140c3
parentac2d15727c079fbc1d3fe6a606feef9c1179d2ce (diff)
downloadlogilab-common-30937b08ed70f51fa5785b419bda47f122157c3c.tar.gz
[py3k] print function
Requires python >= 2.6.
-rw-r--r--clcommands.py54
-rw-r--r--configuration.py33
-rw-r--r--debugger.py7
-rw-r--r--decorators.py7
-rw-r--r--fileutils.py7
-rw-r--r--optik_ext.py8
-rw-r--r--pytest.py41
-rw-r--r--registry.py4
-rw-r--r--shellutils.py5
-rw-r--r--table.py5
-rw-r--r--test/unittest_testlib.py6
-rw-r--r--test/utils.py11
-rw-r--r--testlib.py24
-rw-r--r--ureports/text_writer.py5
14 files changed, 129 insertions, 88 deletions
diff --git a/clcommands.py b/clcommands.py
index 839ab96..4778b99 100644
--- a/clcommands.py
+++ b/clcommands.py
@@ -22,6 +22,8 @@ e.g called as "tool command [options] args..." where <options> and <args> are
command'specific
"""
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
import sys
@@ -115,7 +117,7 @@ class CommandLine(dict):
if arg in ('-h', '--help'):
self.usage_and_exit(0)
if self.version is not None and arg in ('--version'):
- print self.version
+ print(self.version)
sys.exit(0)
rcfile = self.rcfile
if rcfile is not None and arg in ('-C', '--rc-file'):
@@ -127,21 +129,21 @@ class CommandLine(dict):
try:
command = self.get_command(arg)
except KeyError:
- print 'ERROR: no %s command' % arg
- print
+ print('ERROR: no %s command' % arg)
+ print()
self.usage_and_exit(1)
try:
sys.exit(command.main_run(args, rcfile))
except KeyboardInterrupt as exc:
- print 'Interrupted',
+ print('Interrupted', end=' ')
if str(exc):
- print ': %s' % exc,
- print
+ print(': %s' % exc, end=' ')
+ print()
sys.exit(4)
except BadCommandUsage as err:
- print 'ERROR:', err
- print
- print command.help()
+ print('ERROR:', err)
+ print()
+ print(command.help())
sys.exit(1)
def create_logger(self, handler, logthreshold=None):
@@ -164,32 +166,32 @@ class CommandLine(dict):
"""display usage for the main program (i.e. when no command supplied)
and exit
"""
- print 'usage:', self.pgm,
+ print('usage:', self.pgm, end=' ')
if self.rcfile:
- print '[--rc-file=<configuration file>]',
- print '<command> [options] <command argument>...'
+ print('[--rc-file=<configuration file>]', end=' ')
+ print('<command> [options] <command argument>...')
if self.doc:
- print '\n%s' % self.doc
- print '''
+ print('\n%s' % self.doc)
+ print('''
Type "%(pgm)s <command> --help" for more information about a specific
-command. Available commands are :\n''' % self.__dict__
+command. Available commands are :\n''' % self.__dict__)
max_len = max([len(cmd) for cmd in self])
padding = ' ' * max_len
for cmdname, cmd in sorted(self.items()):
if not cmd.hidden:
- print ' ', (cmdname + padding)[:max_len], cmd.short_description()
+ print(' ', (cmdname + padding)[:max_len], cmd.short_description())
if self.rcfile:
- print '''
+ print('''
Use --rc-file=<configuration file> / -C <configuration file> before the command
to specify a configuration file. Default to %s.
-''' % self.rcfile
- print '''%(pgm)s -h/--help
- display this usage information and exit''' % self.__dict__
+''' % self.rcfile)
+ print('''%(pgm)s -h/--help
+ display this usage information and exit''' % self.__dict__)
if self.version:
- print '''%(pgm)s -v/--version
- display version configuration and exit''' % self.__dict__
+ print('''%(pgm)s -v/--version
+ display version configuration and exit''' % self.__dict__)
if self.copyright:
- print '\n', self.copyright
+ print('\n', self.copyright)
def usage_and_exit(self, status):
self.usage()
@@ -283,14 +285,14 @@ class ListCommandsCommand(Command):
command = args.pop()
cmd = _COMMANDS[command]
for optname, optdict in cmd.options:
- print '--help'
- print '--' + optname
+ print('--help')
+ print('--' + optname)
else:
commands = sorted(_COMMANDS.keys())
for command in commands:
cmd = _COMMANDS[command]
if not cmd.hidden:
- print command
+ print(command)
# deprecated stuff #############################################################
diff --git a/configuration.py b/configuration.py
index a14fb95..d04e77b 100644
--- a/configuration.py
+++ b/configuration.py
@@ -106,6 +106,9 @@ Quick start: simplest usage
than 0.61 the behaviour is unspecified.
"""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
__all__ = ('OptionsManagerMixIn', 'OptionsProviderMixIn',
@@ -251,7 +254,7 @@ def input_password(optdict, question='password:'):
value2 = getpass('confirm: ')
if value == value2:
return value
- print 'password mismatch, try again'
+ print('password mismatch, try again')
def input_string(optdict, question):
value = raw_input(question).strip()
@@ -267,7 +270,7 @@ def _make_input_function(opttype):
return _call_validator(opttype, optdict, None, value)
except optik_ext.OptionValueError as ex:
msg = str(ex).split(':', 1)[-1].strip()
- print 'bad value: %s' % msg
+ print('bad value: %s' % msg)
return input_validator
INPUT_FUNCTIONS = {
@@ -377,8 +380,8 @@ def ini_format_section(stream, section, options, encoding=None, doc=None):
"""format an options section using the INI format"""
encoding = _get_encoding(encoding, stream)
if doc:
- print >> stream, _encode(comment(doc), encoding)
- print >> stream, '[%s]' % section
+ print(_encode(comment(doc), encoding), file=stream)
+ print('[%s]' % section, file=stream)
ini_format(stream, options, encoding)
def ini_format(stream, options, encoding):
@@ -388,15 +391,15 @@ def ini_format(stream, options, encoding):
help = optdict.get('help')
if help:
help = normalize_text(help, line_len=79, indent='# ')
- print >> stream
- print >> stream, _encode(help, encoding)
+ print(file=stream)
+ print(_encode(help, encoding), file=stream)
else:
- print >> stream
+ print(file=stream)
if value is None:
- print >> stream, '#%s=' % optname
+ print('#%s=' % optname, file=stream)
else:
value = _encode(value, encoding).strip()
- print >> stream, '%s=%s' % (optname, value)
+ print('%s=%s' % (optname, value), file=stream)
format_section = ini_format_section
@@ -575,7 +578,7 @@ class OptionsManagerMixIn(object):
printed = False
for section in sections:
if printed:
- print >> stream, '\n'
+ print('\n', file=stream)
format_section(stream, section.upper(), options_by_section[section],
encoding)
printed = True
@@ -614,7 +617,7 @@ class OptionsManagerMixIn(object):
if opt in self._all_options:
break # already processed
def helpfunc(option, opt, val, p, level=helplevel):
- print self.help(level)
+ print(self.help(level))
sys.exit(0)
helpmsg = '%s verbose help.' % ' '.join(['more'] * helplevel)
optdict = {'action' : 'callback', 'callback' : helpfunc,
@@ -636,7 +639,7 @@ class OptionsManagerMixIn(object):
parser._sections[sect.upper()] = values
elif not self.quiet:
msg = 'No config file found, using default configuration'
- print >> sys.stderr, msg
+ print(msg, file=sys.stderr)
return
def input_config(self, onlysection=None, inputlevel=0, stream=None):
@@ -860,12 +863,12 @@ class OptionsProviderMixIn(object):
defaultstr = ': '
else:
defaultstr = '(default: %s): ' % format_option_value(optdict, default)
- print ':%s:' % option
- print optdict.get('help') or option
+ print(':%s:' % option)
+ print(optdict.get('help') or option)
inputfunc = INPUT_FUNCTIONS[optdict['type']]
value = inputfunc(optdict, defaultstr)
while default is REQUIRED and not value:
- print 'please specify a value'
+ print('please specify a value')
value = inputfunc(optdict, '%s: ' % option)
if value is None and default is not None:
value = default
diff --git a/debugger.py b/debugger.py
index 7556322..ab0fb75 100644
--- a/debugger.py
+++ b/debugger.py
@@ -26,6 +26,9 @@
"""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
try:
@@ -182,8 +185,8 @@ class Debugger(Pdb):
if not arg:
try:
source, start_lineno = getsource(self.curframe)
- print colorize(''.join(source), start_lineno,
- self.curframe.f_lineno)
+ print(colorize(''.join(source), start_lineno,
+ self.curframe.f_lineno))
except KeyboardInterrupt:
pass
except IOError:
diff --git a/decorators.py b/decorators.py
index 70b4690..e3942da 100644
--- a/decorators.py
+++ b/decorators.py
@@ -16,6 +16,9 @@
# You should have received a copy of the GNU Lesser General Public License along
# with logilab-common. If not, see <http://www.gnu.org/licenses/>.
""" A few useful function/method decorators. """
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
import sys
@@ -225,8 +228,8 @@ def timed(f):
t = time()
c = clock()
res = f(*args, **kwargs)
- print '%s clock: %.9f / time: %.9f' % (f.__name__,
- clock() - c, time() - t)
+ print('%s clock: %.9f / time: %.9f' % (f.__name__,
+ clock() - c, time() - t))
return res
return wrap
diff --git a/fileutils.py b/fileutils.py
index 3b04db9..b30cf5f 100644
--- a/fileutils.py
+++ b/fileutils.py
@@ -23,6 +23,9 @@ get_by_ext, remove_dead_links
write_open_mode, ensure_fs_mode, export
:sort: path manipulation, file manipulation
"""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
import sys
@@ -374,7 +377,7 @@ def export(from_dir, to_dir,
src = join(directory, filename)
dest = to_dir + src[len(from_dir):]
if verbose:
- print >> sys.stderr, src, '->', dest
+ print(src, '->', dest, file=sys.stderr)
if exists(dest):
remove(dest)
shutil.copy2(src, dest)
@@ -396,6 +399,6 @@ def remove_dead_links(directory, verbose=0):
src = join(dirpath, filename)
if islink(src) and not exists(src):
if verbose:
- print 'remove dead link', src
+ print('remove dead link', src)
remove(src)
diff --git a/optik_ext.py b/optik_ext.py
index 7ba30bb..1fd2a7f 100644
--- a/optik_ext.py
+++ b/optik_ext.py
@@ -46,6 +46,8 @@ It also defines three new types for optik/optparse command line parser :
argument of this type will be converted to a float value in bytes
according to byte units (b, kb, mb, gb, tb)
"""
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
import re
@@ -381,9 +383,9 @@ def generate_manpage(optparser, pkginfo, section=1, stream=sys.stdout, level=0):
formatter = ManHelpFormatter()
formatter.output_level = level
formatter.parser = optparser
- print >> stream, formatter.format_head(optparser, pkginfo, section)
- print >> stream, optparser.format_option_help(formatter)
- print >> stream, formatter.format_tail(pkginfo)
+ print(formatter.format_head(optparser, pkginfo, section), file=stream)
+ print(optparser.format_option_help(formatter), file=stream)
+ print(formatter.format_tail(pkginfo), file=stream)
__all__ = ('OptionParser', 'Option', 'OptionGroup', 'OptionValueError',
diff --git a/pytest.py b/pytest.py
index a84e6f4..486d4fd 100644
--- a/pytest.py
+++ b/pytest.py
@@ -92,6 +92,9 @@ you can filter the function with a simple python expression
* ``tata`` and ``titi`` match``rouge ^ carre``
* ``titi`` match ``rouge and not carre``
"""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
PYTEST_DOC = """%prog [OPTIONS] [testfile [testpattern]]
@@ -333,8 +336,8 @@ class PyTester(object):
def show_report(self):
"""prints the report and returns appropriate exitcode"""
# everything has been ran, print report
- print "*" * 79
- print self.report
+ print("*" * 79)
+ print(self.report)
def get_errcode(self):
# errcode set explicitly
@@ -357,13 +360,13 @@ class PyTester(object):
dirs.remove(skipped)
basename = osp.basename(dirname)
if this_is_a_testdir(basename):
- print "going into", dirname
+ print("going into", dirname)
# we found a testdir, let's explore it !
if not self.testonedir(dirname, exitfirst):
break
dirs[:] = []
if self.report.ran == 0:
- print "no test dir found testing here:", here
+ print("no test dir found testing here:", here)
# if no test was found during the visit, consider
# the local directory as a test directory even if
# it doesn't have a traditional test directory name
@@ -383,8 +386,9 @@ class PyTester(object):
restartfile = open(FILE_RESTART, "w")
restartfile.close()
except Exception:
- print >> sys.__stderr__, "Error while overwriting \
-succeeded test file :", osp.join(os.getcwd(), FILE_RESTART)
+ print("Error while overwriting succeeded test file :",
+ osp.join(os.getcwd(), FILE_RESTART),
+ file=sys.__stderr__)
raise
# run test and collect information
prog = self.testfile(filename, batchmode=True)
@@ -410,11 +414,12 @@ succeeded test file :", osp.join(os.getcwd(), FILE_RESTART)
restartfile = open(FILE_RESTART, "w")
restartfile.close()
except Exception:
- print >> sys.__stderr__, "Error while overwriting \
-succeeded test file :", osp.join(os.getcwd(), FILE_RESTART)
+ print("Error while overwriting succeeded test file :",
+ osp.join(os.getcwd(), FILE_RESTART), file=sys.__stderr__)
raise
modname = osp.basename(filename)[:-3]
- print >> sys.stderr, (' %s ' % osp.basename(filename)).center(70, '=')
+ print((' %s ' % osp.basename(filename)).center(70, '='),
+ file=sys.__stderr__)
try:
tstart, cstart = time(), clock()
try:
@@ -426,12 +431,13 @@ succeeded test file :", osp.join(os.getcwd(), FILE_RESTART)
self.errcode = exc.code
raise
except testlib.SkipTest:
- print "Module skipped:", filename
+ print("Module skipped:", filename)
self.report.skip_module(filename)
return None
except Exception:
self.report.failed_to_test_module(filename)
- print >> sys.stderr, 'unhandled exception occurred while testing', modname
+ print('unhandled exception occurred while testing', modname,
+ file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
return None
@@ -482,7 +488,7 @@ class DjangoTester(PyTester):
from django.test.utils import teardown_test_environment
from django.test.utils import destroy_test_db
teardown_test_environment()
- print 'destroying', self.dbname
+ print('destroying', self.dbname)
destroy_test_db(self.dbname, verbosity=0)
def testall(self, exitfirst=False):
@@ -500,7 +506,7 @@ class DjangoTester(PyTester):
else:
basename = osp.basename(dirname)
if basename in ('test', 'tests'):
- print "going into", dirname
+ print("going into", dirname)
# we found a testdir, let's explore it !
if not self.testonedir(dirname, exitfirst):
break
@@ -541,7 +547,8 @@ class DjangoTester(PyTester):
os.chdir(dirname)
self.load_django_settings(dirname)
modname = osp.basename(filename)[:-3]
- print >>sys.stderr, (' %s ' % osp.basename(filename)).center(70, '=')
+ print((' %s ' % osp.basename(filename)).center(70, '='),
+ file=sys.stderr)
try:
try:
tstart, cstart = time(), clock()
@@ -557,8 +564,8 @@ class DjangoTester(PyTester):
import traceback
traceback.print_exc()
self.report.failed_to_test_module(filename)
- print 'unhandled exception occurred while testing', modname
- print 'error: %s' % exc
+ print('unhandled exception occurred while testing', modname)
+ print('error: %s' % exc)
return None
finally:
self.after_testfile()
@@ -687,7 +694,7 @@ def run():
prof = hotshot.Profile(options.profile)
prof.runcall(cmd, *args)
prof.close()
- print 'profile data saved in', options.profile
+ print('profile data saved in', options.profile)
else:
cmd(*args)
except SystemExit:
diff --git a/registry.py b/registry.py
index 24b5a78..62c9707 100644
--- a/registry.py
+++ b/registry.py
@@ -73,6 +73,8 @@ Exceptions
.. autoclass:: NoSelectableObject
"""
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
import sys
@@ -847,7 +849,7 @@ TRACED_OIDS = None
def _trace_selector(cls, selector, args, ret):
vobj = args[0]
if TRACED_OIDS == 'all' or vobj.__regid__ in TRACED_OIDS:
- print '%s -> %s for %s(%s)' % (cls, ret, vobj, vobj.__regid__)
+ print('%s -> %s for %s(%s)' % (cls, ret, vobj, vobj.__regid__))
def _lltrace(selector):
"""use this decorator on your predicates so they become traceable with
diff --git a/shellutils.py b/shellutils.py
index b444e0e..02d4455 100644
--- a/shellutils.py
+++ b/shellutils.py
@@ -18,6 +18,9 @@
"""shell/term utilities, useful to write some python scripts instead of shell
scripts.
"""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
import os
@@ -426,7 +429,7 @@ class RawInput(object):
if self._print:
self._print(msg)
else:
- print msg
+ print(msg)
tries -= 1
raise Exception('unable to get a sensible answer')
diff --git a/table.py b/table.py
index f40d3b3..122e368 100644
--- a/table.py
+++ b/table.py
@@ -16,6 +16,9 @@
# You should have received a copy of the GNU Lesser General Public License along
# with logilab-common. If not, see <http://www.gnu.org/licenses/>.
"""Table management module."""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
@@ -650,7 +653,7 @@ class TableStyleSheet:
'table.py', 'exec'))
self.rules.append(rule)
except SyntaxError:
- print "Bad Stylesheet Rule : %s [skipped]"%rule
+ print("Bad Stylesheet Rule : %s [skipped]" % rule)
def add_rowsum_rule(self, dest_cell, row_index, start_col, end_col):
diff --git a/test/unittest_testlib.py b/test/unittest_testlib.py
index f83e1f2..59e736d 100644
--- a/test/unittest_testlib.py
+++ b/test/unittest_testlib.py
@@ -17,6 +17,8 @@
# with logilab-common. If not, see <http://www.gnu.org/licenses/>.
"""unittest module for logilab.comon.testlib"""
+from __future__ import print_function
+
import os
import sys
from os.path import join, dirname, isdir, isfile, abspath, exists
@@ -709,8 +711,8 @@ class DecoratorTC(TestCase):
not exist : function return by the decorator should \
NOT be the same.' % module)
return
- print 'all modules in %s exist. Could not test %s' % (', '.join(modules),
- sys._getframe().f_code.co_name)
+ print('all modules in %s exist. Could not test %s' % (', '.join(modules),
+ sys._getframe().f_code.co_name))
class TagTC(TestCase):
diff --git a/test/utils.py b/test/utils.py
index f54c179..37e23cc 100644
--- a/test/utils.py
+++ b/test/utils.py
@@ -18,6 +18,7 @@
'''unit tests utilities for ureports
'''
+from __future__ import print_function
from cStringIO import StringIO
from logilab.common.ureports.nodes import *
@@ -31,11 +32,11 @@ class WriterTC:
try:
self.assertMultiLineEqual(got, expected)
except:
- print '**** got for %s' % test_id
- print got
- print '**** while expected'
- print expected
- print '****'
+ print('**** got for %s' % test_id)
+ print(got)
+ print('**** while expected')
+ print(expected)
+ print('****')
raise
def test_section(self):
diff --git a/testlib.py b/testlib.py
index 2265ce2..c3cf17e 100644
--- a/testlib.py
+++ b/testlib.py
@@ -36,6 +36,9 @@ If no non-option arguments are present, prefixes used are 'test',
'regrtest', 'smoketest' and 'unittest'.
"""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
# modified copy of some functions from test/regrtest.py from PyXml
# disable camel case warning
@@ -189,27 +192,27 @@ def start_interactive_mode(result):
else:
while True:
testindex = 0
- print "Choose a test to debug:"
+ print("Choose a test to debug:")
# order debuggers in the same way than errors were printed
- print "\n".join(['\t%s : %s' % (i, descr) for i, (_, descr)
- in enumerate(descrs)])
- print "Type 'exit' (or ^D) to quit"
- print
+ print("\n".join(['\t%s : %s' % (i, descr) for i, (_, descr)
+ in enumerate(descrs)]))
+ print("Type 'exit' (or ^D) to quit")
+ print()
try:
todebug = raw_input('Enter a test name: ')
if todebug.strip().lower() == 'exit':
- print
+ print()
break
else:
try:
testindex = int(todebug)
debugger = debuggers[descrs[testindex][0]]
except (ValueError, IndexError):
- print "ERROR: invalid test number %r" % (todebug, )
+ print("ERROR: invalid test number %r" % (todebug, ))
else:
debugger.start()
except (EOFError, KeyboardInterrupt):
- print
+ print()
break
@@ -594,8 +597,9 @@ class TestCase(unittest.TestCase):
finally:
restartfile.close()
except Exception:
- print >> sys.__stderr__, "Error while saving \
-succeeded test into", osp.join(os.getcwd(), FILE_RESTART)
+ print("Error while saving succeeded test into",
+ osp.join(os.getcwd(), FILE_RESTART),
+ file=sys.__stderr__)
raise
result.addSuccess(self)
finally:
diff --git a/ureports/text_writer.py b/ureports/text_writer.py
index 04c8f26..88a046a 100644
--- a/ureports/text_writer.py
+++ b/ureports/text_writer.py
@@ -16,6 +16,9 @@
# You should have received a copy of the GNU Lesser General Public License along
# with logilab-common. If not, see <http://www.gnu.org/licenses/>.
"""Text formatting drivers for ureports"""
+
+from __future__ import print_function
+
__docformat__ = "restructuredtext en"
from logilab.common.textutils import linesep
@@ -54,7 +57,7 @@ class TextWriter(BaseWriter):
try:
self.writeln(TITLE_UNDERLINES[self.section] * len(title))
except IndexError:
- print "FIXME TITLE TOO DEEP. TURNING TITLE INTO TEXT"
+ print("FIXME TITLE TOO DEEP. TURNING TITLE INTO TEXT")
def visit_paragraph(self, layout):
"""enter a paragraph"""