This commit is contained in:
Dmitry Shachnev 2014-01-22 18:34:51 +04:00
commit 953b33d3f7
65 changed files with 427 additions and 371 deletions

View File

@ -14,6 +14,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import sys import sys
import optparse import optparse
@ -50,12 +51,12 @@ def write_file(name, text, opts):
"""Write the output file for module/package <name>.""" """Write the output file for module/package <name>."""
fname = path.join(opts.destdir, '%s.%s' % (name, opts.suffix)) fname = path.join(opts.destdir, '%s.%s' % (name, opts.suffix))
if opts.dryrun: if opts.dryrun:
print 'Would create file %s.' % fname print('Would create file %s.' % fname)
return return
if not opts.force and path.isfile(fname): if not opts.force and path.isfile(fname):
print 'File %s already exists, skipping.' % fname print('File %s already exists, skipping.' % fname)
else: else:
print 'Creating file %s.' % fname print('Creating file %s.' % fname)
f = open(fname, 'w') f = open(fname, 'w')
try: try:
f.write(text) f.write(text)
@ -312,7 +313,7 @@ Note: By default this script will not overwrite already created files.""")
if opts.suffix.startswith('.'): if opts.suffix.startswith('.'):
opts.suffix = opts.suffix[1:] opts.suffix = opts.suffix[1:]
if not path.isdir(rootpath): if not path.isdir(rootpath):
print >>sys.stderr, '%s is not a directory.' % rootpath print('%s is not a directory.' % rootpath, file=sys.stderr)
sys.exit(1) sys.exit(1)
if not path.isdir(opts.destdir): if not path.isdir(opts.destdir):
if not opts.dryrun: if not opts.dryrun:

View File

@ -10,6 +10,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import sys import sys
@ -38,6 +39,8 @@ from sphinx.util.tags import Tags
from sphinx.util.osutil import ENOENT from sphinx.util.osutil import ENOENT
from sphinx.util.console import bold, lightgray, darkgray from sphinx.util.console import bold, lightgray, darkgray
if hasattr(sys, 'intern'):
intern = sys.intern
# List of all known core events. Maps name to arguments description. # List of all known core events. Maps name to arguments description.
events = { events = {
@ -174,7 +177,7 @@ class Sphinx(object):
# this can raise if the data version doesn't fit # this can raise if the data version doesn't fit
self.env.domains[domain] = self.domains[domain](self.env) self.env.domains[domain] = self.domains[domain](self.env)
self.info('done') self.info('done')
except Exception, err: except Exception as err:
if type(err) is IOError and err.errno == ENOENT: if type(err) is IOError and err.errno == ENOENT:
self.info('not yet created') self.info('not yet created')
else: else:
@ -185,7 +188,7 @@ class Sphinx(object):
def _init_builder(self, buildername): def _init_builder(self, buildername):
if buildername is None: if buildername is None:
print >>self._status, 'No builder selected, using default: html' print('No builder selected, using default: html', file=self._status)
buildername = 'html' buildername = 'html'
if buildername not in self.builderclasses: if buildername not in self.builderclasses:
raise SphinxError('Builder name %s not registered' % buildername) raise SphinxError('Builder name %s not registered' % buildername)
@ -209,7 +212,7 @@ class Sphinx(object):
self.builder.build_specific(filenames) self.builder.build_specific(filenames)
else: else:
self.builder.build_update() self.builder.build_update()
except Exception, err: except Exception as err:
# delete the saved env to force a fresh build next time # delete the saved env to force a fresh build next time
envfile = path.join(self.doctreedir, ENV_PICKLE_FILENAME) envfile = path.join(self.doctreedir, ENV_PICKLE_FILENAME)
if path.isfile(envfile): if path.isfile(envfile):
@ -320,7 +323,7 @@ class Sphinx(object):
return return
try: try:
mod = __import__(extension, None, None, ['setup']) mod = __import__(extension, None, None, ['setup'])
except ImportError, err: except ImportError as err:
self.verbose('Original exception:\n' + traceback.format_exc()) self.verbose('Original exception:\n' + traceback.format_exc())
raise ExtensionError('Could not import extension %s' % extension, raise ExtensionError('Could not import extension %s' % extension,
err) err)
@ -330,7 +333,7 @@ class Sphinx(object):
else: else:
try: try:
mod.setup(self) mod.setup(self)
except VersionRequirementError, err: except VersionRequirementError as err:
# add the extension name to the version required # add the extension name to the version required
raise VersionRequirementError( raise VersionRequirementError(
'The %s extension used by this project needs at least ' 'The %s extension used by this project needs at least '
@ -347,17 +350,17 @@ class Sphinx(object):
"""Import an object from a 'module.name' string.""" """Import an object from a 'module.name' string."""
try: try:
module, name = objname.rsplit('.', 1) module, name = objname.rsplit('.', 1)
except ValueError, err: except ValueError as err:
raise ExtensionError('Invalid full object name %s' % objname + raise ExtensionError('Invalid full object name %s' % objname +
(source and ' (needed for %s)' % source or ''), (source and ' (needed for %s)' % source or ''),
err) err)
try: try:
return getattr(__import__(module, None, None, [name]), name) return getattr(__import__(module, None, None, [name]), name)
except ImportError, err: except ImportError as err:
raise ExtensionError('Could not import %s' % module + raise ExtensionError('Could not import %s' % module +
(source and ' (needed for %s)' % source or ''), (source and ' (needed for %s)' % source or ''),
err) err)
except AttributeError, err: except AttributeError as err:
raise ExtensionError('Could not find %s' % objname + raise ExtensionError('Could not find %s' % objname +
(source and ' (needed for %s)' % source or ''), (source and ' (needed for %s)' % source or ''),
err) err)

View File

@ -94,7 +94,7 @@ class DevhelpBuilder(StandaloneHTMLBuilder):
def istoctree(node): def istoctree(node):
return isinstance(node, addnodes.compact_paragraph) and \ return isinstance(node, addnodes.compact_paragraph) and \
node.has_key('toctree') 'toctree' in node
for node in tocdoc.traverse(istoctree): for node in tocdoc.traverse(istoctree):
write_toc(node, chapters) write_toc(node, chapters)

View File

@ -218,7 +218,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
"""Collect section titles, their depth in the toc and the refuri.""" """Collect section titles, their depth in the toc and the refuri."""
# XXX: is there a better way than checking the attribute # XXX: is there a better way than checking the attribute
# toctree-l[1-8] on the parent node? # toctree-l[1-8] on the parent node?
if isinstance(doctree, nodes.reference) and doctree.has_key('refuri'): if isinstance(doctree, nodes.reference) and 'refuri' in doctree:
refuri = doctree['refuri'] refuri = doctree['refuri']
if refuri.startswith('http://') or refuri.startswith('https://') \ if refuri.startswith('http://') or refuri.startswith('https://') \
or refuri.startswith('irc:') or refuri.startswith('mailto:'): or refuri.startswith('irc:') or refuri.startswith('mailto:'):
@ -417,7 +417,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
try: try:
copyfile(path.join(self.srcdir, src), copyfile(path.join(self.srcdir, src),
path.join(self.outdir, '_images', dest)) path.join(self.outdir, '_images', dest))
except (IOError, OSError), err: except (IOError, OSError) as err:
self.warn('cannot copy image file %r: %s' % self.warn('cannot copy image file %r: %s' %
(path.join(self.srcdir, src), err)) (path.join(self.srcdir, src), err))
continue continue
@ -433,7 +433,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
img = img.resize((nw, nh), Image.BICUBIC) img = img.resize((nw, nh), Image.BICUBIC)
try: try:
img.save(path.join(self.outdir, '_images', dest)) img.save(path.join(self.outdir, '_images', dest))
except (IOError, OSError), err: except (IOError, OSError) as err:
self.warn('cannot write image file %r: %s' % self.warn('cannot write image file %r: %s' %
(path.join(self.srcdir, src), err)) (path.join(self.srcdir, src), err))
@ -489,7 +489,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
fn = path.join(outdir, outname) fn = path.join(outdir, outname)
try: try:
os.mkdir(path.dirname(fn)) os.mkdir(path.dirname(fn))
except OSError, err: except OSError as err:
if err.errno != EEXIST: if err.errno != EEXIST:
raise raise
f = codecs.open(path.join(outdir, outname), 'w', 'utf-8') f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')

View File

@ -184,7 +184,7 @@ class MessageCatalogBuilder(I18nBuilder):
for textdomain, catalog in self.status_iterator( for textdomain, catalog in self.status_iterator(
self.catalogs.iteritems(), "writing message catalogs... ", self.catalogs.iteritems(), "writing message catalogs... ",
darkgreen, len(self.catalogs), darkgreen, len(self.catalogs),
lambda (textdomain, _): textdomain): lambda textdomain__: textdomain__[0]):
# noop if config.gettext_compact is set # noop if config.gettext_compact is set
ensuredir(path.join(self.outdir, path.dirname(textdomain))) ensuredir(path.join(self.outdir, path.dirname(textdomain)))

View File

@ -531,7 +531,7 @@ class StandaloneHTMLBuilder(Builder):
try: try:
copyfile(path.join(self.srcdir, src), copyfile(path.join(self.srcdir, src),
path.join(self.outdir, '_images', dest)) path.join(self.outdir, '_images', dest))
except Exception, err: except Exception as err:
self.warn('cannot copy image file %r: %s' % self.warn('cannot copy image file %r: %s' %
(path.join(self.srcdir, src), err)) (path.join(self.srcdir, src), err))
@ -546,7 +546,7 @@ class StandaloneHTMLBuilder(Builder):
try: try:
copyfile(path.join(self.srcdir, src), copyfile(path.join(self.srcdir, src),
path.join(self.outdir, '_downloads', dest)) path.join(self.outdir, '_downloads', dest))
except Exception, err: except Exception as err:
self.warn('cannot copy downloadable file %r: %s' % self.warn('cannot copy downloadable file %r: %s' %
(path.join(self.srcdir, src), err)) (path.join(self.srcdir, src), err))
@ -775,7 +775,7 @@ class StandaloneHTMLBuilder(Builder):
f.write(output) f.write(output)
finally: finally:
f.close() f.close()
except (IOError, OSError), err: except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err)) self.warn("error writing file %s: %s" % (outfilename, err))
if self.copysource and ctx.get('sourcename'): if self.copysource and ctx.get('sourcename'):
# copy the source file for the "show source" link # copy the source file for the "show source" link

View File

@ -9,6 +9,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import codecs import codecs
@ -197,7 +198,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
f = self.open_file(outdir, outname+'.stp') f = self.open_file(outdir, outname+'.stp')
try: try:
for word in sorted(stopwords): for word in sorted(stopwords):
print >>f, word print(word, file=f)
finally: finally:
f.close() f.close()
@ -217,8 +218,8 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
for fn in files: for fn in files:
if (staticdir and not fn.endswith('.js')) or \ if (staticdir and not fn.endswith('.js')) or \
fn.endswith('.html'): fn.endswith('.html'):
print >>f, path.join(root, fn)[olen:].replace(os.sep, print(path.join(root, fn)[olen:].replace(os.sep, '\\'),
'\\') file=f)
finally: finally:
f.close() f.close()
@ -256,7 +257,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
write_toc(subnode, ullevel) write_toc(subnode, ullevel)
def istoctree(node): def istoctree(node):
return isinstance(node, addnodes.compact_paragraph) and \ return isinstance(node, addnodes.compact_paragraph) and \
node.has_key('toctree') 'toctree' in node
for node in tocdoc.traverse(istoctree): for node in tocdoc.traverse(istoctree):
write_toc(node) write_toc(node)
f.write(contents_footer) f.write(contents_footer)

View File

@ -153,7 +153,7 @@ class CheckExternalLinksBuilder(Builder):
req = HeadRequest(req_url) req = HeadRequest(req_url)
f = opener.open(req, **kwargs) f = opener.open(req, **kwargs)
f.close() f.close()
except HTTPError, err: except HTTPError as err:
if err.code != 405: if err.code != 405:
raise raise
# retry with GET if that fails, some servers # retry with GET if that fails, some servers
@ -162,7 +162,7 @@ class CheckExternalLinksBuilder(Builder):
f = opener.open(req, **kwargs) f = opener.open(req, **kwargs)
f.close() f.close()
except Exception, err: except Exception as err:
self.broken[uri] = str(err) self.broken[uri] = str(err)
return 'broken', str(err), 0 return 'broken', str(err), 0
if f.url.rstrip('/') == req_url.rstrip('/'): if f.url.rstrip('/') == req_url.rstrip('/'):

View File

@ -123,7 +123,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
prune_toctrees=False) prune_toctrees=False)
istoctree = lambda node: ( istoctree = lambda node: (
isinstance(node, addnodes.compact_paragraph) isinstance(node, addnodes.compact_paragraph)
and node.has_key('toctree')) and 'toctree' in node)
sections = [] sections = []
for node in tocdoc.traverse(istoctree): for node in tocdoc.traverse(istoctree):
sections.extend(self.write_toc(node)) sections.extend(self.write_toc(node))

View File

@ -223,6 +223,6 @@ class TexinfoBuilder(Builder):
mkfile.write(TEXINFO_MAKEFILE) mkfile.write(TEXINFO_MAKEFILE)
finally: finally:
mkfile.close() mkfile.close()
except (IOError, OSError), err: except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (fn, err)) self.warn("error writing file %s: %s" % (fn, err))
self.info(' done') self.info(' done')

View File

@ -65,7 +65,7 @@ class TextBuilder(Builder):
f.write(self.writer.output) f.write(self.writer.output)
finally: finally:
f.close() f.close()
except (IOError, OSError), err: except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err)) self.warn("error writing file %s: %s" % (outfilename, err))
def finish(self): def finish(self):

View File

@ -81,7 +81,7 @@ class XMLBuilder(Builder):
f.write(self.writer.output) f.write(self.writer.output)
finally: finally:
f.close() f.close()
except (IOError, OSError), err: except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err)) self.warn("error writing file %s: %s" % (outfilename, err))
def finish(self): def finish(self):

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import sys import sys
@ -28,9 +29,9 @@ from sphinx.util.pycompat import terminal_safe, bytes
def usage(argv, msg=None): def usage(argv, msg=None):
if msg: if msg:
print >>sys.stderr, msg print(msg, file=sys.stderr)
print >>sys.stderr print(file=sys.stderr)
print >>sys.stderr, """\ print("""\
Sphinx v%s Sphinx v%s
Usage: %s [options] sourcedir outdir [filenames...] Usage: %s [options] sourcedir outdir [filenames...]
@ -75,7 +76,7 @@ Standard options
^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
-h, --help show this help and exit -h, --help show this help and exit
--version show version information and exit --version show version information and exit
""" % (__version__, argv[0]) """ % (__version__, argv[0]), file=sys.stderr)
def main(argv): def main(argv):
@ -87,6 +88,7 @@ def main(argv):
try: try:
opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:nNEqQWw:PThvj:', opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:nNEqQWw:PThvj:',
['help', 'version']) ['help', 'version'])
<<<<<<< local
except getopt.error, err: except getopt.error, err:
usage(argv, 'Error: %s' % err) usage(argv, 'Error: %s' % err)
return 1 return 1
@ -105,24 +107,47 @@ def main(argv):
# get paths (first and second positional argument) # get paths (first and second positional argument)
try: try:
=======
allopts = set(opt[0] for opt in opts)
if '-h' in allopts or '--help' in allopts:
usage(argv)
print(file=sys.stderr)
print('For more information, see <http://sphinx-doc.org/>.',
file=sys.stderr)
return 0
if '--version' in allopts:
print('Sphinx (sphinx-build) %s' % __version__)
return 0
>>>>>>> other
srcdir = confdir = abspath(args[0]) srcdir = confdir = abspath(args[0])
if not path.isdir(srcdir): if not path.isdir(srcdir):
print >>sys.stderr, 'Error: Cannot find source directory `%s\'.' % ( print('Error: Cannot find source directory `%s\'.' % srcdir,
srcdir,) file=sys.stderr)
return 1 return 1
if not path.isfile(path.join(srcdir, 'conf.py')) and \ if not path.isfile(path.join(srcdir, 'conf.py')) and \
'-c' not in allopts and '-C' not in allopts: '-c' not in allopts and '-C' not in allopts:
<<<<<<< local
print >>sys.stderr, ('Error: Source directory doesn\'t ' print >>sys.stderr, ('Error: Source directory doesn\'t '
'contain a conf.py file.') 'contain a conf.py file.')
=======
print('Error: Source directory doesn\'t contain conf.py file.',
file=sys.stderr)
>>>>>>> other
return 1 return 1
outdir = abspath(args[1]) outdir = abspath(args[1])
<<<<<<< local
=======
except getopt.error as err:
usage(argv, 'Error: %s' % err)
return 1
>>>>>>> other
except IndexError: except IndexError:
usage(argv, 'Error: Insufficient arguments.') usage(argv, 'Error: Insufficient arguments.')
return 1 return 1
except UnicodeError: except UnicodeError:
print >>sys.stderr, ( print(
'Error: Multibyte filename not supported on this filesystem ' 'Error: Multibyte filename not supported on this filesystem '
'encoding (%r).' % fs_encoding) 'encoding (%r).' % fs_encoding, file=sys.stderr)
return 1 return 1
# handle remaining filename arguments # handle remaining filename arguments
@ -130,7 +155,7 @@ def main(argv):
err = 0 err = 0
for filename in filenames: for filename in filenames:
if not path.isfile(filename): if not path.isfile(filename):
print >>sys.stderr, 'Error: Cannot find file %r.' % filename print('Error: Cannot find file %r.' % filename, file=sys.stderr)
err = 1 err = 1
if err: if err:
return 1 return 1
@ -169,8 +194,8 @@ def main(argv):
elif opt == '-c': elif opt == '-c':
confdir = abspath(val) confdir = abspath(val)
if not path.isfile(path.join(confdir, 'conf.py')): if not path.isfile(path.join(confdir, 'conf.py')):
print >>sys.stderr, ('Error: Configuration directory ' print('Error: Configuration directory doesn\'t contain conf.py file.',
'doesn\'t contain conf.py file.') file=sys.stderr)
return 1 return 1
elif opt == '-C': elif opt == '-C':
confdir = None confdir = None
@ -178,8 +203,8 @@ def main(argv):
try: try:
key, val = val.split('=') key, val = val.split('=')
except ValueError: except ValueError:
print >>sys.stderr, ('Error: -D option argument must be ' print('Error: -D option argument must be in the form name=value.',
'in the form name=value.') file=sys.stderr)
return 1 return 1
if likely_encoding and isinstance(val, bytes): if likely_encoding and isinstance(val, bytes):
try: try:
@ -191,8 +216,8 @@ def main(argv):
try: try:
key, val = val.split('=') key, val = val.split('=')
except ValueError: except ValueError:
print >>sys.stderr, ('Error: -A option argument must be ' print('Error: -A option argument must be in the form name=value.',
'in the form name=value.') file=sys.stderr)
return 1 return 1
try: try:
val = int(val) val = int(val)
@ -229,8 +254,8 @@ def main(argv):
try: try:
parallel = int(val) parallel = int(val)
except ValueError: except ValueError:
print >>sys.stderr, ('Error: -j option argument must be an ' print('Error: -j option argument must be an integer.',
'integer.') file=sys.stderr)
return 1 return 1
if warning and warnfile: if warning and warnfile:
@ -240,7 +265,7 @@ def main(argv):
if not path.isdir(outdir): if not path.isdir(outdir):
if status: if status:
print >>status, 'Making output directory...' print('Making output directory...', file=status)
os.makedirs(outdir) os.makedirs(outdir)
app = None app = None
@ -250,24 +275,25 @@ def main(argv):
warningiserror, tags, verbosity, parallel) warningiserror, tags, verbosity, parallel)
app.build(force_all, filenames) app.build(force_all, filenames)
return app.statuscode return app.statuscode
except (Exception, KeyboardInterrupt), err: except (Exception, KeyboardInterrupt) as err:
if use_pdb: if use_pdb:
import pdb import pdb
print >>error, red('Exception occurred while building, ' print(red('Exception occurred while building, starting debugger:'),
'starting debugger:') file=error)
traceback.print_exc() traceback.print_exc()
pdb.post_mortem(sys.exc_info()[2]) pdb.post_mortem(sys.exc_info()[2])
else: else:
print >>error print(file=error)
if show_traceback: if show_traceback:
traceback.print_exc(None, error) traceback.print_exc(None, error)
print >>error print(file=error)
if isinstance(err, KeyboardInterrupt): if isinstance(err, KeyboardInterrupt):
print >>error, 'interrupted!' print('interrupted!', file=error)
elif isinstance(err, SystemMessage): elif isinstance(err, SystemMessage):
print >>error, red('reST markup error:') print(red('reST markup error:'), file=error)
print >>error, terminal_safe(err.args[0]) print(terminal_safe(err.args[0]), file=error)
elif isinstance(err, SphinxError): elif isinstance(err, SphinxError):
<<<<<<< local
print >>error, red('%s:' % err.category) print >>error, red('%s:' % err.category)
print >>error, terminal_safe(unicode(err)) print >>error, terminal_safe(unicode(err))
elif isinstance(err, UnicodeError): elif isinstance(err, UnicodeError):
@ -277,19 +303,23 @@ def main(argv):
print >>error, red('The full traceback has been saved ' print >>error, red('The full traceback has been saved '
'in %s, if you want to report the ' 'in %s, if you want to report the '
'issue to the developers.' % tbpath) 'issue to the developers.' % tbpath)
=======
print(red('%s:' % err.category), file=error)
print(terminal_safe(unicode(err)), file=error)
>>>>>>> other
else: else:
print >>error, red('Exception occurred:') print(red('Exception occurred:'), file=error)
print >>error, format_exception_cut_frames().rstrip() print(format_exception_cut_frames().rstrip(), file=error)
tbpath = save_traceback(app) tbpath = save_traceback(app)
print >>error, red('The full traceback has been saved ' print(red('The full traceback has been saved in %s, if you '
'in %s, if you want to report the ' 'want to report the issue to the developers.' % tbpath),
'issue to the developers.' % tbpath) file=error)
print >>error, ('Please also report this if it was a user ' print('Please also report this if it was a user error, so '
'error, so that a better error message ' 'that a better error message can be provided next time.',
'can be provided next time.') file=error)
print >>error, ( print('Either send bugs to the mailing list at '
'Either send bugs to the mailing list at ' '<http://groups.google.com/group/sphinx-users/>,\n'
'<http://groups.google.com/group/sphinx-users/>,\n' 'or report them in the tracker at '
'or report them in the tracker at ' '<http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!',
'<http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!') file=error)
return 1 return 1

View File

@ -226,7 +226,7 @@ class Config(object):
os.chdir(dirname) os.chdir(dirname)
try: try:
execfile_(filename, config) execfile_(filename, config)
except SyntaxError, err: except SyntaxError as err:
raise ConfigError(CONFIG_SYNTAX_ERROR % err) raise ConfigError(CONFIG_SYNTAX_ERROR % err)
finally: finally:
os.chdir(olddir) os.chdir(olddir)

View File

@ -39,7 +39,7 @@ class Highlight(Directive):
except Exception: except Exception:
linenothreshold = 10 linenothreshold = 10
else: else:
linenothreshold = sys.maxint linenothreshold = sys.maxsize
return [addnodes.highlightlang(lang=self.arguments[0].strip(), return [addnodes.highlightlang(lang=self.arguments[0].strip(),
linenothreshold=linenothreshold)] linenothreshold=linenothreshold)]
@ -69,7 +69,7 @@ class CodeBlock(Directive):
try: try:
nlines = len(self.content) nlines = len(self.content)
hl_lines = [x+1 for x in parselinenos(linespec, nlines)] hl_lines = [x+1 for x in parselinenos(linespec, nlines)]
except ValueError, err: except ValueError as err:
document = self.state.document document = self.state.document
return [document.reporter.warning(str(err), line=self.lineno)] return [document.reporter.warning(str(err), line=self.lineno)]
else: else:
@ -167,7 +167,7 @@ class LiteralInclude(Directive):
if linespec is not None: if linespec is not None:
try: try:
linelist = parselinenos(linespec, len(lines)) linelist = parselinenos(linespec, len(lines))
except ValueError, err: except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)] return [document.reporter.warning(str(err), line=self.lineno)]
# just ignore nonexisting lines # just ignore nonexisting lines
nlines = len(lines) nlines = len(lines)
@ -181,7 +181,7 @@ class LiteralInclude(Directive):
if linespec: if linespec:
try: try:
hl_lines = [x+1 for x in parselinenos(linespec, len(lines))] hl_lines = [x+1 for x in parselinenos(linespec, len(lines))]
except ValueError, err: except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)] return [document.reporter.warning(str(err), line=self.lineno)]
else: else:
hl_lines = None hl_lines = None

View File

@ -68,7 +68,7 @@ class CObject(ObjectDescription):
def _parse_type(self, node, ctype): def _parse_type(self, node, ctype):
# add cross-ref nodes for all words # add cross-ref nodes for all words
for part in filter(None, wsplit_re.split(ctype)): for part in [_f for _f in wsplit_re.split(ctype) if _f]:
tnode = nodes.Text(part, part) tnode = nodes.Text(part, part)
if part[0] in string.ascii_letters+'_' and \ if part[0] in string.ascii_letters+'_' and \
part not in self.stopwords: part not in self.stopwords:

View File

@ -1065,7 +1065,7 @@ class CPPObject(ObjectDescription):
try: try:
rv = self.parse_definition(parser) rv = self.parse_definition(parser)
parser.assert_end() parser.assert_end()
except DefinitionError, e: except DefinitionError as e:
self.state_machine.reporter.warning(e.description, line=self.lineno) self.state_machine.reporter.warning(e.description, line=self.lineno)
raise ValueError raise ValueError
self.describe_signature(signode, rv) self.describe_signature(signode, rv)
@ -1219,7 +1219,7 @@ class CPPCurrentNamespace(Directive):
try: try:
prefix = parser.parse_type() prefix = parser.parse_type()
parser.assert_end() parser.assert_end()
except DefinitionError, e: except DefinitionError as e:
self.state_machine.reporter.warning(e.description, self.state_machine.reporter.warning(e.description,
line=self.lineno) line=self.lineno)
else: else:

View File

@ -522,7 +522,7 @@ class StandardDomain(Domain):
if labelid is None: if labelid is None:
continue continue
node = document.ids[labelid] node = document.ids[labelid]
if name.isdigit() or node.has_key('refuri') or \ if name.isdigit() or 'refuri' in node or \
node.tagname.startswith('desc_'): node.tagname.startswith('desc_'):
# ignore footnote labels, labels automatically generated from a # ignore footnote labels, labels automatically generated from a
# link and object descriptions # link and object descriptions

View File

@ -618,8 +618,16 @@ class BuildEnvironment:
pub.process_programmatic_settings(None, self.settings, None) pub.process_programmatic_settings(None, self.settings, None)
pub.set_source(None, src_path.encode(fs_encoding)) pub.set_source(None, src_path.encode(fs_encoding))
pub.set_destination(None, None) pub.set_destination(None, None)
<<<<<<< local
pub.publish() pub.publish()
doctree = pub.document doctree = pub.document
=======
try:
pub.publish()
doctree = pub.document
except UnicodeError as err:
raise SphinxError(str(err))
>>>>>>> other
# post-processing # post-processing
self.filter_messages(doctree) self.filter_messages(doctree)
@ -808,7 +816,7 @@ class BuildEnvironment:
imgtype = imghdr.what(f) imgtype = imghdr.what(f)
finally: finally:
f.close() f.close()
except (OSError, IOError), err: except (OSError, IOError) as err:
self.warn_node('image file %s not readable: %s' % self.warn_node('image file %s not readable: %s' %
(filename, err), node) (filename, err), node)
if imgtype: if imgtype:
@ -919,7 +927,7 @@ class BuildEnvironment:
longtitlenode = titlenode longtitlenode = titlenode
# explicit title set with title directive; use this only for # explicit title set with title directive; use this only for
# the <title> tag in HTML output # the <title> tag in HTML output
if document.has_key('title'): if 'title' in document:
longtitlenode = nodes.title() longtitlenode = nodes.title()
longtitlenode += nodes.Text(document['title']) longtitlenode += nodes.Text(document['title'])
# look for first section title and use that as the title # look for first section title and use that as the title
@ -1423,7 +1431,7 @@ class BuildEnvironment:
for node in doctree.traverse(addnodes.only): for node in doctree.traverse(addnodes.only):
try: try:
ret = builder.tags.eval_condition(node['expr']) ret = builder.tags.eval_condition(node['expr'])
except Exception, err: except Exception as err:
self.warn_node('exception while evaluating only ' self.warn_node('exception while evaluating only '
'directive expression: %s' % err, node) 'directive expression: %s' % err, node)
node.replace_self(node.children or nodes.comment()) node.replace_self(node.children or nodes.comment())
@ -1549,7 +1557,7 @@ class BuildEnvironment:
add_entry(first, _('see also %s') % second, link=False) add_entry(first, _('see also %s') % second, link=False)
else: else:
self.warn(fn, 'unknown index entry type %r' % type) self.warn(fn, 'unknown index entry type %r' % type)
except ValueError, err: except ValueError as err:
self.warn(fn, str(err)) self.warn(fn, str(err))
# sort the index entries; put all symbols at the front, even those # sort the index entries; put all symbols at the front, even those

View File

@ -443,7 +443,7 @@ class Documenter(object):
# try to introspect the signature # try to introspect the signature
try: try:
args = self.format_args() args = self.format_args()
except Exception, err: except Exception as err:
self.directive.warn('error while formatting arguments for ' self.directive.warn('error while formatting arguments for '
'%s: %s' % (self.fullname, err)) '%s: %s' % (self.fullname, err))
args = None args = None
@ -763,7 +763,7 @@ class Documenter(object):
# parse right now, to get PycodeErrors on parsing (results will # parse right now, to get PycodeErrors on parsing (results will
# be cached anyway) # be cached anyway)
self.analyzer.find_attr_docs() self.analyzer.find_attr_docs()
except PycodeError, err: except PycodeError as err:
self.env.app.debug('[autodoc] module analyzer failed: %s', err) self.env.app.debug('[autodoc] module analyzer failed: %s', err)
# no source file -- e.g. for builtin and C modules # no source file -- e.g. for builtin and C modules
self.analyzer = None self.analyzer = None
@ -1230,7 +1230,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter):
ret = ClassLevelDocumenter.import_object(self) ret = ClassLevelDocumenter.import_object(self)
if isinstance(self.object, classmethod) or \ if isinstance(self.object, classmethod) or \
(isinstance(self.object, MethodType) and (isinstance(self.object, MethodType) and
self.object.im_self is not None): self.object.__self__ is not None):
self.directivetype = 'classmethod' self.directivetype = 'classmethod'
# document class and static members before ordinary ones # document class and static members before ordinary ones
self.member_order = self.member_order - 1 self.member_order = self.member_order - 1
@ -1422,7 +1422,7 @@ class AutoDirective(Directive):
try: try:
self.genopt = Options(assemble_option_dict( self.genopt = Options(assemble_option_dict(
self.options.items(), doc_class.option_spec)) self.options.items(), doc_class.option_spec))
except (KeyError, ValueError, TypeError), err: except (KeyError, ValueError, TypeError) as err:
# an option is either unknown or has a wrong type # an option is either unknown or has a wrong type
msg = self.reporter.error('An option to %s is either unknown or ' msg = self.reporter.error('An option to %s is either unknown or '
'has an invalid value: %s' % (self.name, err), 'has an invalid value: %s' % (self.name, err),

View File

@ -465,7 +465,7 @@ def _import_by_name(name):
return obj, parent return obj, parent
else: else:
return sys.modules[modname], None return sys.modules[modname], None
except (ValueError, ImportError, AttributeError, KeyError), e: except (ValueError, ImportError, AttributeError, KeyError) as e:
raise ImportError(*e.args) raise ImportError(*e.args)

View File

@ -17,6 +17,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import re import re
@ -70,10 +71,10 @@ def main(argv=sys.argv):
template_dir=options.templates) template_dir=options.templates)
def _simple_info(msg): def _simple_info(msg):
print msg print(msg)
def _simple_warn(msg): def _simple_warn(msg):
print >> sys.stderr, 'WARNING: ' + msg print('WARNING: ' + msg, file=sys.stderr)
# -- Generating output --------------------------------------------------------- # -- Generating output ---------------------------------------------------------
@ -127,7 +128,7 @@ def generate_autosummary_docs(sources, output_dir=None, suffix='.rst',
try: try:
name, obj, parent = import_by_name(name) name, obj, parent = import_by_name(name)
except ImportError, e: except ImportError as e:
warn('[autosummary] failed to import %r: %s' % (name, e)) warn('[autosummary] failed to import %r: %s' % (name, e))
continue continue
@ -240,8 +241,8 @@ def find_autosummary_in_docstring(name, module=None, filename=None):
return find_autosummary_in_lines(lines, module=name, filename=filename) return find_autosummary_in_lines(lines, module=name, filename=filename)
except AttributeError: except AttributeError:
pass pass
except ImportError, e: except ImportError as e:
print "Failed to import '%s': %s" % (name, e) print("Failed to import '%s': %s" % (name, e))
return [] return []
def find_autosummary_in_lines(lines, module=None, filename=None): def find_autosummary_in_lines(lines, module=None, filename=None):

View File

@ -134,7 +134,7 @@ class CoverageBuilder(Builder):
try: try:
mod = __import__(mod_name, fromlist=['foo']) mod = __import__(mod_name, fromlist=['foo'])
except ImportError, err: except ImportError as err:
self.warn('module %s could not be imported: %s' % self.warn('module %s could not be imported: %s' %
(mod_name, err)) (mod_name, err))
self.py_undoc[mod_name] = {'error': err} self.py_undoc[mod_name] = {'error': err}

View File

@ -289,14 +289,14 @@ Doctest summary
if self.config.doctest_test_doctest_blocks: if self.config.doctest_test_doctest_blocks:
def condition(node): def condition(node):
return (isinstance(node, (nodes.literal_block, nodes.comment)) return (isinstance(node, (nodes.literal_block, nodes.comment))
and node.has_key('testnodetype')) or \ and 'testnodetype' in node) or \
isinstance(node, nodes.doctest_block) isinstance(node, nodes.doctest_block)
else: else:
def condition(node): def condition(node):
return isinstance(node, (nodes.literal_block, nodes.comment)) \ return isinstance(node, (nodes.literal_block, nodes.comment)) \
and node.has_key('testnodetype') and 'testnodetype' in node
for node in doctree.traverse(condition): for node in doctree.traverse(condition):
source = node.has_key('test') and node['test'] or node.astext() source = 'test' in node and node['test'] or node.astext()
if not source: if not source:
self.warn('no code/output in %s block at %s:%s' % self.warn('no code/output in %s block at %s:%s' %
(node.get('testnodetype', 'doctest'), (node.get('testnodetype', 'doctest'),

View File

@ -156,7 +156,7 @@ def render_dot(self, code, options, format, prefix='graphviz'):
dot_args.extend(['-Tcmapx', '-o%s.map' % outfn]) dot_args.extend(['-Tcmapx', '-o%s.map' % outfn])
try: try:
p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE) p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
except OSError, err: except OSError as err:
if err.errno != ENOENT: # No such file or directory if err.errno != ENOENT: # No such file or directory
raise raise
self.builder.warn('dot command %r cannot be run (needed for graphviz ' self.builder.warn('dot command %r cannot be run (needed for graphviz '
@ -168,7 +168,7 @@ def render_dot(self, code, options, format, prefix='graphviz'):
# Graphviz may close standard input when an error occurs, # Graphviz may close standard input when an error occurs,
# resulting in a broken pipe on communicate() # resulting in a broken pipe on communicate()
stdout, stderr = p.communicate(code) stdout, stderr = p.communicate(code)
except (OSError, IOError), err: except (OSError, IOError) as err:
if err.errno not in (EPIPE, EINVAL): if err.errno not in (EPIPE, EINVAL):
raise raise
# in this case, read the standard output and standard error streams # in this case, read the standard output and standard error streams
@ -192,7 +192,7 @@ def render_dot_html(self, node, code, options, prefix='graphviz',
raise GraphvizError("graphviz_output_format must be one of 'png', " raise GraphvizError("graphviz_output_format must be one of 'png', "
"'svg', but is %r" % format) "'svg', but is %r" % format)
fname, outfn = render_dot(self, code, options, format, prefix) fname, outfn = render_dot(self, code, options, format, prefix)
except GraphvizError, exc: except GraphvizError as exc:
self.builder.warn('dot code %r: ' % code + str(exc)) self.builder.warn('dot code %r: ' % code + str(exc))
raise nodes.SkipNode raise nodes.SkipNode
@ -243,7 +243,7 @@ def html_visit_graphviz(self, node):
def render_dot_latex(self, node, code, options, prefix='graphviz'): def render_dot_latex(self, node, code, options, prefix='graphviz'):
try: try:
fname, outfn = render_dot(self, code, options, 'pdf', prefix) fname, outfn = render_dot(self, code, options, 'pdf', prefix)
except GraphvizError, exc: except GraphvizError as exc:
self.builder.warn('dot code %r: ' % code + str(exc)) self.builder.warn('dot code %r: ' % code + str(exc))
raise nodes.SkipNode raise nodes.SkipNode
@ -276,7 +276,7 @@ def latex_visit_graphviz(self, node):
def render_dot_texinfo(self, node, code, options, prefix='graphviz'): def render_dot_texinfo(self, node, code, options, prefix='graphviz'):
try: try:
fname, outfn = render_dot(self, code, options, 'png', prefix) fname, outfn = render_dot(self, code, options, 'png', prefix)
except GraphvizError, exc: except GraphvizError as exc:
self.builder.warn('dot code %r: ' % code + str(exc)) self.builder.warn('dot code %r: ' % code + str(exc))
raise nodes.SkipNode raise nodes.SkipNode
if fname is not None: if fname is not None:

View File

@ -53,7 +53,7 @@ def process_ifconfig_nodes(app, doctree, docname):
for node in doctree.traverse(ifconfig): for node in doctree.traverse(ifconfig):
try: try:
res = eval(node['expr'], ns) res = eval(node['expr'], ns)
except Exception, err: except Exception as err:
# handle exceptions in a clean fashion # handle exceptions in a clean fashion
from traceback import format_exception_only from traceback import format_exception_only
msg = ''.join(format_exception_only(err.__class__, err)) msg = ''.join(format_exception_only(err.__class__, err))

View File

@ -306,7 +306,7 @@ class InheritanceDiagram(Directive):
class_names, env.temp_data.get('py:module'), class_names, env.temp_data.get('py:module'),
parts=node['parts'], parts=node['parts'],
private_bases='private-bases' in self.options) private_bases='private-bases' in self.options)
except InheritanceException, err: except InheritanceException as err:
return [node.document.reporter.warning(err.args[0], return [node.document.reporter.warning(err.args[0],
line=self.lineno)] line=self.lineno)]

View File

@ -132,7 +132,7 @@ def fetch_inventory(app, uri, inv):
f = urllib2.urlopen(inv) f = urllib2.urlopen(inv)
else: else:
f = open(path.join(app.srcdir, inv), 'rb') f = open(path.join(app.srcdir, inv), 'rb')
except Exception, err: except Exception as err:
app.warn('intersphinx inventory %r not fetchable due to ' app.warn('intersphinx inventory %r not fetchable due to '
'%s: %s' % (inv, err.__class__, err)) '%s: %s' % (inv, err.__class__, err))
return return
@ -149,7 +149,7 @@ def fetch_inventory(app, uri, inv):
except ValueError: except ValueError:
f.close() f.close()
raise ValueError('unknown or unsupported inventory version') raise ValueError('unknown or unsupported inventory version')
except Exception, err: except Exception as err:
app.warn('intersphinx inventory %r not readable due to ' app.warn('intersphinx inventory %r not readable due to '
'%s: %s' % (inv, err.__class__.__name__, err)) '%s: %s' % (inv, err.__class__.__name__, err))
else: else:

View File

@ -123,7 +123,7 @@ def render_math(self, math):
try: try:
try: try:
p = Popen(ltx_args, stdout=PIPE, stderr=PIPE) p = Popen(ltx_args, stdout=PIPE, stderr=PIPE)
except OSError, err: except OSError as err:
if err.errno != ENOENT: # No such file or directory if err.errno != ENOENT: # No such file or directory
raise raise
self.builder.warn('LaTeX command %r cannot be run (needed for math ' self.builder.warn('LaTeX command %r cannot be run (needed for math '
@ -150,7 +150,7 @@ def render_math(self, math):
dvipng_args.append(path.join(tempdir, 'math.dvi')) dvipng_args.append(path.join(tempdir, 'math.dvi'))
try: try:
p = Popen(dvipng_args, stdout=PIPE, stderr=PIPE) p = Popen(dvipng_args, stdout=PIPE, stderr=PIPE)
except OSError, err: except OSError as err:
if err.errno != ENOENT: # No such file or directory if err.errno != ENOENT: # No such file or directory
raise raise
self.builder.warn('dvipng command %r cannot be run (needed for math ' self.builder.warn('dvipng command %r cannot be run (needed for math '
@ -190,7 +190,7 @@ def get_tooltip(self, node):
def html_visit_math(self, node): def html_visit_math(self, node):
try: try:
fname, depth = render_math(self, '$'+node['latex']+'$') fname, depth = render_math(self, '$'+node['latex']+'$')
except MathExtError, exc: except MathExtError as exc:
msg = unicode(exc) msg = unicode(exc)
sm = nodes.system_message(msg, type='WARNING', level=2, sm = nodes.system_message(msg, type='WARNING', level=2,
backrefs=[], source=node['latex']) backrefs=[], source=node['latex'])
@ -215,7 +215,7 @@ def html_visit_displaymath(self, node):
latex = wrap_displaymath(node['latex'], None) latex = wrap_displaymath(node['latex'], None)
try: try:
fname, depth = render_math(self, latex) fname, depth = render_math(self, latex)
except MathExtError, exc: except MathExtError as exc:
sm = nodes.system_message(str(exc), type='WARNING', level=2, sm = nodes.system_message(str(exc), type='WARNING', level=2,
backrefs=[], source=node['latex']) backrefs=[], source=node['latex'])
sm.walkabout(self) sm.walkabout(self)

View File

@ -14,6 +14,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import sys import sys
@ -68,90 +69,90 @@ class Make(object):
if not path.exists(self.builddir): if not path.exists(self.builddir):
return return
elif not path.isdir(self.builddir): elif not path.isdir(self.builddir):
print "Error: %r is not a directory!" % self.builddir print("Error: %r is not a directory!" % self.builddir)
return 1 return 1
print "Removing everything under %r..." % self.builddir print("Removing everything under %r..." % self.builddir)
for item in os.listdir(self.builddir): for item in os.listdir(self.builddir):
shutil.rmtree(self.builddir_join(item)) shutil.rmtree(self.builddir_join(item))
def build_help(self): def build_help(self):
print bold("Sphinx v%s" % sphinx.__version__) print(bold("Sphinx v%s" % sphinx.__version__))
print "Please use `make %s' where %s is one of" % ((blue('target'),)*2) print("Please use `make %s' where %s is one of" % ((blue('target'),)*2))
for osname, bname, description in BUILDERS: for osname, bname, description in BUILDERS:
if not osname or os.name == osname: if not osname or os.name == osname:
print ' %s %s' % (blue(bname.ljust(10)), description) print(' %s %s' % (blue(bname.ljust(10)), description))
def build_html(self): def build_html(self):
if self.run_generic_build('html') > 0: if self.run_generic_build('html') > 0:
return 1 return 1
print print()
print 'Build finished. The HTML pages are in %s.' % self.builddir_join('html') print('Build finished. The HTML pages are in %s.' % self.builddir_join('html'))
def build_dirhtml(self): def build_dirhtml(self):
if self.run_generic_build('dirhtml') > 0: if self.run_generic_build('dirhtml') > 0:
return 1 return 1
print print()
print 'Build finished. The HTML pages are in %s.' % self.builddir_join('dirhtml') print('Build finished. The HTML pages are in %s.' % self.builddir_join('dirhtml'))
def build_singlehtml(self): def build_singlehtml(self):
if self.run_generic_build('singlehtml') > 0: if self.run_generic_build('singlehtml') > 0:
return 1 return 1
print print()
print 'Build finished. The HTML page is in %s.' % self.builddir_join('singlehtml') print('Build finished. The HTML page is in %s.' % self.builddir_join('singlehtml'))
def build_pickle(self): def build_pickle(self):
if self.run_generic_build('pickle') > 0: if self.run_generic_build('pickle') > 0:
return 1 return 1
print print()
print 'Build finished; now you can process the pickle files.' print('Build finished; now you can process the pickle files.')
def build_json(self): def build_json(self):
if self.run_generic_build('json') > 0: if self.run_generic_build('json') > 0:
return 1 return 1
print print()
print 'Build finished; now you can process the JSON files.' print('Build finished; now you can process the JSON files.')
def build_htmlhelp(self): def build_htmlhelp(self):
if self.run_generic_build('htmlhelp') > 0: if self.run_generic_build('htmlhelp') > 0:
return 1 return 1
print print()
print ('Build finished; now you can run HTML Help Workshop with the ' print('Build finished; now you can run HTML Help Workshop with the '
'.hhp project file in %s.') % self.builddir_join('htmlhelp') '.hhp project file in %s.' % self.builddir_join('htmlhelp'))
def build_qthelp(self): def build_qthelp(self):
if self.run_generic_build('qthelp') > 0: if self.run_generic_build('qthelp') > 0:
return 1 return 1
print print()
print ('Build finished; now you can run "qcollectiongenerator" with the ' print('Build finished; now you can run "qcollectiongenerator" with the '
'.qhcp project file in %s, like this:') % self.builddir_join('qthelp') '.qhcp project file in %s, like this:' % self.builddir_join('qthelp'))
print '$ qcollectiongenerator %s.qhcp' % self.builddir_join('qthelp', proj_name) print('$ qcollectiongenerator %s.qhcp' % self.builddir_join('qthelp', proj_name))
print 'To view the help file:' print('To view the help file:')
print '$ assistant -collectionFile %s.qhc' % self.builddir_join('qthelp', proj_name) print('$ assistant -collectionFile %s.qhc' % self.builddir_join('qthelp', proj_name))
def build_devhelp(self): def build_devhelp(self):
if self.run_generic_build('devhelp') > 0: if self.run_generic_build('devhelp') > 0:
return 1 return 1
print print()
print "Build finished." print("Build finished.")
print "To view the help file:" print("To view the help file:")
print "$ mkdir -p $HOME/.local/share/devhelp/" + proj_name print("$ mkdir -p $HOME/.local/share/devhelp/" + proj_name)
print "$ ln -s %s $HOME/.local/share/devhelp/%s" % \ print("$ ln -s %s $HOME/.local/share/devhelp/%s" %
(self.builddir_join('devhelp'), proj_name) (self.builddir_join('devhelp'), proj_name))
print "$ devhelp" print("$ devhelp")
def build_epub(self): def build_epub(self):
if self.run_generic_build('epub') > 0: if self.run_generic_build('epub') > 0:
return 1 return 1
print print()
print 'Build finished. The ePub file is in %s.' % self.builddir_join('epub') print('Build finished. The ePub file is in %s.' % self.builddir_join('epub'))
def build_latex(self): def build_latex(self):
if self.run_generic_build('latex') > 0: if self.run_generic_build('latex') > 0:
return 1 return 1
print "Build finished; the LaTeX files are in %s." % self.builddir_join('latex') print("Build finished; the LaTeX files are in %s." % self.builddir_join('latex'))
if os.name == 'posix': if os.name == 'posix':
print "Run `make' in that directory to run these through (pdf)latex" print("Run `make' in that directory to run these through (pdf)latex")
print "(use `make latexpdf' here to do that automatically)." print("(use `make latexpdf' here to do that automatically).")
def build_latexpdf(self): def build_latexpdf(self):
if self.run_generic_build('latex') > 0: if self.run_generic_build('latex') > 0:
@ -166,16 +167,16 @@ class Make(object):
def build_text(self): def build_text(self):
if self.run_generic_build('text') > 0: if self.run_generic_build('text') > 0:
return 1 return 1
print print()
print 'Build finished. The text files are in %s.' % self.builddir_join('text') print('Build finished. The text files are in %s.' % self.builddir_join('text'))
def build_texinfo(self): def build_texinfo(self):
if self.run_generic_build('texinfo') > 0: if self.run_generic_build('texinfo') > 0:
return 1 return 1
print "Build finished; the Texinfo files are in %s." % self.builddir_join('texinfo') print("Build finished; the Texinfo files are in %s." % self.builddir_join('texinfo'))
if os.name == 'posix': if os.name == 'posix':
print "Run `make' in that directory to run these through makeinfo" print("Run `make' in that directory to run these through makeinfo")
print "(use `make info' here to do that automatically)." print("(use `make info' here to do that automatically).")
def build_info(self): def build_info(self):
if self.run_generic_build('texinfo') > 0: if self.run_generic_build('texinfo') > 0:
@ -186,47 +187,47 @@ class Make(object):
dtdir = self.builddir_join('gettext', '.doctrees') dtdir = self.builddir_join('gettext', '.doctrees')
if self.run_generic_build('gettext', doctreedir=dtdir) > 0: if self.run_generic_build('gettext', doctreedir=dtdir) > 0:
return 1 return 1
print print()
print 'Build finished. The message catalogs are in %s.' % self.builddir_join('gettext') print('Build finished. The message catalogs are in %s.' % self.builddir_join('gettext'))
def build_changes(self): def build_changes(self):
if self.run_generic_build('changes') > 0: if self.run_generic_build('changes') > 0:
return 1 return 1
print print()
print 'Build finished. The overview file is in %s.' % self.builddir_join('changes') print('Build finished. The overview file is in %s.' % self.builddir_join('changes'))
def build_linkcheck(self): def build_linkcheck(self):
res = self.run_generic_build('linkcheck') res = self.run_generic_build('linkcheck')
print print()
print ('Link check complete; look for any errors in the above output ' print('Link check complete; look for any errors in the above output '
'or in %s.') % self.builddir_join('linkcheck', 'output.txt') 'or in %s.' % self.builddir_join('linkcheck', 'output.txt'))
return res return res
def build_doctest(self): def build_doctest(self):
res = self.run_generic_build('doctest') res = self.run_generic_build('doctest')
print ("Testing of doctests in the sources finished, look at the " print("Testing of doctests in the sources finished, look at the "
"results in %s." % self.builddir_join('doctest', 'output.txt')) "results in %s." % self.builddir_join('doctest', 'output.txt'))
return res return res
def build_coverage(self): def build_coverage(self):
if self.run_generic_build('coverage') > 0: if self.run_generic_build('coverage') > 0:
print "Has the coverage extension been enabled?" print("Has the coverage extension been enabled?")
return 1 return 1
print print()
print ("Testing of coverage in the sources finished, look at the " print("Testing of coverage in the sources finished, look at the "
"results in %s." % self.builddir_join('coverage')) "results in %s." % self.builddir_join('coverage'))
def build_xml(self): def build_xml(self):
if self.run_generic_build('xml') > 0: if self.run_generic_build('xml') > 0:
return 1 return 1
print print()
print 'Build finished. The XML files are in %s.' % self.builddir_join('xml') print('Build finished. The XML files are in %s.' % self.builddir_join('xml'))
def build_pseudoxml(self): def build_pseudoxml(self):
if self.run_generic_build('pseudoxml') > 0: if self.run_generic_build('pseudoxml') > 0:
return 1 return 1
print print()
print 'Build finished. The pseudo-XML files are in %s.' % self.builddir_join('pseudoxml') print('Build finished. The pseudo-XML files are in %s.' % self.builddir_join('pseudoxml'))
def run_generic_build(self, builder, doctreedir=None): def run_generic_build(self, builder, doctreedir=None):
# compatibility with old Makefile # compatibility with old Makefile
@ -242,8 +243,8 @@ class Make(object):
def run_make_mode(args): def run_make_mode(args):
if len(args) < 3: if len(args) < 3:
print >>sys.stderr, ('Error: at least 3 arguments (builder, source ' print('Error: at least 3 arguments (builder, source '
'dir, build dir) are required.') 'dir, build dir) are required.', file=sys.stderr)
return 1 return 1
make = Make(args[1], args[2], args[3:]) make = Make(args[1], args[2], args[3:])
run_method = 'build_' + args[0] run_method = 'build_' + args[0]

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import sys import sys
from os import path from os import path
@ -182,7 +183,7 @@ class ModuleAnalyzer(object):
return cls.cache['file', filename] return cls.cache['file', filename]
try: try:
fileobj = open(filename, 'rb') fileobj = open(filename, 'rb')
except Exception, err: except Exception as err:
raise PycodeError('error opening %r' % filename, err) raise PycodeError('error opening %r' % filename, err)
obj = cls(fileobj, modname, filename) obj = cls(fileobj, modname, filename)
cls.cache['file', filename] = obj cls.cache['file', filename] = obj
@ -202,7 +203,7 @@ class ModuleAnalyzer(object):
obj = cls.for_string(source, modname) obj = cls.for_string(source, modname)
else: else:
obj = cls.for_file(source, modname) obj = cls.for_file(source, modname)
except PycodeError, err: except PycodeError as err:
cls.cache['module', modname] = err cls.cache['module', modname] = err
raise raise
cls.cache['module', modname] = obj cls.cache['module', modname] = obj
@ -245,7 +246,7 @@ class ModuleAnalyzer(object):
return return
try: try:
self.tokens = list(tokenize.generate_tokens(self.source.readline)) self.tokens = list(tokenize.generate_tokens(self.source.readline))
except tokenize.TokenError, err: except tokenize.TokenError as err:
raise PycodeError('tokenizing failed', err) raise PycodeError('tokenizing failed', err)
self.source.close() self.source.close()
@ -256,7 +257,7 @@ class ModuleAnalyzer(object):
self.tokenize() self.tokenize()
try: try:
self.parsetree = pydriver.parse_tokens(self.tokens) self.parsetree = pydriver.parse_tokens(self.tokens)
except parse.ParseError, err: except parse.ParseError as err:
raise PycodeError('parsing failed', err) raise PycodeError('parsing failed', err)
def find_attr_docs(self, scope=''): def find_attr_docs(self, scope=''):
@ -344,4 +345,4 @@ if __name__ == '__main__':
pprint.pprint(ma.find_tags()) pprint.pprint(ma.find_tags())
x3 = time.time() x3 = time.time()
#print nodes.nice_repr(ma.parsetree, number2name) #print nodes.nice_repr(ma.parsetree, number2name)
print "tokenizing %.4f, parsing %.4f, finding %.4f" % (x1-x0, x2-x1, x3-x2) print("tokenizing %.4f, parsing %.4f, finding %.4f" % (x1-x0, x2-x1, x3-x2))

View File

@ -131,7 +131,7 @@ def load_grammar(gt="Grammar.txt", gp=None,
logger.info("Writing grammar tables to %s", gp) logger.info("Writing grammar tables to %s", gp)
try: try:
g.dump(gp) g.dump(gp)
except IOError, e: except IOError as e:
logger.info("Writing failed:"+str(e)) logger.info("Writing failed:"+str(e))
else: else:
g = grammar.Grammar() g = grammar.Grammar()

View File

@ -11,6 +11,7 @@ token module; the Python tokenize module reports all operators as the
fallback token code OP, but the parser needs the actual token code. fallback token code OP, but the parser needs the actual token code.
""" """
from __future__ import print_function
# Python imports # Python imports
import pickle import pickle
@ -100,17 +101,17 @@ class Grammar(object):
def report(self): def report(self):
"""Dump the grammar tables to standard output, for debugging.""" """Dump the grammar tables to standard output, for debugging."""
from pprint import pprint from pprint import pprint
print "s2n" print("s2n")
pprint(self.symbol2number) pprint(self.symbol2number)
print "n2s" print("n2s")
pprint(self.number2symbol) pprint(self.number2symbol)
print "states" print("states")
pprint(self.states) pprint(self.states)
print "dfas" print("dfas")
pprint(self.dfas) pprint(self.dfas)
print "labels" print("labels")
pprint(self.labels) pprint(self.labels)
print "start", self.start print("start", self.start)
# Map from operator to number (since tokenize doesn't do this) # Map from operator to number (since tokenize doesn't do this)

View File

@ -4,6 +4,7 @@
# Extended to handle raw and unicode literals by Georg Brandl. # Extended to handle raw and unicode literals by Georg Brandl.
"""Safely evaluate Python string literals without using eval().""" """Safely evaluate Python string literals without using eval()."""
from __future__ import print_function
import re import re
@ -89,7 +90,7 @@ def test():
s = repr(c) s = repr(c)
e = evalString(s) e = evalString(s)
if e != c: if e != c:
print i, c, s, e print(i, c, s, e)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -2,6 +2,7 @@
# Licensed to PSF under a Contributor Agreement. # Licensed to PSF under a Contributor Agreement.
# Pgen imports # Pgen imports
from __future__ import print_function
from sphinx.pycode.pgen2 import grammar, token, tokenize from sphinx.pycode.pgen2 import grammar, token, tokenize
class PgenGrammar(grammar.Grammar): class PgenGrammar(grammar.Grammar):
@ -203,10 +204,10 @@ class ParserGenerator(object):
return states # List of DFAState instances; first one is start return states # List of DFAState instances; first one is start
def dump_nfa(self, name, start, finish): def dump_nfa(self, name, start, finish):
print "Dump of NFA for", name print("Dump of NFA for", name)
todo = [start] todo = [start]
for i, state in enumerate(todo): for i, state in enumerate(todo):
print " State", i, state is finish and "(final)" or "" print(" State", i, state is finish and "(final)" or "")
for label, next in state.arcs: for label, next in state.arcs:
if next in todo: if next in todo:
j = todo.index(next) j = todo.index(next)
@ -214,16 +215,16 @@ class ParserGenerator(object):
j = len(todo) j = len(todo)
todo.append(next) todo.append(next)
if label is None: if label is None:
print " -> %d" % j print(" -> %d" % j)
else: else:
print " %s -> %d" % (label, j) print(" %s -> %d" % (label, j))
def dump_dfa(self, name, dfa): def dump_dfa(self, name, dfa):
print "Dump of DFA for", name print("Dump of DFA for", name)
for i, state in enumerate(dfa): for i, state in enumerate(dfa):
print " State", i, state.isfinal and "(final)" or "" print(" State", i, state.isfinal and "(final)" or "")
for label, next in state.arcs.iteritems(): for label, next in state.arcs.iteritems():
print " %s -> %d" % (label, dfa.index(next)) print(" %s -> %d" % (label, dfa.index(next)))
def simplify_dfa(self, dfa): def simplify_dfa(self, dfa):
# This is not theoretically optimal, but works well enough. # This is not theoretically optimal, but works well enough.

View File

@ -25,6 +25,8 @@ are the same, except instead of generating tokens, tokeneater is a callback
function to which the 5 fields described above are passed as 5 arguments, function to which the 5 fields described above are passed as 5 arguments,
each time a new token is found.""" each time a new token is found."""
from __future__ import print_function
__author__ = 'Ka-Ping Yee <ping@lfw.org>' __author__ = 'Ka-Ping Yee <ping@lfw.org>'
__credits__ = \ __credits__ = \
'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro' 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
@ -146,8 +148,8 @@ class StopTokenizing(Exception): pass
def printtoken(type, token, scell, ecell, line): # for testing def printtoken(type, token, scell, ecell, line): # for testing
srow, scol = scell srow, scol = scell
erow, ecol = ecell erow, ecol = ecell
print "%d,%d-%d,%d:\t%s\t%s" % \ print("%d,%d-%d,%d:\t%s\t%s" %
(srow, scol, erow, ecol, tok_name[type], repr(token)) (srow, scol, erow, ecol, tok_name[type], repr(token)))
def tokenize(readline, tokeneater=printtoken): def tokenize(readline, tokeneater=printtoken):
""" """

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import sys, os, time, re import sys, os, time, re
from os import path from os import path
@ -965,9 +966,9 @@ def do_prompt(d, key, text, default=None, validator=nonempty):
if TERM_ENCODING: if TERM_ENCODING:
prompt = prompt.encode(TERM_ENCODING) prompt = prompt.encode(TERM_ENCODING)
else: else:
print turquoise('* Note: non-ASCII default value provided ' print(turquoise('* Note: non-ASCII default value provided '
'and terminal encoding unknown -- assuming ' 'and terminal encoding unknown -- assuming '
'UTF-8 or Latin-1.') 'UTF-8 or Latin-1.'))
try: try:
prompt = prompt.encode('utf-8') prompt = prompt.encode('utf-8')
except UnicodeEncodeError: except UnicodeEncodeError:
@ -982,17 +983,17 @@ def do_prompt(d, key, text, default=None, validator=nonempty):
if TERM_ENCODING: if TERM_ENCODING:
x = x.decode(TERM_ENCODING) x = x.decode(TERM_ENCODING)
else: else:
print turquoise('* Note: non-ASCII characters entered ' print(turquoise('* Note: non-ASCII characters entered '
'and terminal encoding unknown -- assuming ' 'and terminal encoding unknown -- assuming '
'UTF-8 or Latin-1.') 'UTF-8 or Latin-1.'))
try: try:
x = x.decode('utf-8') x = x.decode('utf-8')
except UnicodeDecodeError: except UnicodeDecodeError:
x = x.decode('latin1') x = x.decode('latin1')
try: try:
x = validator(x) x = validator(x)
except ValidationError, err: except ValidationError as err:
print red('* ' + str(err)) print(red('* ' + str(err)))
continue continue
break break
d[key] = x d[key] = x
@ -1030,110 +1031,110 @@ def ask_user(d):
* batchfile: make command file * batchfile: make command file
""" """
print bold('Welcome to the Sphinx %s quickstart utility.') % __version__ print(bold('Welcome to the Sphinx %s quickstart utility.') % __version__)
print ''' print('''
Please enter values for the following settings (just press Enter to Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).''' accept a default value, if one is given in brackets).''')
if 'path' in d: if 'path' in d:
print bold(''' print(bold('''
Selected root path: %s''' % d['path']) Selected root path: %s''' % d['path']))
else: else:
print ''' print('''
Enter the root path for documentation.''' Enter the root path for documentation.''')
do_prompt(d, 'path', 'Root path for the documentation', '.', is_path) do_prompt(d, 'path', 'Root path for the documentation', '.', is_path)
while path.isfile(path.join(d['path'], 'conf.py')) or \ while path.isfile(path.join(d['path'], 'conf.py')) or \
path.isfile(path.join(d['path'], 'source', 'conf.py')): path.isfile(path.join(d['path'], 'source', 'conf.py')):
print print()
print bold('Error: an existing conf.py has been found in the ' print(bold('Error: an existing conf.py has been found in the '
'selected root path.') 'selected root path.'))
print 'sphinx-quickstart will not overwrite existing Sphinx projects.' print('sphinx-quickstart will not overwrite existing Sphinx projects.')
print print()
do_prompt(d, 'path', 'Please enter a new root path (or just Enter ' do_prompt(d, 'path', 'Please enter a new root path (or just Enter '
'to exit)', '', is_path) 'to exit)', '', is_path)
if not d['path']: if not d['path']:
sys.exit(1) sys.exit(1)
if 'sep' not in d: if 'sep' not in d:
print ''' print('''
You have two options for placing the build directory for Sphinx output. You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.''' "source" and "build" directories within the root path.''')
do_prompt(d, 'sep', 'Separate source and build directories (y/n)', 'n', do_prompt(d, 'sep', 'Separate source and build directories (y/n)', 'n',
boolean) boolean)
if 'dot' not in d: if 'dot' not in d:
print ''' print('''
Inside the root directory, two more directories will be created; "_templates" Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.''' files. You can enter another prefix (such as ".") to replace the underscore.''')
do_prompt(d, 'dot', 'Name prefix for templates and static dir', '_', ok) do_prompt(d, 'dot', 'Name prefix for templates and static dir', '_', ok)
if 'project' not in d: if 'project' not in d:
print ''' print('''
The project name will occur in several places in the built documentation.''' The project name will occur in several places in the built documentation.''')
do_prompt(d, 'project', 'Project name') do_prompt(d, 'project', 'Project name')
if 'author' not in d: if 'author' not in d:
do_prompt(d, 'author', 'Author name(s)') do_prompt(d, 'author', 'Author name(s)')
if 'version' not in d: if 'version' not in d:
print ''' print('''
Sphinx has the notion of a "version" and a "release" for the Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1. If you don't need this dual structure, something like 2.5.1 or 3.0a1. If you don't need this dual structure,
just set both to the same value.''' just set both to the same value.''')
do_prompt(d, 'version', 'Project version') do_prompt(d, 'version', 'Project version')
if 'release' not in d: if 'release' not in d:
do_prompt(d, 'release', 'Project release', d['version']) do_prompt(d, 'release', 'Project release', d['version'])
if 'language' not in d: if 'language' not in d:
print ''' print('''
If the documents are to be written in a language other than English, If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then you can select a language here by its language code. Sphinx will then
translate text that it generates into that language. translate text that it generates into that language.
For a list of supported codes, see For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.''' http://sphinx-doc.org/config.html#confval-language.''')
do_prompt(d, 'language', 'Project language', 'en') do_prompt(d, 'language', 'Project language', 'en')
if d['language'] == 'en': if d['language'] == 'en':
d['language'] = None d['language'] = None
if 'suffix' not in d: if 'suffix' not in d:
print ''' print('''
The file name suffix for source files. Commonly, this is either ".txt" The file name suffix for source files. Commonly, this is either ".txt"
or ".rst". Only files with this suffix are considered documents.''' or ".rst". Only files with this suffix are considered documents.''')
do_prompt(d, 'suffix', 'Source file suffix', '.rst', suffix) do_prompt(d, 'suffix', 'Source file suffix', '.rst', suffix)
if 'master' not in d: if 'master' not in d:
print ''' print('''
One document is special in that it is considered the top node of the One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure "contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index" of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.''' document is a custom template, you can also set this to another filename.''')
do_prompt(d, 'master', 'Name of your master document (without suffix)', do_prompt(d, 'master', 'Name of your master document (without suffix)',
'index') 'index')
while path.isfile(path.join(d['path'], d['master']+d['suffix'])) or \ while path.isfile(path.join(d['path'], d['master']+d['suffix'])) or \
path.isfile(path.join(d['path'], 'source', d['master']+d['suffix'])): path.isfile(path.join(d['path'], 'source', d['master']+d['suffix'])):
print print()
print bold('Error: the master file %s has already been found in the ' print(bold('Error: the master file %s has already been found in the '
'selected root path.' % (d['master']+d['suffix'])) 'selected root path.' % (d['master']+d['suffix'])))
print 'sphinx-quickstart will not overwrite the existing file.' print('sphinx-quickstart will not overwrite the existing file.')
print print()
do_prompt(d, 'master', 'Please enter a new file name, or rename the ' do_prompt(d, 'master', 'Please enter a new file name, or rename the '
'existing file and press Enter', d['master']) 'existing file and press Enter', d['master'])
if 'epub' not in d: if 'epub' not in d:
print ''' print('''
Sphinx can also add configuration for epub output:''' Sphinx can also add configuration for epub output:''')
do_prompt(d, 'epub', 'Do you want to use the epub builder (y/n)', do_prompt(d, 'epub', 'Do you want to use the epub builder (y/n)',
'n', boolean) 'n', boolean)
if 'ext_autodoc' not in d: if 'ext_autodoc' not in d:
print ''' print('''
Please indicate if you want to use one of the following Sphinx extensions:''' Please indicate if you want to use one of the following Sphinx extensions:''')
do_prompt(d, 'ext_autodoc', 'autodoc: automatically insert docstrings ' do_prompt(d, 'ext_autodoc', 'autodoc: automatically insert docstrings '
'from modules (y/n)', 'n', boolean) 'from modules (y/n)', 'n', boolean)
if 'ext_doctest' not in d: if 'ext_doctest' not in d:
@ -1155,8 +1156,8 @@ Please indicate if you want to use one of the following Sphinx extensions:'''
do_prompt(d, 'ext_mathjax', 'mathjax: include math, rendered in the ' do_prompt(d, 'ext_mathjax', 'mathjax: include math, rendered in the '
'browser by MathJax (y/n)', 'n', boolean) 'browser by MathJax (y/n)', 'n', boolean)
if d['ext_pngmath'] and d['ext_mathjax']: if d['ext_pngmath'] and d['ext_mathjax']:
print '''Note: pngmath and mathjax cannot be enabled at the same time. print('''Note: pngmath and mathjax cannot be enabled at the same time.
pngmath has been deselected.''' pngmath has been deselected.''')
if 'ext_ifconfig' not in d: if 'ext_ifconfig' not in d:
do_prompt(d, 'ext_ifconfig', 'ifconfig: conditional inclusion of ' do_prompt(d, 'ext_ifconfig', 'ifconfig: conditional inclusion of '
'content based on config values (y/n)', 'n', boolean) 'content based on config values (y/n)', 'n', boolean)
@ -1165,15 +1166,15 @@ pngmath has been deselected.'''
'code of documented Python objects (y/n)', 'n', boolean) 'code of documented Python objects (y/n)', 'n', boolean)
if 'makefile' not in d: if 'makefile' not in d:
print ''' print('''
A Makefile and a Windows command file can be generated for you so that you A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build only have to run e.g. `make html' instead of invoking sphinx-build
directly.''' directly.''')
do_prompt(d, 'makefile', 'Create Makefile? (y/n)', 'y', boolean) do_prompt(d, 'makefile', 'Create Makefile? (y/n)', 'y', boolean)
if 'batchfile' not in d: if 'batchfile' not in d:
do_prompt(d, 'batchfile', 'Create Windows command file? (y/n)', do_prompt(d, 'batchfile', 'Create Windows command file? (y/n)',
'y', boolean) 'y', boolean)
print print()
def generate(d, overwrite=True, silent=False): def generate(d, overwrite=True, silent=False):
@ -1232,14 +1233,14 @@ def generate(d, overwrite=True, silent=False):
def write_file(fpath, content, newline=None): def write_file(fpath, content, newline=None):
if overwrite or not path.isfile(fpath): if overwrite or not path.isfile(fpath):
print 'Creating file %s.' % fpath print('Creating file %s.' % fpath)
f = open(fpath, 'wt', encoding='utf-8', newline=newline) f = open(fpath, 'wt', encoding='utf-8', newline=newline)
try: try:
f.write(content) f.write(content)
finally: finally:
f.close() f.close()
else: else:
print 'File %s already exists, skipping.' % fpath print('File %s already exists, skipping.' % fpath)
conf_text = QUICKSTART_CONF % d conf_text = QUICKSTART_CONF % d
if d['epub']: if d['epub']:
@ -1265,9 +1266,9 @@ def generate(d, overwrite=True, silent=False):
if silent: if silent:
return return
print print()
print bold('Finished: An initial directory structure has been created.') print(bold('Finished: An initial directory structure has been created.'))
print ''' print('''
You should now populate your master file %s and create other documentation You should now populate your master file %s and create other documentation
source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\ source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\
Use the Makefile to build the docs, like so: Use the Makefile to build the docs, like so:
@ -1277,7 +1278,7 @@ Use the sphinx-build command to build the docs, like so:
sphinx-build -b builder %s %s sphinx-build -b builder %s %s
''' % (srcdir, builddir)) + '''\ ''' % (srcdir, builddir)) + '''\
where "builder" is one of the supported builders, e.g. html, latex or linkcheck. where "builder" is one of the supported builders, e.g. html, latex or linkcheck.
''' ''')
def main(argv=sys.argv): def main(argv=sys.argv):
@ -1286,14 +1287,14 @@ def main(argv=sys.argv):
d = {} d = {}
if len(argv) > 3: if len(argv) > 3:
print 'Usage: sphinx-quickstart [root]' print('Usage: sphinx-quickstart [root]')
sys.exit(1) sys.exit(1)
elif len(argv) == 2: elif len(argv) == 2:
d['path'] = argv[1] d['path'] = argv[1]
try: try:
ask_user(d) ask_user(d)
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
print print()
print '[Interrupted.]' print('[Interrupted.]')
return return
generate(d) generate(d)

View File

@ -11,6 +11,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import sys import sys
import os import os
@ -158,12 +159,12 @@ class BuildDoc(Command):
try: try:
app.build(force_all=self.all_files) app.build(force_all=self.all_files)
except Exception, err: except Exception as err:
from docutils.utils import SystemMessage from docutils.utils import SystemMessage
if isinstance(err, SystemMessage): if isinstance(err, SystemMessage):
print >>sys.stderr, darkred('reST markup error:') print(darkred('reST markup error:'), file=sys.stderr)
print >>sys.stderr, err.args[0].encode('ascii', print(err.args[0].encode('ascii',
'backslashreplace') 'backslashreplace'), file=sys.stderr)
else: else:
raise raise

View File

@ -69,7 +69,7 @@ class MoveModuleTargets(Transform):
for node in self.document.traverse(nodes.target): for node in self.document.traverse(nodes.target):
if not node['ids']: if not node['ids']:
continue continue
if (node.has_key('ismod') and if ('ismod' in node and
node.parent.__class__ is nodes.section and node.parent.__class__ is nodes.section and
# index 0 is the section title node # index 0 is the section title node
node.parent.index(node) == 1): node.parent.index(node) == 1):

View File

@ -208,7 +208,7 @@ def get_module_source(modname):
if modname not in sys.modules: if modname not in sys.modules:
try: try:
__import__(modname) __import__(modname)
except Exception, err: except Exception as err:
raise PycodeError('error importing %r' % modname, err) raise PycodeError('error importing %r' % modname, err)
mod = sys.modules[modname] mod = sys.modules[modname]
filename = getattr(mod, '__file__', None) filename = getattr(mod, '__file__', None)
@ -216,12 +216,12 @@ def get_module_source(modname):
if loader and getattr(loader, 'get_filename', None): if loader and getattr(loader, 'get_filename', None):
try: try:
filename = loader.get_filename(modname) filename = loader.get_filename(modname)
except Exception, err: except Exception as err:
raise PycodeError('error getting filename for %r' % filename, err) raise PycodeError('error getting filename for %r' % filename, err)
if filename is None and loader: if filename is None and loader:
try: try:
return 'string', loader.get_source(modname) return 'string', loader.get_source(modname)
except Exception, err: except Exception as err:
raise PycodeError('error getting source for %r' % modname, err) raise PycodeError('error getting source for %r' % modname, err)
if filename is None: if filename is None:
raise PycodeError('no source found for module %r' % modname) raise PycodeError('no source found for module %r' % modname)

View File

@ -240,10 +240,8 @@ class DocFieldTransformer(object):
if is_typefield: if is_typefield:
# filter out only inline nodes; others will result in invalid # filter out only inline nodes; others will result in invalid
# markup being written out # markup being written out
content = filter( content = [n for n in content if isinstance(n, nodes.Inline) or
lambda n: isinstance(n, nodes.Inline) or isinstance(n, nodes.Text)]
isinstance(n, nodes.Text),
content)
if content: if content:
types.setdefault(typename, {})[fieldarg] = content types.setdefault(typename, {})[fieldarg] = content
continue continue

View File

@ -23,7 +23,7 @@ def prepare_docstring(s, ignore=1):
""" """
lines = s.expandtabs().splitlines() lines = s.expandtabs().splitlines()
# Find minimum indentation of any non-blank lines after ignored lines. # Find minimum indentation of any non-blank lines after ignored lines.
margin = sys.maxint margin = sys.maxsize
for line in lines[ignore:]: for line in lines[ignore:]:
content = len(line.lstrip()) content = len(line.lstrip())
if content: if content:
@ -33,7 +33,7 @@ def prepare_docstring(s, ignore=1):
for i in range(ignore): for i in range(ignore):
if i < len(lines): if i < len(lines):
lines[i] = lines[i].lstrip() lines[i] = lines[i].lstrip()
if margin < sys.maxint: if margin < sys.maxsize:
for i in range(ignore, len(lines)): lines[i] = lines[i][margin:] for i in range(ignore, len(lines)): lines[i] = lines[i][margin:]
# Remove any leading blank lines. # Remove any leading blank lines.
while lines and not lines[0]: while lines and not lines[0]:

View File

@ -60,7 +60,7 @@ else: # 2.6, 2.7
def getargspec(func): def getargspec(func):
"""Like inspect.getargspec but supports functools.partial as well.""" """Like inspect.getargspec but supports functools.partial as well."""
if inspect.ismethod(func): if inspect.ismethod(func):
func = func.im_func func = func.__func__
parts = 0, () parts = 0, ()
if type(func) is partial: if type(func) is partial:
keywords = func.keywords keywords = func.keywords
@ -70,8 +70,8 @@ else: # 2.6, 2.7
func = func.func func = func.func
if not inspect.isfunction(func): if not inspect.isfunction(func):
raise TypeError('%r is not a Python function' % func) raise TypeError('%r is not a Python function' % func)
args, varargs, varkw = inspect.getargs(func.func_code) args, varargs, varkw = inspect.getargs(func.__code__)
func_defaults = func.func_defaults func_defaults = func.__defaults__
if func_defaults is None: if func_defaults is None:
func_defaults = [] func_defaults = []
else: else:

View File

@ -77,4 +77,4 @@ def patfilter(names, pat):
if pat not in _pat_cache: if pat not in _pat_cache:
_pat_cache[pat] = re.compile(_translate_pattern(pat)) _pat_cache[pat] = re.compile(_translate_pattern(pat))
match = _pat_cache[pat].match match = _pat_cache[pat].match
return filter(match, names) return list(filter(match, names))

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import re import re
@ -63,7 +64,7 @@ def ensuredir(path):
"""Ensure that a path exists.""" """Ensure that a path exists."""
try: try:
os.makedirs(path) os.makedirs(path)
except OSError, err: except OSError as err:
# 0 for Jython/Win32 # 0 for Jython/Win32
if err.errno not in [0, EEXIST]: if err.errno not in [0, EEXIST]:
raise raise
@ -83,9 +84,9 @@ def walk(top, topdown=True, followlinks=False):
try: try:
fullpath = path.join(top, name) fullpath = path.join(top, name)
except UnicodeError: except UnicodeError:
print >>sys.stderr, ( print('%s:: ERROR: non-ASCII filename not supported on this '
'%s:: ERROR: non-ASCII filename not supported on this ' 'filesystem encoding %r, skipped.' % (name, fs_encoding),
'filesystem encoding %r, skipped.' % (name, fs_encoding)) file=sys.stderr)
continue continue
if path.isdir(fullpath): if path.isdir(fullpath):
dirs.append(name) dirs.append(name)

View File

@ -41,7 +41,7 @@ if sys.version_info >= (3, 0):
source = refactoring_tool._read_python_source(filepath)[0] source = refactoring_tool._read_python_source(filepath)[0]
try: try:
tree = refactoring_tool.refactor_string(source, 'conf.py') tree = refactoring_tool.refactor_string(source, 'conf.py')
except ParseError, err: except ParseError as err:
# do not propagate lib2to3 exceptions # do not propagate lib2to3 exceptions
lineno, offset = err.context[1] lineno, offset = err.context[1]
# try to match ParseError details with SyntaxError details # try to match ParseError details with SyntaxError details

View File

@ -70,7 +70,7 @@ class HTMLTranslator(BaseTranslator):
self.no_smarty = 0 self.no_smarty = 0
self.builder = builder self.builder = builder
self.highlightlang = builder.config.highlight_language self.highlightlang = builder.config.highlight_language
self.highlightlinenothreshold = sys.maxint self.highlightlinenothreshold = sys.maxsize
self.protect_literal_text = 0 self.protect_literal_text = 0
self.permalink_text = builder.config.html_add_permalinks self.permalink_text = builder.config.html_add_permalinks
# support backwards-compatible setting to a bool # support backwards-compatible setting to a bool
@ -260,11 +260,11 @@ class HTMLTranslator(BaseTranslator):
linenos = node.rawsource.count('\n') >= \ linenos = node.rawsource.count('\n') >= \
self.highlightlinenothreshold - 1 self.highlightlinenothreshold - 1
highlight_args = node.get('highlight_args', {}) highlight_args = node.get('highlight_args', {})
if node.has_key('language'): if 'language' in node:
# code-block directives # code-block directives
lang = node['language'] lang = node['language']
highlight_args['force'] = True highlight_args['force'] = True
if node.has_key('linenos'): if 'linenos' in node:
linenos = node['linenos'] linenos = node['linenos']
def warner(msg): def warner(msg):
self.builder.warn(msg, (self.builder.current_docname, node.line)) self.builder.warn(msg, (self.builder.current_docname, node.line))
@ -273,7 +273,7 @@ class HTMLTranslator(BaseTranslator):
**highlight_args) **highlight_args)
starttag = self.starttag(node, 'div', suffix='', starttag = self.starttag(node, 'div', suffix='',
CLASS='highlight-%s' % lang) CLASS='highlight-%s' % lang)
if node.has_key('filename'): if 'filename' in node:
starttag += '<div class="code-block-filename"><tt>%s</tt></div>' % ( starttag += '<div class="code-block-filename"><tt>%s</tt></div>' % (
node['filename'],) node['filename'],)
self.body.append(starttag + highlighted + '</div>\n') self.body.append(starttag + highlighted + '</div>\n')
@ -373,13 +373,13 @@ class HTMLTranslator(BaseTranslator):
if node['uri'].lower().endswith('svg') or \ if node['uri'].lower().endswith('svg') or \
node['uri'].lower().endswith('svgz'): node['uri'].lower().endswith('svgz'):
atts = {'src': node['uri']} atts = {'src': node['uri']}
if node.has_key('width'): if 'width' in node:
atts['width'] = node['width'] atts['width'] = node['width']
if node.has_key('height'): if 'height' in node:
atts['height'] = node['height'] atts['height'] = node['height']
if node.has_key('alt'): if 'alt' in node:
atts['alt'] = node['alt'] atts['alt'] = node['alt']
if node.has_key('align'): if 'align' in node:
self.body.append('<div align="%s" class="align-%s">' % self.body.append('<div align="%s" class="align-%s">' %
(node['align'], node['align'])) (node['align'], node['align']))
self.context.append('</div>\n') self.context.append('</div>\n')
@ -388,21 +388,21 @@ class HTMLTranslator(BaseTranslator):
self.body.append(self.emptytag(node, 'img', '', **atts)) self.body.append(self.emptytag(node, 'img', '', **atts))
return return
if node.has_key('scale'): if 'scale' in node:
# Try to figure out image height and width. Docutils does that too, # Try to figure out image height and width. Docutils does that too,
# but it tries the final file name, which does not necessarily exist # but it tries the final file name, which does not necessarily exist
# yet at the time the HTML file is written. # yet at the time the HTML file is written.
if Image and not (node.has_key('width') if Image and not ('width' in node
and node.has_key('height')): and 'height' in node):
try: try:
im = Image.open(os.path.join(self.builder.srcdir, olduri)) im = Image.open(os.path.join(self.builder.srcdir, olduri))
except (IOError, # Source image can't be found or opened except (IOError, # Source image can't be found or opened
UnicodeError): # PIL doesn't like Unicode paths. UnicodeError): # PIL doesn't like Unicode paths.
pass pass
else: else:
if not node.has_key('width'): if 'width' not in node:
node['width'] = str(im.size[0]) node['width'] = str(im.size[0])
if not node.has_key('height'): if 'height' not in node:
node['height'] = str(im.size[1]) node['height'] = str(im.size[1])
del im del im
BaseTranslator.visit_image(self, node) BaseTranslator.visit_image(self, node)

View File

@ -248,7 +248,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
# the second item is the default for the master file and can be changed # the second item is the default for the master file and can be changed
# by .. highlight:: directive in the master file # by .. highlight:: directive in the master file
self.hlsettingstack = 2 * [[builder.config.highlight_language, self.hlsettingstack = 2 * [[builder.config.highlight_language,
sys.maxint]] sys.maxsize]]
self.footnotestack = [] self.footnotestack = []
self.curfilestack = [] self.curfilestack = []
self.handled_abbrs = set() self.handled_abbrs = set()
@ -1152,7 +1152,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
else: else:
self.builder.warn( self.builder.warn(
'unknown index entry type %s found' % type) 'unknown index entry type %s found' % type)
except ValueError, err: except ValueError as err:
self.builder.warn(str(err)) self.builder.warn(str(err))
raise nodes.SkipNode raise nodes.SkipNode

View File

@ -655,7 +655,7 @@ class TexinfoTranslator(nodes.NodeVisitor):
def visit_reference(self, node): def visit_reference(self, node):
# an xref's target is displayed in Info so we ignore a few # an xref's target is displayed in Info so we ignore a few
# cases for the sake of appearance # cases for the sake of appearance
if isinstance(node.parent, (nodes.title, addnodes.desc_type,)): if isinstance(node.parent, (nodes.title, addnodes.desc_type)):
return return
if isinstance(node[0], nodes.image): if isinstance(node[0], nodes.image):
return return

View File

@ -459,7 +459,7 @@ class TextTranslator(nodes.NodeVisitor):
pass pass
def visit_entry(self, node): def visit_entry(self, node):
if node.has_key('morerows') or node.has_key('morecols'): if 'morerows' in node or 'morecols' in node:
raise NotImplementedError('Column or row spanning cells are ' raise NotImplementedError('Column or row spanning cells are '
'not implemented.') 'not implemented.')
self.new_state(0) self.new_state(0)

View File

@ -53,6 +53,7 @@ coverage.py -a [-d dir] [-o dir1,dir2,...] FILE1 FILE2 ...
Coverage data is saved in the file .coverage by default. Set the Coverage data is saved in the file .coverage by default. Set the
COVERAGE_FILE environment variable to save it somewhere else.""" COVERAGE_FILE environment variable to save it somewhere else."""
from __future__ import print_function
__version__ = "2.85.20080914" # see detailed history at the end of this file. __version__ = "2.85.20080914" # see detailed history at the end of this file.
@ -64,6 +65,7 @@ import re
import string import string
import symbol import symbol
import sys import sys
import atexit
import threading import threading
import token import token
import types import types
@ -187,9 +189,9 @@ class StatementFindingAstVisitor(compiler.visitor.ASTVisitor):
return 0 return 0
# If this line is excluded, or suite_spots maps this line to # If this line is excluded, or suite_spots maps this line to
# another line that is exlcuded, then we're excluded. # another line that is exlcuded, then we're excluded.
elif self.excluded.has_key(lineno) or \ elif lineno in self.excluded or \
self.suite_spots.has_key(lineno) and \ lineno in self.suite_spots and \
self.excluded.has_key(self.suite_spots[lineno][1]): self.suite_spots[lineno][1] in self.excluded:
return 0 return 0
# Otherwise, this is an executable line. # Otherwise, this is an executable line.
else: else:
@ -218,8 +220,8 @@ class StatementFindingAstVisitor(compiler.visitor.ASTVisitor):
lastprev = self.getLastLine(prevsuite) lastprev = self.getLastLine(prevsuite)
firstelse = self.getFirstLine(suite) firstelse = self.getFirstLine(suite)
for l in range(lastprev+1, firstelse): for l in range(lastprev+1, firstelse):
if self.suite_spots.has_key(l): if l in self.suite_spots:
self.doSuite(None, suite, exclude=self.excluded.has_key(l)) self.doSuite(None, suite, exclude=l in self.excluded)
break break
else: else:
self.doSuite(None, suite) self.doSuite(None, suite)
@ -328,9 +330,9 @@ class coverage:
def help(self, error=None): #pragma: no cover def help(self, error=None): #pragma: no cover
if error: if error:
print error print(error)
print print()
print __doc__ print(__doc__)
sys.exit(1) sys.exit(1)
def command_line(self, argv, help_fn=None): def command_line(self, argv, help_fn=None):
@ -354,9 +356,9 @@ class coverage:
long_opts = optmap.values() long_opts = optmap.values()
options, args = getopt.getopt(argv, short_opts, long_opts) options, args = getopt.getopt(argv, short_opts, long_opts)
for o, a in options: for o, a in options:
if optmap.has_key(o): if o in optmap:
settings[optmap[o]] = 1 settings[optmap[o]] = 1
elif optmap.has_key(o + ':'): elif o + ':' in optmap:
settings[optmap[o + ':']] = a settings[optmap[o + ':']] = a
elif o[2:] in long_opts: elif o[2:] in long_opts:
settings[o[2:]] = 1 settings[o[2:]] = 1
@ -398,7 +400,7 @@ class coverage:
self.start() self.start()
import __main__ import __main__
sys.path[0] = os.path.dirname(sys.argv[0]) sys.path[0] = os.path.dirname(sys.argv[0])
execfile(sys.argv[0], __main__.__dict__) exec(compile(open(sys.argv[0]).read(), sys.argv[0], 'exec'), __main__.__dict__)
if settings.get('collect'): if settings.get('collect'):
self.collect() self.collect()
if not args: if not args:
@ -493,7 +495,7 @@ class coverage:
import marshal import marshal
cexecuted = marshal.load(cache) cexecuted = marshal.load(cache)
cache.close() cache.close()
if isinstance(cexecuted, types.DictType): if isinstance(cexecuted, dict):
return cexecuted return cexecuted
else: else:
return {} return {}
@ -514,14 +516,14 @@ class coverage:
def merge_data(self, new_data): def merge_data(self, new_data):
for file_name, file_data in new_data.items(): for file_name, file_data in new_data.items():
if self.cexecuted.has_key(file_name): if file_name in self.cexecuted:
self.merge_file_data(self.cexecuted[file_name], file_data) self.merge_file_data(self.cexecuted[file_name], file_data)
else: else:
self.cexecuted[file_name] = file_data self.cexecuted[file_name] = file_data
def merge_file_data(self, cache_data, new_data): def merge_file_data(self, cache_data, new_data):
for line_number in new_data.keys(): for line_number in new_data.keys():
if not cache_data.has_key(line_number): if line_number not in cache_data:
cache_data[line_number] = new_data[line_number] cache_data[line_number] = new_data[line_number]
def abs_file(self, filename): def abs_file(self, filename):
@ -554,7 +556,7 @@ class coverage:
# normalized case). See [GDR 2001-12-04b, 3.3]. # normalized case). See [GDR 2001-12-04b, 3.3].
def canonical_filename(self, filename): def canonical_filename(self, filename):
if not self.canonical_filename_cache.has_key(filename): if filename not in self.canonical_filename_cache:
f = filename f = filename
if os.path.isabs(f) and not os.path.exists(f): if os.path.isabs(f) and not os.path.exists(f):
if not self.get_zip_data(f): if not self.get_zip_data(f):
@ -578,7 +580,7 @@ class coverage:
# Can't do anything useful with exec'd strings, so skip them. # Can't do anything useful with exec'd strings, so skip them.
continue continue
f = self.canonical_filename(filename) f = self.canonical_filename(filename)
if not self.cexecuted.has_key(f): if f not in self.cexecuted:
self.cexecuted[f] = {} self.cexecuted[f] = {}
self.cexecuted[f][lineno] = 1 self.cexecuted[f][lineno] = 1
self.c = {} self.c = {}
@ -601,7 +603,7 @@ class coverage:
# statements that cross lines. # statements that cross lines.
def analyze_morf(self, morf): def analyze_morf(self, morf):
if self.analysis_cache.has_key(morf): if morf in self.analysis_cache:
return self.analysis_cache[morf] return self.analysis_cache[morf]
filename = self.morf_filename(morf) filename = self.morf_filename(morf)
ext = os.path.splitext(filename)[1] ext = os.path.splitext(filename)[1]
@ -621,7 +623,7 @@ class coverage:
lines, excluded_lines, line_map = self.find_executable_statements( lines, excluded_lines, line_map = self.find_executable_statements(
source, exclude=self.exclude_re source, exclude=self.exclude_re
) )
except SyntaxError, synerr: except SyntaxError as synerr:
raise CoverageException( raise CoverageException(
"Couldn't parse '%s' as Python source: '%s' at line %d" % "Couldn't parse '%s' as Python source: '%s' at line %d" %
(filename, synerr.msg, synerr.lineno) (filename, synerr.msg, synerr.lineno)
@ -792,13 +794,13 @@ class coverage:
def analysis2(self, morf): def analysis2(self, morf):
filename, statements, excluded, line_map = self.analyze_morf(morf) filename, statements, excluded, line_map = self.analyze_morf(morf)
self.canonicalize_filenames() self.canonicalize_filenames()
if not self.cexecuted.has_key(filename): if filename not in self.cexecuted:
self.cexecuted[filename] = {} self.cexecuted[filename] = {}
missing = [] missing = []
for line in statements: for line in statements:
lines = line_map.get(line, [line, line]) lines = line_map.get(line, [line, line])
for l in range(lines[0], lines[1]+1): for l in range(lines[0], lines[1]+1):
if self.cexecuted[filename].has_key(l): if l in self.cexecuted[filename]:
break break
else: else:
missing.append(line) missing.append(line)
@ -837,7 +839,7 @@ class coverage:
def report(self, morfs, show_missing=1, ignore_errors=0, file=None, def report(self, morfs, show_missing=1, ignore_errors=0, file=None,
omit_prefixes=[]): omit_prefixes=[]):
if not isinstance(morfs, types.ListType): if not isinstance(morfs, list):
morfs = [morfs] morfs = [morfs]
# On windows, the shell doesn't expand wildcards. Do it here. # On windows, the shell doesn't expand wildcards. Do it here.
globbed = [] globbed = []
@ -861,8 +863,8 @@ class coverage:
fmt_coverage = fmt_coverage + " %s" fmt_coverage = fmt_coverage + " %s"
if not file: if not file:
file = sys.stdout file = sys.stdout
print >>file, header print(header, file=file)
print >>file, "-" * len(header) print("-" * len(header), file=file)
total_statements = 0 total_statements = 0
total_executed = 0 total_executed = 0
for morf in morfs: for morf in morfs:
@ -878,7 +880,7 @@ class coverage:
args = (name, n, m, pc) args = (name, n, m, pc)
if show_missing: if show_missing:
args = args + (readable,) args = args + (readable,)
print >>file, fmt_coverage % args print(fmt_coverage % args, file=file)
total_statements = total_statements + n total_statements = total_statements + n
total_executed = total_executed + m total_executed = total_executed + m
except KeyboardInterrupt: #pragma: no cover except KeyboardInterrupt: #pragma: no cover
@ -886,9 +888,9 @@ class coverage:
except: except:
if not ignore_errors: if not ignore_errors:
typ, msg = sys.exc_info()[:2] typ, msg = sys.exc_info()[:2]
print >>file, fmt_err % (name, typ, msg) print(fmt_err % (name, typ, msg), file=file)
if len(morfs) > 1: if len(morfs) > 1:
print >>file, "-" * len(header) print("-" * len(header), file=file)
if total_statements > 0: if total_statements > 0:
pc = 100.0 * total_executed / total_statements pc = 100.0 * total_executed / total_statements
else: else:
@ -896,7 +898,7 @@ class coverage:
args = ("TOTAL", total_statements, total_executed, pc) args = ("TOTAL", total_statements, total_executed, pc)
if show_missing: if show_missing:
args = args + ("",) args = args + ("",)
print >>file, fmt_coverage % args print(fmt_coverage % args, file=file)
# annotate(morfs, ignore_errors). # annotate(morfs, ignore_errors).
@ -1006,14 +1008,7 @@ def annotate(*args, **kw):
def annotate_file(*args, **kw): def annotate_file(*args, **kw):
return the_coverage.annotate_file(*args, **kw) return the_coverage.annotate_file(*args, **kw)
# Save coverage data when Python exits. (The atexit module wasn't atexit.register(the_coverage.save)
# introduced until Python 2.0, so use sys.exitfunc when it's not
# available.)
try:
import atexit
atexit.register(the_coverage.save)
except ImportError:
sys.exitfunc = the_coverage.save
def main(): def main():
the_coverage.command_line(sys.argv[1:]) the_coverage.command_line(sys.argv[1:])

View File

@ -79,6 +79,7 @@
# -------------------------------------------------------------------- # --------------------------------------------------------------------
from __future__ import generators from __future__ import generators
from __future__ import absolute_import
__all__ = [ __all__ = [
# public symbols # public symbols
@ -144,7 +145,7 @@ class _SimpleElementPath(object):
return result return result
try: try:
import ElementPath from . import ElementPath
except ImportError: except ImportError:
# FIXME: issue warning in this case? # FIXME: issue warning in this case?
ElementPath = _SimpleElementPath() ElementPath = _SimpleElementPath()
@ -1524,7 +1525,7 @@ class XMLParser(object):
def feed(self, data): def feed(self, data):
try: try:
self._parser.Parse(data, 0) self._parser.Parse(data, 0)
except self._error, v: except self._error as v:
self._raiseerror(v) self._raiseerror(v)
## ##
@ -1536,7 +1537,7 @@ class XMLParser(object):
def close(self): def close(self):
try: try:
self._parser.Parse("", 1) # end of data self._parser.Parse("", 1) # end of data
except self._error, v: except self._error as v:
self._raiseerror(v) self._raiseerror(v)
tree = self.target.close() tree = self.target.close()
del self.target, self._parser # get rid of circular references del self.target, self._parser # get rid of circular references

View File

@ -1,3 +1,4 @@
from __future__ import absolute_import
# #
# ElementTree # ElementTree
# $Id$ # $Id$
@ -53,7 +54,7 @@ import htmlentitydefs
import re, string, sys import re, string, sys
import mimetools, StringIO import mimetools, StringIO
import ElementTree from . import ElementTree
AUTOCLOSE = "p", "li", "tr", "th", "td", "head", "body" AUTOCLOSE = "p", "li", "tr", "th", "td", "head", "body"
IGNOREEND = "img", "hr", "meta", "link", "br" IGNOREEND = "img", "hr", "meta", "link", "br"

View File

@ -178,7 +178,7 @@ class path(unicode):
""" """
return os.path.lexists(self) return os.path.lexists(self)
def makedirs(self, mode=0777): def makedirs(self, mode=0o777):
""" """
Recursively create directories. Recursively create directories.
""" """

View File

@ -1,2 +1,2 @@
print "line 1" print("line 1")
print "line 2" print("line 2")

View File

@ -9,6 +9,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import sys import sys
from os import path, chdir, listdir, environ from os import path, chdir, listdir, environ

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import gettext import gettext
import os import os
@ -63,8 +64,8 @@ def test_gettext(app):
else: else:
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
if p.returncode != 0: if p.returncode != 0:
print stdout print(stdout)
print stderr print(stderr)
assert False, 'msginit exited with return code %s' % \ assert False, 'msginit exited with return code %s' % \
p.returncode p.returncode
assert (app.outdir / 'en_US.po').isfile(), 'msginit failed' assert (app.outdir / 'en_US.po').isfile(), 'msginit failed'
@ -77,8 +78,8 @@ def test_gettext(app):
else: else:
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
if p.returncode != 0: if p.returncode != 0:
print stdout print(stdout)
print stderr print(stderr)
assert False, 'msgfmt exited with return code %s' % \ assert False, 'msgfmt exited with return code %s' % \
p.returncode p.returncode
assert (app.outdir / 'en' / 'LC_MESSAGES' / 'test_root.mo').isfile(), \ assert (app.outdir / 'en' / 'LC_MESSAGES' / 'test_root.mo').isfile(), \
@ -106,7 +107,7 @@ def test_gettext_index_entries(app):
return None return None
pot = (app.outdir / 'index_entries.pot').text(encoding='utf-8') pot = (app.outdir / 'index_entries.pot').text(encoding='utf-8')
msgids = filter(None, map(msgid_getter, pot.splitlines())) msgids = [_f for _f in map(msgid_getter, pot.splitlines()) if _f]
expected_msgids = [ expected_msgids = [
"i18n with index entries", "i18n with index entries",

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import re import re
@ -90,8 +91,8 @@ def test_latex(app):
else: else:
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
if p.returncode != 0: if p.returncode != 0:
print stdout print(stdout)
print stderr print(stderr)
del app.cleanup_trees[:] del app.cleanup_trees[:]
assert False, 'latex exited with return code %s' % p.returncode assert False, 'latex exited with return code %s' % p.returncode
finally: finally:

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import re import re
@ -61,8 +62,8 @@ def test_texinfo(app):
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
retcode = p.returncode retcode = p.returncode
if retcode != 0: if retcode != 0:
print stdout print(stdout)
print stderr print(stderr)
del app.cleanup_trees[:] del app.cleanup_trees[:]
assert False, 'makeinfo exited with return code %s' % retcode assert False, 'makeinfo exited with return code %s' % retcode
finally: finally:

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import sys import sys
import StringIO import StringIO
@ -24,7 +25,7 @@ def test_build(app):
cleanup_called = 0 cleanup_called = 0
app.builder.build_all() app.builder.build_all()
if app.statuscode != 0: if app.statuscode != 0:
print >>sys.stderr, status.getvalue() print(status.getvalue(), file=sys.stderr)
assert False, 'failures in doctests' assert False, 'failures in doctests'
# in doctest.txt, there are two named groups and the default group, # in doctest.txt, there are two named groups and the default group,
# so the cleanup function must be called three times # so the cleanup function must be called three times

View File

@ -9,6 +9,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import os import os
import re import re
@ -58,8 +59,8 @@ def setup_module():
else: else:
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
if p.returncode != 0: if p.returncode != 0:
print stdout print(stdout)
print stderr print(stderr)
assert False, \ assert False, \
'msgfmt exited with return code %s' % p.returncode 'msgfmt exited with return code %s' % p.returncode
assert mo.isfile(), 'msgfmt failed' assert mo.isfile(), 'msgfmt failed'
@ -84,7 +85,7 @@ def elem_gettexts(elem):
yield s yield s
if e.tail: if e.tail:
yield e.tail yield e.tail
return filter(None, [s.strip() for s in itertext(elem)]) return [_f for _f in [s.strip() for s in itertext(elem)] if _f]
def elem_getref(elem): def elem_getref(elem):

View File

@ -53,8 +53,7 @@ def test_sectioning(app):
app.env.process_only_nodes(doctree, app.builder) app.env.process_only_nodes(doctree, app.builder)
parts = [getsects(n) parts = [getsects(n)
for n in filter(lambda n: isinstance(n, nodes.section), for n in [_n for _n in doctree.children if isinstance(_n, nodes.section)]]
doctree.children)]
for i, s in enumerate(parts): for i, s in enumerate(parts):
testsects(str(i+1) + '.', s, 4) testsects(str(i+1) + '.', s, 4)
assert len(parts) == 4, 'Expected 4 document level headings, got:\n%s' % \ assert len(parts) == 4, 'Expected 4 document level headings, got:\n%s' % \

View File

@ -62,7 +62,7 @@ def raises_msg(exc, msg, func, *args, **kwds):
""" """
try: try:
func(*args, **kwds) func(*args, **kwds)
except exc, err: except exc as err:
assert msg in str(err), "\"%s\" not in \"%s\"" % (msg, err) assert msg in str(err), "\"%s\" not in \"%s\"" % (msg, err)
else: else:
raise AssertionError('%s did not raise %s' % raise AssertionError('%s did not raise %s' %

View File

@ -10,6 +10,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
from __future__ import print_function
import sys, os, re import sys, os, re
import cStringIO import cStringIO
@ -54,7 +55,7 @@ if sys.version_info < (3, 0):
def check_syntax(fn, lines): def check_syntax(fn, lines):
try: try:
compile(b('').join(lines), fn, "exec") compile(b('').join(lines), fn, "exec")
except SyntaxError, err: except SyntaxError as err:
yield 0, "not compilable: %s" % err yield 0, "not compilable: %s" % err
@ -77,9 +78,9 @@ def check_style_and_encoding(fn, lines):
yield lno+1, 'using == None/True/False' yield lno+1, 'using == None/True/False'
try: try:
line.decode(encoding) line.decode(encoding)
except UnicodeDecodeError, err: except UnicodeDecodeError as err:
yield lno+1, "not decodable: %s\n Line: %r" % (err, line) yield lno+1, "not decodable: %s\n Line: %r" % (err, line)
except LookupError, err: except LookupError as err:
yield 0, "unknown encoding: %s" % encoding yield 0, "unknown encoding: %s" % encoding
encoding = 'latin1' encoding = 'latin1'
@ -183,7 +184,7 @@ def main(argv):
elif len(args) == 1: elif len(args) == 1:
path = args[0] path = args[0]
else: else:
print args print(args)
parser.error('No more then one path supported') parser.error('No more then one path supported')
verbose = options.verbose verbose = options.verbose
@ -214,7 +215,7 @@ def main(argv):
continue continue
if verbose: if verbose:
print "Checking %s..." % fn print("Checking %s..." % fn)
try: try:
f = open(fn, 'rb') f = open(fn, 'rb')
@ -222,8 +223,8 @@ def main(argv):
lines = list(f) lines = list(f)
finally: finally:
f.close() f.close()
except (IOError, OSError), err: except (IOError, OSError) as err:
print "%s: cannot open: %s" % (fn, err) print("%s: cannot open: %s" % (fn, err))
num += 1 num += 1
continue continue
@ -231,15 +232,15 @@ def main(argv):
if not in_check_pkg and checker.only_pkg: if not in_check_pkg and checker.only_pkg:
continue continue
for lno, msg in checker(fn, lines): for lno, msg in checker(fn, lines):
print >>out, "%s:%d: %s" % (fn, lno, msg) print("%s:%d: %s" % (fn, lno, msg), file=out)
num += 1 num += 1
if verbose: if verbose:
print print()
if num == 0: if num == 0:
print "No errors found." print("No errors found.")
else: else:
print out.getvalue().rstrip('\n') print(out.getvalue().rstrip('\n'))
print "%d error%s found." % (num, num > 1 and "s" or "") print("%d error%s found." % (num, num > 1 and "s" or ""))
return int(num > 0) return int(num > 0)

View File

@ -38,6 +38,7 @@ file is generated with shutil.copy(), but some corner cases regarding
user/group and permissions could leave the backup file more readable that user/group and permissions could leave the backup file more readable that
you'd prefer. You can always use the --nobackup option to prevent this. you'd prefer. You can always use the --nobackup option to prevent this.
""" """
from __future__ import print_function
__version__ = "1" __version__ = "1"
@ -59,8 +60,8 @@ makebackup = True
def usage(msg=None): def usage(msg=None):
if msg is not None: if msg is not None:
print >> sys.stderr, msg print(msg, file=sys.stderr)
print >> sys.stderr, __doc__ print(__doc__, file=sys.stderr)
def errprint(*args): def errprint(*args):
sep = "" sep = ""
@ -75,7 +76,7 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "drnvh", opts, args = getopt.getopt(sys.argv[1:], "drnvh",
["dryrun", "recurse", "nobackup", "verbose", "help"]) ["dryrun", "recurse", "nobackup", "verbose", "help"])
except getopt.error, msg: except getopt.error as msg:
usage(msg) usage(msg)
return return
for o, a in opts: for o, a in opts:
@ -101,7 +102,7 @@ def main():
def check(file): def check(file):
if os.path.isdir(file) and not os.path.islink(file): if os.path.isdir(file) and not os.path.islink(file):
if verbose: if verbose:
print "listing directory", file print("listing directory", file)
names = os.listdir(file) names = os.listdir(file)
for name in names: for name in names:
fullname = os.path.join(file, name) fullname = os.path.join(file, name)
@ -113,10 +114,10 @@ def check(file):
return return
if verbose: if verbose:
print "checking", file, "...", print("checking", file, "...", end=' ')
try: try:
f = open(file) f = open(file)
except IOError, msg: except IOError as msg:
errprint("%s: I/O Error: %s" % (file, str(msg))) errprint("%s: I/O Error: %s" % (file, str(msg)))
return return
@ -124,24 +125,24 @@ def check(file):
f.close() f.close()
if r.run(): if r.run():
if verbose: if verbose:
print "changed." print("changed.")
if dryrun: if dryrun:
print "But this is a dry run, so leaving it alone." print("But this is a dry run, so leaving it alone.")
if not dryrun: if not dryrun:
bak = file + ".bak" bak = file + ".bak"
if makebackup: if makebackup:
shutil.copyfile(file, bak) shutil.copyfile(file, bak)
if verbose: if verbose:
print "backed up", file, "to", bak print("backed up", file, "to", bak)
f = open(file, "w") f = open(file, "w")
r.write(f) r.write(f)
f.close() f.close()
if verbose: if verbose:
print "wrote new", file print("wrote new", file)
return True return True
else: else:
if verbose: if verbose:
print "unchanged." print("unchanged.")
return False return False
def _rstrip(line, JUNK='\n \t'): def _rstrip(line, JUNK='\n \t'):
@ -262,7 +263,7 @@ class Reindenter:
return line return line
# Line-eater for tokenize. # Line-eater for tokenize.
def tokeneater(self, type, token, (sline, scol), end, line, def tokeneater(self, type, token, position, end, line,
INDENT=tokenize.INDENT, INDENT=tokenize.INDENT,
DEDENT=tokenize.DEDENT, DEDENT=tokenize.DEDENT,
NEWLINE=tokenize.NEWLINE, NEWLINE=tokenize.NEWLINE,
@ -285,7 +286,7 @@ class Reindenter:
elif type == COMMENT: elif type == COMMENT:
if self.find_stmt: if self.find_stmt:
self.stats.append((sline, -1)) self.stats.append((position[0], -1))
# but we're still looking for a new stmt, so leave # but we're still looking for a new stmt, so leave
# find_stmt alone # find_stmt alone
@ -298,7 +299,7 @@ class Reindenter:
# ENDMARKER. # ENDMARKER.
self.find_stmt = 0 self.find_stmt = 0
if line: # not endmarker if line: # not endmarker
self.stats.append((sline, self.level)) self.stats.append((position[0], self.level))
# Count number of leading blanks. # Count number of leading blanks.
def getlspace(line): def getlspace(line):