void-packages/srcpkgs/python-docutils/patches/0002-py3-Switch-to-print-functions.patch
Doan Tran Cong Danh 6b24f153d7 python3-docutils: unbroken: import from upstream
All of those patches are picked from upstream.

    xbps-src check python3-docutils

works fine now!
2019-12-01 12:38:58 +01:00

1517 lines
56 KiB
Diff
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

From ede25690b4b71fbab02506f3a0919e9101b7b73b Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 19 Nov 2019 23:47:55 +0700
Subject: [PATCH 02/26] py3: Switch to print functions
Remove all uses of print as a statement. This includes comments, many of
which are simply removed as noise (they're in version control and can be
re-added later, if necessary).
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8346 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/core.py | 37 +++++++------
docutils/io.py | 7 ++-
docutils/nodes.py | 3 +-
docutils/parsers/rst/directives/body.py | 3 +-
docutils/parsers/rst/roles.py | 1 -
docutils/parsers/rst/states.py | 4 +-
docutils/statemachine.py | 55 +++++++++----------
docutils/transforms/universal.py | 3 +-
docutils/utils/__init__.py | 1 -
docutils/utils/math/latex2mathml.py | 1 -
docutils/utils/math/tex2mathml_extern.py | 7 ++-
docutils/utils/smartquotes.py | 19 ++++---
docutils/writers/_html_base.py | 9 ---
docutils/writers/latex2e/__init__.py | 9 ++-
install.py | 5 +-
setup.py | 11 ++--
test/DocutilsTestSupport.py | 27 ++++-----
test/alltests.py | 32 +++++------
test/package_unittest.py | 11 ++--
test/test_error_reporting.py | 7 ++-
test/test_functional.py | 5 +-
test/test_io.py | 4 +-
.../test_rst/test_directives/test_code.py | 14 +++--
.../test_directives/test_code_long.py | 7 ++-
.../test_directives/test_code_none.py | 4 +-
.../test_rst/test_doctest_blocks.py | 12 ++--
test/test_settings.py | 9 +--
test/test_statemachine.py | 23 ++++----
test/test_transforms/test_smartquotes.py | 10 ++--
.../test_strip_elements_with_class.py | 2 +-
test/test_viewlist.py | 14 -----
tools/dev/create_unimap.py | 1 +
tools/dev/generate_punctuation_chars.py | 48 +---------------
tools/dev/profile_docutils.py | 1 +
tools/dev/unicode2rstsubs.py | 1 +
tools/quicktest.py | 1 +
tools/rst2odt_prepstyles.py | 28 +++++-----
37 files changed, 195 insertions(+), 241 deletions(-)
diff --git a/docutils/core.py b/docutils/core.py
index 2eebbf2..6a99020 100644
--- a/docutils/core.py
+++ b/docutils/core.py
@@ -11,6 +11,7 @@ custom component objects first, and pass *them* to
.. _The Docutils Publisher: http://docutils.sf.net/docs/api/publisher.html
"""
+from __future__ import print_function
__docformat__ = 'reStructuredText'
@@ -243,24 +244,24 @@ class Publisher(object):
if not self.document:
return
if self.settings.dump_settings:
- print >>self._stderr, '\n::: Runtime settings:'
- print >>self._stderr, pprint.pformat(self.settings.__dict__)
+ print('\n::: Runtime settings:', file=self._stderr)
+ print(pprint.pformat(self.settings.__dict__), file=self._stderr)
if self.settings.dump_internals:
- print >>self._stderr, '\n::: Document internals:'
- print >>self._stderr, pprint.pformat(self.document.__dict__)
+ print('\n::: Document internals:', file=self._stderr)
+ print(pprint.pformat(self.document.__dict__), file=self._stderr)
if self.settings.dump_transforms:
- print >>self._stderr, '\n::: Transforms applied:'
- print >>self._stderr, (' (priority, transform class, '
- 'pending node details, keyword args)')
- print >>self._stderr, pprint.pformat(
+ print('\n::: Transforms applied:', file=self._stderr)
+ print(' (priority, transform class, pending node details, '
+ 'keyword args)', file=self._stderr)
+ print(pprint.pformat(
[(priority, '%s.%s' % (xclass.__module__, xclass.__name__),
pending and pending.details, kwargs)
for priority, xclass, pending, kwargs
- in self.document.transformer.applied])
+ in self.document.transformer.applied]), file=self._stderr)
if self.settings.dump_pseudo_xml:
- print >>self._stderr, '\n::: Pseudo-XML:'
- print >>self._stderr, self.document.pformat().encode(
- 'raw_unicode_escape')
+ print('\n::: Pseudo-XML:', file=self._stderr)
+ print(self.document.pformat().encode(
+ 'raw_unicode_escape'), file=self._stderr)
def report_Exception(self, error):
if isinstance(error, utils.SystemMessage):
@@ -275,8 +276,8 @@ class Publisher(object):
u'Unable to open destination file for writing:\n'
u' %s\n' % ErrorString(error))
else:
- print >>self._stderr, u'%s' % ErrorString(error)
- print >>self._stderr, ("""\
+ print(u'%s' % ErrorString(error), file=self._stderr)
+ print(("""\
Exiting due to error. Use "--traceback" to diagnose.
Please report errors to <docutils-users@lists.sf.net>.
Include "--traceback" output, Docutils version (%s%s),
@@ -284,12 +285,12 @@ Python version (%s), your OS type & version, and the
command line used.""" % (__version__,
docutils.__version_details__ and
' [%s]'%docutils.__version_details__ or '',
- sys.version.split()[0]))
+ sys.version.split()[0])), file=self._stderr)
def report_SystemMessage(self, error):
- print >>self._stderr, ('Exiting due to level-%s (%s) system message.'
- % (error.level,
- utils.Reporter.levels[error.level]))
+ print('Exiting due to level-%s (%s) system message.' % (
+ error.level, utils.Reporter.levels[error.level]),
+ file=self._stderr)
def report_UnicodeError(self, error):
data = error.object[error.start:error.end]
diff --git a/docutils/io.py b/docutils/io.py
index 79cb012..3b0f93e 100644
--- a/docutils/io.py
+++ b/docutils/io.py
@@ -6,6 +6,7 @@
I/O classes provide a uniform API for low-level input and output. Subclasses
exist for a variety of input/output mechanisms.
"""
+from __future__ import print_function
__docformat__ = 'reStructuredText'
@@ -343,9 +344,9 @@ class FileOutput(Output):
elif (# destination is file-type object -> check mode:
mode and hasattr(self.destination, 'mode')
and mode != self.destination.mode):
- print >>self._stderr, ('Warning: Destination mode "%s" '
- 'differs from specified mode "%s"' %
- (self.destination.mode, mode))
+ print('Warning: Destination mode "%s" differs from specified '
+ 'mode "%s"' % (self.destination.mode, mode),
+ file=self._stderr)
if not destination_path:
try:
self.destination_path = self.destination.name
diff --git a/docutils/nodes.py b/docutils/nodes.py
index 9573208..8a5b7bb 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -19,6 +19,7 @@ hierarchy.
.. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd
"""
+from __future__ import print_function
__docformat__ = 'reStructuredText'
@@ -1724,7 +1725,7 @@ class system_message(Special, BackLinkable, PreBibliographic, Element):
try:
Element.__init__(self, rawsource, *children, **attributes)
except:
- print 'system_message: children=%r' % (children,)
+ print('system_message: children=%r' % (children,))
raise
def astext(self):
diff --git a/docutils/parsers/rst/directives/body.py b/docutils/parsers/rst/directives/body.py
index c8bf172..b60c3ad 100644
--- a/docutils/parsers/rst/directives/body.py
+++ b/docutils/parsers/rst/directives/body.py
@@ -11,13 +11,13 @@ See `docutils.parsers.rst.directives` for API details.
__docformat__ = 'reStructuredText'
-import sys
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
from docutils.parsers.rst.roles import set_classes
from docutils.utils.code_analyzer import Lexer, LexerError, NumberLines
+
class BasePseudoSection(Directive):
required_arguments = 1
@@ -167,7 +167,6 @@ class CodeBlock(Directive):
node.attributes['source'] = self.options['source']
# analyze content and add nodes for every token
for classes, value in tokens:
- # print (classes, value)
if classes:
node += nodes.inline(value, value, classes=classes)
else:
diff --git a/docutils/parsers/rst/roles.py b/docutils/parsers/rst/roles.py
index aa42c80..bf786b7 100644
--- a/docutils/parsers/rst/roles.py
+++ b/docutils/parsers/rst/roles.py
@@ -342,7 +342,6 @@ def code_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
# analyse content and add nodes for every token
for classes, value in tokens:
- # print (classes, value)
if classes:
node += nodes.inline(value, value, classes=classes)
else:
diff --git a/docutils/parsers/rst/states.py b/docutils/parsers/rst/states.py
index 2ece3b3..a2970c8 100644
--- a/docutils/parsers/rst/states.py
+++ b/docutils/parsers/rst/states.py
@@ -2758,8 +2758,8 @@ class Text(RSTState):
src, srcline = self.state_machine.get_source_and_line()
# TODO: why is abs_line_number() == srcline+1
# if the error is in a table (try with test_tables.py)?
- # print "get_source_and_line", srcline
- # print "abs_line_number", self.state_machine.abs_line_number()
+ # print("get_source_and_line", srcline)
+ # print("abs_line_number", self.state_machine.abs_line_number())
msg = self.reporter.severe('Unexpected section title.',
nodes.literal_block(blocktext, blocktext),
source=src, line=srcline)
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 2188982..6714a04 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -103,6 +103,7 @@ How To Use This Module
sm.unlink()
"""
+from __future__ import print_function
__docformat__ = 'restructuredtext'
@@ -213,15 +214,15 @@ class StateMachine(object):
self.line_offset = -1
self.current_state = initial_state or self.initial_state
if self.debug:
- print >>self._stderr, (
+ print((
u'\nStateMachine.run: input_lines (line_offset=%s):\n| %s'
- % (self.line_offset, u'\n| '.join(self.input_lines)))
+ % (self.line_offset, u'\n| '.join(self.input_lines))), file=self._stderr)
transitions = None
results = []
state = self.get_state()
try:
if self.debug:
- print >>self._stderr, '\nStateMachine.run: bof transition'
+ print('\nStateMachine.run: bof transition', file=self._stderr)
context, result = state.bof(context)
results.extend(result)
while True:
@@ -231,17 +232,17 @@ class StateMachine(object):
if self.debug:
source, offset = self.input_lines.info(
self.line_offset)
- print >>self._stderr, (
+ print((
u'\nStateMachine.run: line (source=%r, '
u'offset=%r):\n| %s'
- % (source, offset, self.line))
+ % (source, offset, self.line)), file=self._stderr)
context, next_state, result = self.check_line(
context, state, transitions)
except EOFError:
if self.debug:
- print >>self._stderr, (
+ print((
'\nStateMachine.run: %s.eof transition'
- % state.__class__.__name__)
+ % state.__class__.__name__), file=self._stderr)
result = state.eof(context)
results.extend(result)
break
@@ -251,10 +252,10 @@ class StateMachine(object):
self.previous_line() # back up for another try
transitions = (exception.args[0],)
if self.debug:
- print >>self._stderr, (
+ print((
'\nStateMachine.run: TransitionCorrection to '
'state "%s", transition %s.'
- % (state.__class__.__name__, transitions[0]))
+ % (state.__class__.__name__, transitions[0])), file=self._stderr)
continue
except StateCorrection, exception:
self.previous_line() # back up for another try
@@ -264,10 +265,10 @@ class StateMachine(object):
else:
transitions = (exception.args[1],)
if self.debug:
- print >>self._stderr, (
+ print((
'\nStateMachine.run: StateCorrection to state '
'"%s", transition %s.'
- % (next_state, transitions[0]))
+ % (next_state, transitions[0])), file=self._stderr)
else:
transitions = None
state = self.get_state(next_state)
@@ -288,11 +289,11 @@ class StateMachine(object):
"""
if next_state:
if self.debug and next_state != self.current_state:
- print >>self._stderr, (
+ print((
'\nStateMachine.get_state: Changing state from '
'"%s" to "%s" (input line %s).'
% (self.current_state, next_state,
- self.abs_line_number()))
+ self.abs_line_number())), file=self._stderr)
self.current_state = next_state
try:
return self.states[self.current_state]
@@ -382,15 +383,11 @@ class StateMachine(object):
# line is None if index is "Just past the end"
src, srcline = self.get_source_and_line(offset + self.input_offset)
return src, srcline + 1
- except (IndexError): # `offset` is off the list
+ except (IndexError): # `offset` is off the list
src, srcline = None, None
# raise AssertionError('cannot find line %d in %s lines' %
# (offset, len(self.input_lines)))
# # list(self.input_lines.lines())))
- # assert offset == srcoffset, str(self.input_lines)
- # print "get_source_and_line(%s):" % lineno,
- # print offset + 1, '->', src, srcline
- # print self.input_lines
return (src, srcline)
def insert_input(self, input_lines, source):
@@ -445,24 +442,24 @@ class StateMachine(object):
transitions = state.transition_order
state_correction = None
if self.debug:
- print >>self._stderr, (
+ print((
'\nStateMachine.check_line: state="%s", transitions=%r.'
- % (state.__class__.__name__, transitions))
+ % (state.__class__.__name__, transitions)), file=self._stderr)
for name in transitions:
pattern, method, next_state = state.transitions[name]
match = pattern.match(self.line)
if match:
if self.debug:
- print >>self._stderr, (
+ print((
'\nStateMachine.check_line: Matched transition '
'"%s" in state "%s".'
- % (name, state.__class__.__name__))
+ % (name, state.__class__.__name__)), file=self._stderr)
return method(match, context, next_state)
else:
if self.debug:
- print >>self._stderr, (
+ print((
'\nStateMachine.check_line: No match in state "%s".'
- % state.__class__.__name__)
+ % state.__class__.__name__), file=self._stderr)
return state.no_match(context, transitions)
def add_state(self, state_class):
@@ -494,10 +491,10 @@ class StateMachine(object):
def error(self):
"""Report error details."""
type, value, module, line, function = _exception_data()
- print >>self._stderr, u'%s: %s' % (type, value)
- print >>self._stderr, 'input line %s' % (self.abs_line_number())
- print >>self._stderr, (u'module %s, line %s, function %s' %
- (module, line, function))
+ print(u'%s: %s' % (type, value), file=self._stderr)
+ print('input line %s' % (self.abs_line_number()), file=self._stderr)
+ print((u'module %s, line %s, function %s' %
+ (module, line, function)), file=self._stderr)
def attach_observer(self, observer):
"""
@@ -1329,7 +1326,7 @@ class ViewList(object):
def pprint(self):
"""Print the list in `grep` format (`source:offset:value` lines)"""
for line in self.xitems():
- print "%s:%d:%s" % line
+ print("%s:%d:%s" % line)
class StringList(ViewList):
diff --git a/docutils/transforms/universal.py b/docutils/transforms/universal.py
index 3f8ddbc..47e1276 100644
--- a/docutils/transforms/universal.py
+++ b/docutils/transforms/universal.py
@@ -17,12 +17,12 @@ Transforms needed by most or all documents:
__docformat__ = 'reStructuredText'
import re
-import sys
import time
from docutils import nodes, utils
from docutils.transforms import TransformError, Transform
from docutils.utils import smartquotes
+
class Decorations(Transform):
"""
@@ -257,7 +257,6 @@ class SmartQuotes(Transform):
alternative = smart_quotes.startswith('alt')
except AttributeError:
alternative = False
- # print repr(alternative)
document_language = self.document.settings.language_code
lc_smartquotes = self.document.settings.smartquotes_locales
diff --git a/docutils/utils/__init__.py b/docutils/utils/__init__.py
index 7760f38..692335a 100644
--- a/docutils/utils/__init__.py
+++ b/docutils/utils/__init__.py
@@ -173,7 +173,6 @@ class Reporter(object):
if not 'source' in attributes: # 'line' is absolute line number
try: # look up (source, line-in-source)
source, line = self.get_source_and_line(attributes.get('line'))
- # print "locator lookup", kwargs.get('line'), "->", source, line
except AttributeError:
source, line = None, None
if source is not None:
diff --git a/docutils/utils/math/latex2mathml.py b/docutils/utils/math/latex2mathml.py
index 1a01bc8..255e96f 100644
--- a/docutils/utils/math/latex2mathml.py
+++ b/docutils/utils/math/latex2mathml.py
@@ -384,7 +384,6 @@ def parse_latex_math(string, inline=True):
c2 = string[1]
else:
c2 = ''
-## print n, string, c, c2, node.__class__.__name__
if c == ' ':
pass
elif c == '\\':
diff --git a/docutils/utils/math/tex2mathml_extern.py b/docutils/utils/math/tex2mathml_extern.py
index e461836..3e7f158 100644
--- a/docutils/utils/math/tex2mathml_extern.py
+++ b/docutils/utils/math/tex2mathml_extern.py
@@ -15,6 +15,7 @@
# Wrappers for TeX->MathML conversion by external tools
# =====================================================
+from __future__ import print_function
import subprocess
document_template = r"""\documentclass{article}
@@ -141,6 +142,6 @@ def blahtexml(math_code, inline=True, reporter=None):
if __name__ == "__main__":
example = ur'\frac{\partial \sin^2(\alpha)}{\partial \vec r} \varpi \, \text{Grüße}'
- # print latexml(example).encode('utf8')
- # print ttm(example)#.encode('utf8')
- print blahtexml(example).encode('utf8')
+ # print(latexml(example).encode('utf8'))
+ # print(ttm(example))
+ print(blahtexml(example).encode('utf8'))
diff --git a/docutils/utils/smartquotes.py b/docutils/utils/smartquotes.py
index ebf0240..148a4c9 100644
--- a/docutils/utils/smartquotes.py
+++ b/docutils/utils/smartquotes.py
@@ -315,6 +315,7 @@ Version History
1.5_1.0: Tue, 09 Mar 2004 08:08:35 -0500
- Initial release
"""
+from __future__ import print_function
options = r"""
Options
@@ -964,16 +965,16 @@ if __name__ == "__main__":
args = parser.parse_args()
if args.doc:
- print (__doc__)
+ print(__doc__)
elif args.actionhelp:
- print options
+ print(options)
elif args.stylehelp:
- print
- print "Available styles (primary open/close, secondary open/close)"
- print "language tag quotes"
- print "============ ======"
+ print()
+ print("Available styles (primary open/close, secondary open/close)")
+ print("language tag quotes")
+ print("============ ======")
for key in sorted(smartchars.quotes.keys()):
- print "%-14s %s" % (key, smartchars.quotes[key])
+ print("%-14s %s" % (key, smartchars.quotes[key]))
elif args.test:
# Unit test output goes to stderr.
import unittest
@@ -1006,5 +1007,5 @@ if __name__ == "__main__":
else:
args.language += '-x-altquot'
text = sys.stdin.read().decode(args.encoding)
- print smartyPants(text, attr=args.action,
- language=args.language).encode(args.encoding)
+ print(smartyPants(text, attr=args.action,
+ language=args.language).encode(args.encoding))
diff --git a/docutils/writers/_html_base.py b/docutils/writers/_html_base.py
index b357120..fa27911 100644
--- a/docutils/writers/_html_base.py
+++ b/docutils/writers/_html_base.py
@@ -494,7 +494,6 @@ class HTMLTranslator(nodes.NodeVisitor):
# the end of this file).
def is_compactable(self, node):
- # print "is_compactable %s ?" % node.__class__,
# explicite class arguments have precedence
if 'compact' in node['classes']:
return True
@@ -503,11 +502,9 @@ class HTMLTranslator(nodes.NodeVisitor):
# check config setting:
if (isinstance(node, (nodes.field_list, nodes.definition_list))
and not self.settings.compact_field_lists):
- # print "`compact-field-lists` is False"
return False
if (isinstance(node, (nodes.enumerated_list, nodes.bullet_list))
and not self.settings.compact_lists):
- # print "`compact-lists` is False"
return False
# more special cases:
if (self.topic_classes == ['contents']): # TODO: self.in_contents
@@ -882,7 +879,6 @@ class HTMLTranslator(nodes.NodeVisitor):
if 'sectnum' in node['classes']:
# get section number (strip trailing no-break-spaces)
sectnum = node.astext().rstrip(u' ')
- # print sectnum.encode('utf-8')
self.body.append('<span class="sectnum">%s</span> '
% self.encode(sectnum))
# Content already processed:
@@ -1194,7 +1190,6 @@ class HTMLTranslator(nodes.NodeVisitor):
pass # never reached
def visit_math_block(self, node):
- # print node.astext().encode('utf8')
math_env = pick_math_environment(node.astext())
self.visit_math(node, math_env=math_env)
@@ -1611,20 +1606,16 @@ class SimpleListChecker(nodes.GenericNodeVisitor):
raise nodes.NodeFound
def visit_list_item(self, node):
- # print "visiting list item", node.__class__
children = [child for child in node.children
if not isinstance(child, nodes.Invisible)]
- # print "has %s visible children" % len(children)
if (children and isinstance(children[0], nodes.paragraph)
and (isinstance(children[-1], nodes.bullet_list) or
isinstance(children[-1], nodes.enumerated_list) or
isinstance(children[-1], nodes.field_list))):
children.pop()
- # print "%s children remain" % len(children)
if len(children) <= 1:
return
else:
- # print "found", child.__class__, "in", node.__class__
raise nodes.NodeFound
def pass_node(self, node):
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index 2ee1270..5c33d0a 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -15,7 +15,6 @@ __docformat__ = 'reStructuredText'
import sys
import os
-import time
import re
import string
import urllib
@@ -28,6 +27,7 @@ from docutils.utils.error_reporting import SafeString
from docutils.transforms import writer_aux
from docutils.utils.math import pick_math_environment, unichar2tex
+
class Writer(writers.Writer):
supported = ('latex','latex2e')
@@ -2283,14 +2283,14 @@ class LaTeXTranslator(nodes.NodeVisitor):
href = self.document.nameids[node['refname']]
# if not self.docutils_footnotes:
# TODO: insert footnote content at (or near) this place
- # print "footnote-ref to", node['refid']
+ # print("footnote-ref to", node['refid'])
# footnotes = (self.document.footnotes +
# self.document.autofootnotes +
# self.document.symbol_footnotes)
# for footnote in footnotes:
- # # print footnote['ids']
+ # # print(footnote['ids'])
# if node.get('refid', '') in footnote['ids']:
- # print 'matches', footnote['ids']
+ # print('matches', footnote['ids'])
format = self.settings.footnote_references
if format == 'brackets':
self.append_hypertargets(node)
@@ -2623,7 +2623,6 @@ class LaTeXTranslator(nodes.NodeVisitor):
r'\begin{%s}' % math_env,
'%s',
r'\end{%s}' % math_env])
- # print repr(wrapper), repr(math_code)
self.out.append(wrapper % math_code)
if node['classes']:
self.depart_inline(node)
diff --git a/install.py b/install.py
index 2085627..b7de278 100755
--- a/install.py
+++ b/install.py
@@ -15,12 +15,13 @@ one of::
python setup.py install --help
python setup.py --help
"""
+from __future__ import print_function
from distutils import core
from setup import do_setup
-if __name__ == '__main__' :
- print __doc__
+if __name__ == '__main__':
+ print(__doc__)
core._setup_stop_after = 'config'
dist = do_setup()
dist.commands = ['install']
diff --git a/setup.py b/setup.py
index f801ea2..4280b98 100755
--- a/setup.py
+++ b/setup.py
@@ -2,9 +2,12 @@
# $Id: setup.py 8304 2019-07-30 09:51:07Z grubert $
# Copyright: This file has been placed in the public domain.
+from __future__ import print_function
+
import sys
import os
import glob
+
try:
import setuptools
from distutils.core import setup, Command
@@ -17,10 +20,10 @@ try:
from distutils.util import convert_path
from distutils import log
except ImportError:
- print ('Error: The "distutils" standard module, which is required for the ')
- print ('installation of Docutils, could not be found. You may need to ')
- print ('install a package called "python-devel" (or similar) on your ')
- print ('system using your package manager.')
+ print('Error: The "distutils" standard module, which is required for the ')
+ print('installation of Docutils, could not be found. You may need to ')
+ print('install a package called "python-devel" (or similar) on your ')
+ print('system using your package manager.')
sys.exit(1)
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index f7986f5..25196ec 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -38,6 +38,7 @@ Exports the following:
- `HtmlFragmentTestSuite`
- `DevNull` (output sink)
"""
+from __future__ import print_function
__docformat__ = 'reStructuredText'
import sys
@@ -230,17 +231,17 @@ class CustomTestCase(StandardTestCase):
try:
self.assertEqual(output, expected)
except AssertionError, error:
- print >>sys.stderr, '\n%s\ninput:' % (self,)
- print >>sys.stderr, input
+ print('\n%s\ninput:' % (self,), file=sys.stderr)
+ print(input, file=sys.stderr)
try:
comparison = ''.join(self.compare(expected.splitlines(1),
output.splitlines(1)))
- print >>sys.stderr, '-: expected\n+: output'
- print >>sys.stderr, comparison
+ print('-: expected\n+: output', file=sys.stderr)
+ print(comparison, file=sys.stderr)
except AttributeError: # expected or output not a string
# alternative output for non-strings:
- print >>sys.stderr, 'expected: %r' % expected
- print >>sys.stderr, 'output: %r' % output
+ print('expected: %r' % expected, file=sys.stderr)
+ print('output: %r' % output, file=sys.stderr)
raise error
@@ -375,20 +376,20 @@ class TransformTestCase(CustomTestCase):
def test_transforms_verbosely(self):
if self.run_in_debugger:
pdb.set_trace()
- print '\n', self.id
- print '-' * 70
- print self.input
+ print('\n', self.id)
+ print('-' * 70)
+ print(self.input)
settings = self.settings.copy()
settings.__dict__.update(self.suite_settings)
document = utils.new_document('test data', settings)
self.parser.parse(self.input, document)
- print '-' * 70
- print document.pformat()
+ print('-' * 70)
+ print(document.pformat())
for transformClass in self.transforms:
transformClass(document).apply()
output = document.pformat()
- print '-' * 70
- print output
+ print('-' * 70)
+ print(output)
self.compare_output(self.input, output, self.expected)
diff --git a/test/alltests.py b/test/alltests.py
index 9373124..364593f 100755
--- a/test/alltests.py
+++ b/test/alltests.py
@@ -1,12 +1,12 @@
#!/bin/sh
''''exec python -u "$0" "$@" #'''
+from __future__ import print_function
# $Id: alltests.py 8124 2017-06-23 02:29:16Z goodger $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
-__doc__ = \
-"""
+__doc__ = """\
All modules named 'test_*.py' in the current directory, and recursively in
subdirectories (packages) called 'test_*', are loaded and test suites within
are run.
@@ -15,7 +15,7 @@ are run.
import time
# Start point for actual elapsed time, including imports
# and setup outside of unittest.
-start = time.time()
+start = time.time() # noqa
import sys
import os
@@ -57,12 +57,13 @@ def pformat(suite):
if line[-1:] == '[':
indent += step
else:
- if line [-5:] == ']>]>,':
+ if line[-5:] == ']>]>,':
indent -= step * 2
elif line[-3:] == ']>,':
indent -= step
return '\n'.join(output)
+
def suite():
path, script = os.path.split(sys.argv[0])
suite = package_unittest.loadTestModules(DocutilsTestSupport.testroot,
@@ -70,26 +71,25 @@ def suite():
sys.stdout.flush()
return suite
+
# must redirect stderr *before* first import of unittest
sys.stdout = sys.stderr = Tee('alltests.out')
-import package_unittest
+import package_unittest # noqa
if __name__ == '__main__':
suite = suite()
- print ('Testing Docutils %s with Python %s on %s at %s'
- % (docutils.__version__, sys.version.split()[0],
- time.strftime('%Y-%m-%d'), time.strftime('%H:%M:%S')))
- print ('OS: %s %s %s (%s, %s)'
- % (platform.system(), platform.release(), platform.version(),
- sys.platform, platform.platform()))
- print 'Working directory: %s' % os.getcwd()
- print 'Docutils package: %s' % os.path.dirname(docutils.__file__)
+ print('Testing Docutils %s with Python %s on %s at %s' % (
+ docutils.__version__, sys.version.split()[0],
+ time.strftime('%Y-%m-%d'), time.strftime('%H:%M:%S')))
+ print('OS: %s %s %s (%s, %s)' % (
+ platform.system(), platform.release(), platform.version(),
+ sys.platform, platform.platform()))
+ print('Working directory: %s' % os.getcwd())
+ print('Docutils package: %s' % os.path.dirname(docutils.__file__))
sys.stdout.flush()
result = package_unittest.main(suite)
- #if package_unittest.verbosity > 1:
- # print >>sys.stderr, pformat(suite) # check the test suite
finish = time.time()
- print 'Elapsed time: %.3f seconds' % (finish - start)
+ print('Elapsed time: %.3f seconds' % (finish - start))
sys.exit(not result.wasSuccessful())
diff --git a/test/package_unittest.py b/test/package_unittest.py
index 0efab12..daf11f4 100644
--- a/test/package_unittest.py
+++ b/test/package_unittest.py
@@ -9,6 +9,7 @@ This module extends unittest.py with `loadTestModules()`, by loading multiple
test modules from a directory. Optionally, test packages are also loaded,
recursively.
"""
+from __future__ import print_function
import sys
import os
@@ -37,8 +38,8 @@ Options:
def usageExit(msg=None):
"""Print usage and exit."""
if msg:
- print msg
- print USAGE
+ print(msg)
+ print(USAGE)
sys.exit(2)
def parseArgs(argv=sys.argv):
@@ -96,11 +97,11 @@ def loadTestModules(path, name='', packages=None):
sys.path.insert(0, path)
for mod in testModules:
if debug:
- print >>sys.stderr, "importing %s" % mod
+ print("importing %s" % mod, file=sys.stderr)
try:
module = import_module(mod)
except ImportError:
- print >>sys.stderr, "ERROR: Can't import %s, skipping its tests:" % mod
+ print("ERROR: Can't import %s, skipping its tests:" % mod, file=sys.stderr)
sys.excepthook(*sys.exc_info())
else:
# if there's a suite defined, incorporate its contents
@@ -148,7 +149,7 @@ def main(suite=None):
suite = unittest.defaultTestLoader.loadTestsFromModule(
__import__('__main__'))
if debug:
- print >>sys.stderr, "Debug: Suite=%s" % suite
+ print("Debug: Suite=%s" % suite, file=sys.stderr)
testRunner = unittest.TextTestRunner(verbosity=verbosity)
# run suites (if we were called from test_all) or suite...
if type(suite) == type([]):
diff --git a/test/test_error_reporting.py b/test/test_error_reporting.py
index 902e878..c4eae40 100644
--- a/test/test_error_reporting.py
+++ b/test/test_error_reporting.py
@@ -20,13 +20,14 @@ instances like, e.g., ::
try:
something
except IOError, error:
- print 'Found %s' % error
+ print('Found %s' % error)
unless the minimal required Python version has this problem fixed.
"""
import unittest
-import sys, os
+import sys
+import os
import codecs
from io import StringIO, BytesIO
@@ -42,7 +43,7 @@ if sys.version_info < (3,0): # problems solved in py3k
# Why does getlocale return the defaultlocale in Python 3.2 ????
# oldlocale = (None, None) # test suite runs without locale
except ImportError:
- print ('cannot test error reporting with problematic locales,\n'
+ print('cannot test error reporting with problematic locales,\n'
'`import locale` failed.')
diff --git a/test/test_functional.py b/test/test_functional.py
index 43710de..5d3beb9 100755
--- a/test/test_functional.py
+++ b/test/test_functional.py
@@ -9,6 +9,7 @@ Perform tests with the data in the functional/ directory.
Read README.txt for details on how this is done.
"""
+from __future__ import print_function
import sys
import os
@@ -194,8 +195,8 @@ expected output and check it in:
expected_path, params['destination_path']))
if sys.version_info < (3,0):
diff = diff.encode(sys.stderr.encoding or 'ascii', 'replace')
- print >>sys.stderr, '\n%s:' % (self,)
- print >>sys.stderr, diff
+ print('\n%s:' % (self,), file=sys.stderr)
+ print(diff, file=sys.stderr)
raise
# Execute optional function containing extra tests:
if '_test_more' in namespace:
diff --git a/test/test_io.py b/test/test_io.py
index 6ea4789..737a19d 100755
--- a/test/test_io.py
+++ b/test/test_io.py
@@ -69,7 +69,7 @@ blah
input = io.StringInput(source=b"""\
#! python
# -*- coding: ascii -*-
-print "hello world"
+print("hello world")
""")
data = input.read()
self.assertEqual(input.successful_encoding, 'ascii')
@@ -77,7 +77,7 @@ print "hello world"
#! python
# extraneous comment; prevents coding slug from being read
# -*- coding: ascii -*-
-print "hello world"
+print("hello world")
""")
data = input.read()
self.assertNotEqual(input.successful_encoding, 'ascii')
diff --git a/test/test_parsers/test_rst/test_directives/test_code.py b/test/test_parsers/test_rst/test_directives/test_code.py
index 30fe74f..51c1558 100644
--- a/test/test_parsers/test_rst/test_directives/test_code.py
+++ b/test/test_parsers/test_rst/test_directives/test_code.py
@@ -98,7 +98,7 @@ totest['code-parsing'] = [
.. code:: python
:class: testclass
- print 'hello world' # to stdout
+ print('hello world') # to stdout
""",
"""\
<document source="test data">
@@ -106,9 +106,12 @@ totest['code-parsing'] = [
\n\
<inline classes="keyword">
print
- \n\
+ <inline classes="punctuation">
+ (
<inline classes="literal string single">
'hello world'
+ <inline classes="punctuation">
+ )
\n\
<inline classes="comment single">
# to stdout
@@ -124,7 +127,7 @@ totest['code-parsing'] = [
'''
# and now for something completely different
- print 8/2
+ print(8/2)
""",
"""\
<document source="test data">
@@ -163,13 +166,16 @@ totest['code-parsing'] = [
\n\
<inline classes="keyword">
print
- \n\
+ <inline classes="punctuation">
+ (
<inline classes="literal number integer">
8
<inline classes="operator">
/
<inline classes="literal number integer">
2
+ <inline classes="punctuation">
+ )
"""],
["""\
.. code:: latex
diff --git a/test/test_parsers/test_rst/test_directives/test_code_long.py b/test/test_parsers/test_rst/test_directives/test_code_long.py
index 43eb886..74f16d5 100644
--- a/test/test_parsers/test_rst/test_directives/test_code_long.py
+++ b/test/test_parsers/test_rst/test_directives/test_code_long.py
@@ -29,7 +29,7 @@ totest['code-parsing-long'] = [
'''
# and now for something completely different
- print 8/2
+ print(8/2)
""",
"""\
<document source="test data">
@@ -68,13 +68,16 @@ totest['code-parsing-long'] = [
\n\
<inline classes="keyword">
print
- \n\
+ <inline classes="punctuation">
+ (
<inline classes="literal number integer">
8
<inline classes="operator">
/
<inline classes="literal number integer">
2
+ <inline classes="punctuation">
+ )
"""],
["""\
.. code:: latex
diff --git a/test/test_parsers/test_rst/test_directives/test_code_none.py b/test/test_parsers/test_rst/test_directives/test_code_none.py
index 86653e6..515772c 100644
--- a/test/test_parsers/test_rst/test_directives/test_code_none.py
+++ b/test/test_parsers/test_rst/test_directives/test_code_none.py
@@ -37,7 +37,7 @@ totest['code-parsing-none'] = [
'''
# and now for something completely different
- print 8/2
+ print(8/2)
""",
"""\
<document source="test data">
@@ -59,7 +59,7 @@ totest['code-parsing-none'] = [
# and now for something completely different
<inline classes="ln">
12 \n\
- print 8/2
+ print(8/2)
"""],
["""\
.. code:: latex
diff --git a/test/test_parsers/test_rst/test_doctest_blocks.py b/test/test_parsers/test_rst/test_doctest_blocks.py
index dabc2ec..4f367db 100755
--- a/test/test_parsers/test_rst/test_doctest_blocks.py
+++ b/test/test_parsers/test_rst/test_doctest_blocks.py
@@ -21,7 +21,7 @@ totest['doctest_blocks'] = [
["""\
Paragraph.
->>> print "Doctest block."
+>>> print("Doctest block.")
Doctest block.
Paragraph.
@@ -31,7 +31,7 @@ Paragraph.
<paragraph>
Paragraph.
<doctest_block xml:space="preserve">
- >>> print "Doctest block."
+ >>> print("Doctest block.")
Doctest block.
<paragraph>
Paragraph.
@@ -39,7 +39,7 @@ Paragraph.
["""\
Paragraph.
->>> print " Indented output."
+>>> print(" Indented output.")
Indented output.
""",
"""\
@@ -47,13 +47,13 @@ Paragraph.
<paragraph>
Paragraph.
<doctest_block xml:space="preserve">
- >>> print " Indented output."
+ >>> print(" Indented output.")
Indented output.
"""],
["""\
Paragraph.
- >>> print " Indented block & output."
+ >>> print(" Indented block & output.")
Indented block & output.
""",
"""\
@@ -62,7 +62,7 @@ Paragraph.
Paragraph.
<block_quote>
<doctest_block xml:space="preserve">
- >>> print " Indented block & output."
+ >>> print(" Indented block & output.")
Indented block & output.
"""],
]
diff --git a/test/test_settings.py b/test/test_settings.py
index 5b687eb..d101a59 100755
--- a/test/test_settings.py
+++ b/test/test_settings.py
@@ -8,6 +8,7 @@
"""
Tests of runtime settings.
"""
+from __future__ import print_function
import sys
import os
@@ -111,10 +112,10 @@ class ConfigFileTests(unittest.TestCase):
try:
self.assertEqual(result, expected)
except AssertionError:
- print >>sys.stderr, '\n%s\n' % (self,)
- print >>sys.stderr, '-: expected\n+: result'
- print >>sys.stderr, ''.join(self.compare(expected.splitlines(1),
- result.splitlines(1)))
+ print('\n%s\n' % (self,), file=sys.stderr)
+ print('-: expected\n+: result', file=sys.stderr)
+ print(''.join(self.compare(expected.splitlines(1),
+ result.splitlines(1))), file=sys.stderr)
raise
def test_nofiles(self):
diff --git a/test/test_statemachine.py b/test/test_statemachine.py
index 07c561e..6352ca4 100755
--- a/test/test_statemachine.py
+++ b/test/test_statemachine.py
@@ -7,6 +7,7 @@
"""
Test module for statemachine.py.
"""
+from __future__ import print_function
import unittest
import sys
@@ -56,47 +57,47 @@ class MockState(statemachine.StateWS):
def bof(self, context):
self.levelholder[0] += 1
self.level = self.levelholder[0]
- if self.debug: print >>sys.stderr, 'StateMachine%s' % self.level
+ if self.debug: print('StateMachine%s' % self.level, file=sys.stderr)
return [], ['StateMachine%s' % self.level]
def blank(self, match, context, next_state):
result = ['blank%s' % self.level]
- if self.debug: print >>sys.stderr, 'blank%s' % self.level
+ if self.debug: print('blank%s' % self.level, file=sys.stderr)
if context and context[-1] and context[-1][-2:] == '::':
result.extend(self.literalblock())
return [], None, result
def indent(self, match, context, next_state):
- if self.debug: print >>sys.stderr, 'indent%s' % self.level
+ if self.debug: print('indent%s' % self.level, file=sys.stderr)
context, next_state, result = statemachine.StateWS.indent(
self, match, context, next_state)
return context, next_state, ['indent%s' % self.level] + result
def known_indent(self, match, context, next_state):
- if self.debug: print >>sys.stderr, 'known_indent%s' % self.level
+ if self.debug: print('known_indent%s' % self.level, file=sys.stderr)
context, next_state, result = statemachine.StateWS.known_indent(
self, match, context, next_state)
return context, next_state, ['known_indent%s' % self.level] + result
def bullet(self, match, context, next_state):
- if self.debug: print >>sys.stderr, 'bullet%s' % self.level
+ if self.debug: print('bullet%s' % self.level, file=sys.stderr)
context, next_state, result \
= self.known_indent(match, context, next_state)
return [], next_state, ['bullet%s' % self.level] + result
def text(self, match, context, next_state):
- if self.debug: print >>sys.stderr, 'text%s' % self.level
+ if self.debug: print('text%s' % self.level, file=sys.stderr)
return [match.string], next_state, ['text%s' % self.level]
def literalblock(self):
indented, indent, offset, good = self.state_machine.get_indented()
- if self.debug: print >>sys.stderr, 'literalblock%s(%s)' % (self.level,
- indent)
+ if self.debug: print('literalblock%s(%s)' % (self.level,
+ indent), file=sys.stderr)
return ['literalblock%s(%s)' % (self.level, indent)]
def eof(self, context):
self.levelholder[0] -= 1
- if self.debug: print >>sys.stderr, 'finished%s' % self.level
+ if self.debug: print('finished%s' % self.level, file=sys.stderr)
return ['finished%s' % self.level]
@@ -169,10 +170,10 @@ class SMWSTests(unittest.TestCase):
self.assertTrue(good)
self.sm.previous_line(3)
if self.sm.debug:
- print '\ntest_get_indented: self.sm.line:\n', self.sm.line
+ print('\ntest_get_indented: self.sm.line:\n', self.sm.line)
indented, indent, offset, good = self.sm.get_indented()
if self.sm.debug:
- print '\ntest_get_indented: indented:\n', indented
+ print('\ntest_get_indented: indented:\n', indented)
self.assertEqual(indent, lbindent)
self.assertEqual(indented, literalblock)
self.assertEqual(offset, (len(para1) + len(item1) + len(item2)
diff --git a/test/test_transforms/test_smartquotes.py b/test/test_transforms/test_smartquotes.py
index fb46b30..e2874c0 100644
--- a/test/test_transforms/test_smartquotes.py
+++ b/test/test_transforms/test_smartquotes.py
@@ -18,7 +18,7 @@ Test module for universal.SmartQuotes transform.
"""
-from __init__ import DocutilsTestSupport # must be imported before docutils
+from __init__ import DocutilsTestSupport # must be imported before docutils
from docutils.transforms.universal import SmartQuotes
from docutils.parsers.rst import Parser
@@ -69,11 +69,11 @@ Do not "educate" quotes ``inside "literal" text`` and ::
"literal" blocks.
Keep quotes straight in code and math:
-:code:`print "hello"` :math:`1' 12"`.
+:code:`print("hello")` :math:`1' 12"`.
.. code::
- print "hello"
+ print("hello")
.. math::
@@ -92,13 +92,13 @@ u"""\
<paragraph>
Keep quotes straight in code and math:
<literal classes="code">
- print "hello"
+ print("hello")
<math>
1' 12"
.
<literal_block classes="code" xml:space="preserve">
- print "hello"
+ print("hello")
<math_block xml:space="preserve">
f'(x) = df(x)/dx
"""],
diff --git a/test/test_transforms/test_strip_elements_with_class.py b/test/test_transforms/test_strip_elements_with_class.py
index 7a36fb9..6503586 100644
--- a/test/test_transforms/test_strip_elements_with_class.py
+++ b/test/test_transforms/test_strip_elements_with_class.py
@@ -37,7 +37,7 @@ this is ham
.. code::
:class: spam
- print "spam"
+ print("spam")
.. image:: spam.jpg
:class: spam
diff --git a/test/test_viewlist.py b/test/test_viewlist.py
index 23ba033..f5df548 100755
--- a/test/test_viewlist.py
+++ b/test/test_viewlist.py
@@ -9,8 +9,6 @@ Test module for the ViewList class from statemachine.py.
"""
import unittest
-import sys
-import re
from DocutilsTestSupport import statemachine
@@ -76,7 +74,6 @@ class ViewListTests(unittest.TestCase):
self.assertEqual(a, a_list)
self.assertEqual(a.items, [('a', i+1) for (i, v) in enumerate(a_list)])
self.assertEqual(a.parent, self.a)
- # a.pprint()
def test_set_slice(self):
a = statemachine.ViewList(self.a[:])
@@ -84,8 +81,6 @@ class ViewListTests(unittest.TestCase):
s[2:2] = self.b
s_list = self.a_list[2:-2]
s_list[2:2] = self.b_list
- # s.pprint()
- # s[1:4].pprint()
self.assertEqual(s, s_list)
self.assertEqual(s, a[2:-2])
self.assertEqual(s.items, a[2:-2].items)
@@ -119,7 +114,6 @@ class ViewListTests(unittest.TestCase):
a = statemachine.ViewList(self.a)
a.append('Q', 'runtime')
a.append(self.b)
- # a.pprint()
self.assertEqual(a, a_list)
self.assertEqual(a.info(len(self.a)), ('runtime', 0))
self.assertEqual(a.info(-2), ('b', len(self.b) - 2))
@@ -131,7 +125,6 @@ class ViewListTests(unittest.TestCase):
a.extend(self.b)
self.assertEqual(a, a_list)
self.assertEqual(a.info(len(self.a) + 1), ('b', 1))
- # a.pprint()
def test_view(self):
a = statemachine.ViewList(self.a[:])
@@ -176,16 +169,9 @@ class ViewListTests(unittest.TestCase):
def test_sort(self):
c = self.c[:]
c.reverse()
- # c.pprint()
c.sort()
self.assertEqual(self.c, c)
-# print
-# print a
-# print s
-# print a.items
-# print s.items
-
class StringList(unittest.TestCase):
diff --git a/tools/dev/create_unimap.py b/tools/dev/create_unimap.py
index a1d92ac..85ac264 100755
--- a/tools/dev/create_unimap.py
+++ b/tools/dev/create_unimap.py
@@ -9,6 +9,7 @@
# Get unicode.xml from
# <http://www.w3.org/2003/entities/xml/unicode.xml>.
+from __future__ import print_function
from xml.dom import minidom
import sys
import pprint
diff --git a/tools/dev/generate_punctuation_chars.py b/tools/dev/generate_punctuation_chars.py
index e05515d..5947fe5 100644
--- a/tools/dev/generate_punctuation_chars.py
+++ b/tools/dev/generate_punctuation_chars.py
@@ -33,14 +33,13 @@
# .. _inline markup recognition rules:
# ../../docs/ref/rst/restructuredtext.html#inline-markup
+from __future__ import print_function
-# Setup::
-
-import sys, re
+import sys
import unicodedata
if sys.version_info >= (3,):
- unichr = chr # unichr not available in Py3k
+ unichr = chr # unichr not available in Py3k
else:
import codecs
sys.stdout = codecs.getwriter('UTF-8')(sys.stdout)
@@ -421,44 +420,3 @@ if __name__ == '__main__':
}
print(module_template % substitutions)
-
-
-# test prints
-# ~~~~~~~~~~~
-#
-# For interactive use in development you may uncomment the following
-# definitions::
-
- # print "wide" Unicode characters:
- # ucharlists = unicode_charlists(unicode_punctuation_categories)
- # for key in ucharlists:
- # if key.endswith('wide'):
- # print key, ucharlists[key]
-
- # print 'openers = ', repr(openers)
- # print 'closers = ', repr(closers)
- # print 'delimiters = ', repr(delimiters)
- # print 'closing_delimiters = ', repr(closing_delimiters)
-
- # ucharlists = unicode_charlists(unicode_punctuation_categories)
- # for cat, chars in ucharlists.items():
- # # print cat, chars
- # # compact output (visible with a comprehensive font):
- # print (u":%s: %s" % (cat, u''.join(chars))).encode('utf8')
-
-# verbose print
-#
-# ::
-
- # print 'openers:'
- # for ch in openers:
- # print ch.encode('utf8'), unicodedata.name(ch)
- # print 'closers:'
- # for ch in closers:
- # print ch.encode('utf8'), unicodedata.name(ch)
- # print 'delimiters:'
- # for ch in delimiters:
- # print ch.encode('utf8'), unicodedata.name(ch)
- # print 'closing_delimiters:'
- # for ch in closing_delimiters:
- # print ch.encode('utf8'), unicodedata.name(ch)
diff --git a/tools/dev/profile_docutils.py b/tools/dev/profile_docutils.py
index 1f43ecc..4b9125d 100755
--- a/tools/dev/profile_docutils.py
+++ b/tools/dev/profile_docutils.py
@@ -4,6 +4,7 @@
# Author: Lea Wiemann <LeWiemann@gmail.com>
# Copyright: This script has been placed in the public domain.
+from __future__ import print_function
import os.path
import docutils.core
import hotshot.stats
diff --git a/tools/dev/unicode2rstsubs.py b/tools/dev/unicode2rstsubs.py
index d719005..b51eec4 100755
--- a/tools/dev/unicode2rstsubs.py
+++ b/tools/dev/unicode2rstsubs.py
@@ -19,6 +19,7 @@ The input file, unicode.xml, is maintained as part of the MathML 2
Recommentation XML source, and is available from
<http://www.w3.org/2003/entities/xml/>.
"""
+from __future__ import print_function
import sys
import os
diff --git a/tools/quicktest.py b/tools/quicktest.py
index 4ddbe59..3b6b6b4 100755
--- a/tools/quicktest.py
+++ b/tools/quicktest.py
@@ -5,6 +5,7 @@
# David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
+from __future__ import print_function
try:
import locale
locale.setlocale(locale.LC_ALL, '')
diff --git a/tools/rst2odt_prepstyles.py b/tools/rst2odt_prepstyles.py
index b0b7dcc..67f8942 100755
--- a/tools/rst2odt_prepstyles.py
+++ b/tools/rst2odt_prepstyles.py
@@ -9,9 +9,10 @@ Fix a word-processor-generated styles.odt for odtwriter use: Drop page size
specifications from styles.xml in STYLE_FILE.odt.
"""
-#
# Author: Michael Schutte <michi@uiae.at>
+from __future__ import print_function
+
from lxml import etree
import sys
import zipfile
@@ -24,28 +25,29 @@ NAMESPACES = {
"fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
}
+
def prepstyle(filename):
-
+
zin = zipfile.ZipFile(filename)
styles = zin.read("styles.xml")
-
+
root = etree.fromstring(styles)
- for el in root.xpath("//style:page-layout-properties",
- namespaces=NAMESPACES):
+ for el in root.xpath("//style:page-layout-properties",
+ namespaces=NAMESPACES):
for attr in el.attrib:
if attr.startswith("{%s}" % NAMESPACES["fo"]):
del el.attrib[attr]
-
+
tempname = mkstemp()
zout = zipfile.ZipFile(os.fdopen(tempname[0], "w"), "w",
- zipfile.ZIP_DEFLATED)
-
+ zipfile.ZIP_DEFLATED)
+
for item in zin.infolist():
if item.filename == "styles.xml":
zout.writestr(item, etree.tostring(root))
else:
zout.writestr(item, zin.read(item.filename))
-
+
zout.close()
zin.close()
shutil.move(tempname[1], filename)
@@ -54,14 +56,12 @@ def prepstyle(filename):
def main():
args = sys.argv[1:]
if len(args) != 1:
- print >> sys.stderr, __doc__
- print >> sys.stderr, "Usage: %s STYLE_FILE.odt\n" % sys.argv[0]
+ print(__doc__, file=sys.stderr)
+ print("Usage: %s STYLE_FILE.odt\n" % sys.argv[0], file=sys.stderr)
sys.exit(1)
filename = args[0]
prepstyle(filename)
+
if __name__ == '__main__':
main()
-
-
-# vim:tw=78:sw=4:sts=4:et:
--
2.24.0.375.geb5ae68d41