Import Upstream version 2.7.18

This commit is contained in:
geos_one
2025-08-15 16:28:06 +02:00
commit ba1f69ab39
4521 changed files with 1778434 additions and 0 deletions

View File

@@ -0,0 +1,121 @@
# -*- coding: utf-8 -*-
"""
c_annotations.py
~~~~~~~~~~~~~~~~
Supports annotations for C API elements:
* reference count annotations for C API functions. Based on
refcount.py and anno-api.py in the old Python documentation tools.
* stable API annotations
Usage: Set the `refcount_file` config value to the path to the reference
count data file.
:copyright: Copyright 2007-2014 by Georg Brandl.
:license: Python license.
"""
from os import path
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.domains.c import CObject
class RCEntry:
def __init__(self, name):
self.name = name
self.args = []
self.result_type = ''
self.result_refs = None
class Annotations(dict):
@classmethod
def fromfile(cls, filename):
d = cls()
fp = open(filename, 'r')
try:
for line in fp:
line = line.strip()
if line[:1] in ("", "#"):
# blank lines and comments
continue
parts = line.split(":", 4)
if len(parts) != 5:
raise ValueError("Wrong field count in %r" % line)
function, type, arg, refcount, comment = parts
# Get the entry, creating it if needed:
try:
entry = d[function]
except KeyError:
entry = d[function] = RCEntry(function)
if not refcount or refcount == "null":
refcount = None
else:
refcount = int(refcount)
# Update the entry with the new parameter or the result
# information.
if arg:
entry.args.append((arg, type, refcount))
else:
entry.result_type = type
entry.result_refs = refcount
finally:
fp.close()
return d
def add_annotations(self, app, doctree):
for node in doctree.traverse(addnodes.desc_content):
par = node.parent
if par['domain'] != 'c':
continue
if par['stableabi']:
node.insert(0, nodes.emphasis(' Part of the stable ABI.',
' Part of the stable ABI.',
classes=['stableabi']))
if par['objtype'] != 'function':
continue
if not par[0].has_key('names') or not par[0]['names']:
continue
name = par[0]['names'][0]
if name.startswith("c."):
name = name[2:]
entry = self.get(name)
if not entry:
continue
elif entry.result_type not in ("PyObject*", "PyVarObject*"):
continue
if entry.result_refs is None:
rc = 'Return value: Always NULL.'
elif entry.result_refs:
rc = 'Return value: New reference.'
else:
rc = 'Return value: Borrowed reference.'
node.insert(0, nodes.emphasis(rc, rc, classes=['refcount']))
def init_annotations(app):
refcounts = Annotations.fromfile(
path.join(app.srcdir, app.config.refcount_file))
app.connect('doctree-read', refcounts.add_annotations)
def setup(app):
app.add_config_value('refcount_file', '', True)
app.connect('builder-inited', init_annotations)
# monkey-patch C object...
CObject.option_spec = {
'noindex': directives.flag,
'stableabi': directives.flag,
}
old_handle_signature = CObject.handle_signature
def new_handle_signature(self, sig, signode):
signode.parent['stableabi'] = 'stableabi' in self.options
return old_handle_signature(self, sig, signode)
CObject.handle_signature = new_handle_signature
return {'version': '1.0', 'parallel_read_safe': True}

View File

@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
"""
patchlevel.py
~~~~~~~~~~~~~
Extract version info from Include/patchlevel.h.
Adapted from Doc/tools/getversioninfo.
:copyright: 2007-2008 by Georg Brandl.
:license: Python license.
"""
import os
import re
import sys
def get_header_version_info(srcdir):
patchlevel_h = os.path.join(srcdir, '..', 'Include', 'patchlevel.h')
# This won't pick out all #defines, but it will pick up the ones we
# care about.
rx = re.compile(r'\s*#define\s+([a-zA-Z][a-zA-Z_0-9]*)\s+([a-zA-Z_0-9]+)')
d = {}
f = open(patchlevel_h)
try:
for line in f:
m = rx.match(line)
if m is not None:
name, value = m.group(1, 2)
d[name] = value
finally:
f.close()
release = version = '%s.%s' % (d['PY_MAJOR_VERSION'], d['PY_MINOR_VERSION'])
micro = int(d['PY_MICRO_VERSION'])
if micro != 0:
release += '.' + str(micro)
level = d['PY_RELEASE_LEVEL']
suffixes = {
'PY_RELEASE_LEVEL_ALPHA': 'a',
'PY_RELEASE_LEVEL_BETA': 'b',
'PY_RELEASE_LEVEL_GAMMA': 'rc',
}
if level != 'PY_RELEASE_LEVEL_FINAL':
release += suffixes[level] + str(int(d['PY_RELEASE_SERIAL']))
return version, release
def get_sys_version_info():
major, minor, micro, level, serial = sys.version_info
release = version = '%s.%s' % (major, minor)
if micro:
release += '.%s' % micro
if level != 'final':
release += '%s%s' % (level[0], serial)
return version, release
def get_version_info():
try:
return get_header_version_info('.')
except (IOError, OSError):
version, release = get_sys_version_info()
print >>sys.stderr, 'Can\'t get version info from Include/patchlevel.h, ' \
'using version of this interpreter (%s).' % release
return version, release
if __name__ == '__main__':
print(get_header_version_info('.')[1])

View File

@@ -0,0 +1,265 @@
# -*- coding: utf-8 -*-
"""
pyspecific.py
~~~~~~~~~~~~~
Sphinx extension with Python doc-specific markup.
:copyright: 2008-2014 by Georg Brandl.
:license: Python license.
"""
ISSUE_URI = 'https://bugs.python.org/issue%s'
SOURCE_URI = 'https://github.com/python/cpython/tree/2.7/%s'
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from sphinx.util.nodes import split_explicit_title
from sphinx.writers.html import HTMLTranslator
from sphinx.writers.latex import LaTeXTranslator
from sphinx.writers.text import TextTranslator
# monkey-patch reST parser to disable alphabetic and roman enumerated lists
from docutils.parsers.rst.states import Body
Body.enum.converters['loweralpha'] = \
Body.enum.converters['upperalpha'] = \
Body.enum.converters['lowerroman'] = \
Body.enum.converters['upperroman'] = lambda x: None
# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
# doctest docs themselves
orig_visit_literal_block = HTMLTranslator.visit_literal_block
def new_visit_literal_block(self, node):
meta = self.builder.env.metadata[self.builder.current_docname]
old_trim_doctest_flags = self.highlighter.trim_doctest_flags
if 'keepdoctest' in meta:
self.highlighter.trim_doctest_flags = False
try:
orig_visit_literal_block(self, node)
finally:
self.highlighter.trim_doctest_flags = old_trim_doctest_flags
HTMLTranslator.visit_literal_block = new_visit_literal_block
orig_depart_literal_block = LaTeXTranslator.depart_literal_block
def new_depart_literal_block(self, node):
meta = self.builder.env.metadata[self.curfilestack[-1]]
old_trim_doctest_flags = self.highlighter.trim_doctest_flags
if 'keepdoctest' in meta:
self.highlighter.trim_doctest_flags = False
try:
orig_depart_literal_block(self, node)
finally:
self.highlighter.trim_doctest_flags = old_trim_doctest_flags
LaTeXTranslator.depart_literal_block = new_depart_literal_block
# Support for marking up and linking to bugs.python.org issues
def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
issue = utils.unescape(text)
text = 'bpo-'+ issue
refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
return [refnode], []
# Support for linking to Python source files easily
def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
has_t, title, target = split_explicit_title(text)
title = utils.unescape(title)
target = utils.unescape(target)
refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
return [refnode], []
# Support for marking up implementation details
class ImplementationDetail(Directive):
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
def run(self):
pnode = nodes.compound(classes=['impl-detail'])
content = self.content
add_text = nodes.strong('CPython implementation detail:',
'CPython implementation detail:')
if self.arguments:
n, m = self.state.inline_text(self.arguments[0], self.lineno)
pnode.append(nodes.paragraph('', '', *(n + m)))
self.state.nested_parse(content, self.content_offset, pnode)
if pnode.children and isinstance(pnode[0], nodes.paragraph):
pnode[0].insert(0, add_text)
pnode[0].insert(1, nodes.Text(' '))
else:
pnode.insert(0, nodes.paragraph('', '', add_text))
return [pnode]
# Support for documenting decorators
from sphinx import addnodes
from sphinx.domains.python import PyModulelevel, PyClassmember
class PyDecoratorMixin(object):
def handle_signature(self, sig, signode):
ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
signode.insert(0, addnodes.desc_addname('@', '@'))
return ret
def needs_arglist(self):
return False
class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
def run(self):
# a decorator function is a function after all
self.name = 'py:function'
return PyModulelevel.run(self)
class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
def run(self):
self.name = 'py:method'
return PyClassmember.run(self)
# Support for building "topic help" for pydoc
pydoc_topic_labels = [
'assert', 'assignment', 'atom-identifiers', 'atom-literals',
'attribute-access', 'attribute-references', 'augassign', 'binary',
'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans',
'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
'context-managers', 'continue', 'conversions', 'customization', 'debugger',
'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'exec', 'execmodel',
'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
'lambda', 'lists', 'naming', 'numbers', 'numeric-types',
'objects', 'operator-summary', 'pass', 'power', 'print', 'raise', 'return',
'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
]
from os import path
from time import asctime
from pprint import pformat
from docutils.io import StringOutput
from docutils.utils import new_document
from sphinx.builders import Builder
from sphinx.writers.text import TextWriter
class PydocTopicsBuilder(Builder):
name = 'pydoc-topics'
default_translator_class = TextTranslator
def init(self):
self.topics = {}
self.secnumbers = {}
def get_outdated_docs(self):
return 'all pydoc topics'
def get_target_uri(self, docname, typ=None):
return '' # no URIs
def write(self, *ignored):
try: # sphinx>=1.6
from sphinx.util import status_iterator
except ImportError: # sphinx<1.6
status_iterator = self.status_iterator
writer = TextWriter(self)
for label in status_iterator(pydoc_topic_labels,
'building topics... ',
length=len(pydoc_topic_labels)):
if label not in self.env.domaindata['std']['labels']:
self.warn('label %r not in documentation' % label)
continue
docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
doctree = self.env.get_and_resolve_doctree(docname, self)
document = new_document('<section node>')
document.append(doctree.ids[labelid])
destination = StringOutput(encoding='utf-8')
writer.write(document, destination)
self.topics[label] = writer.output
def finish(self):
f = open(path.join(self.outdir, 'topics.py'), 'wb')
try:
f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
finally:
f.close()
# Support for checking for suspicious markup
import suspicious
# Support for documenting Opcodes
import re
opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
def parse_opcode_signature(env, sig, signode):
"""Transform an opcode signature into RST nodes."""
m = opcode_sig_re.match(sig)
if m is None:
raise ValueError
opname, arglist = m.groups()
signode += addnodes.desc_name(opname, opname)
if arglist is not None:
paramlist = addnodes.desc_parameterlist()
signode += paramlist
paramlist += addnodes.desc_parameter(arglist, arglist)
return opname.strip()
# Support for documenting pdb commands
pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
# later...
#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
# [.,:]+ | # punctuation
# [\[\]()] | # parens
# \s+ # whitespace
# ''', re.X)
def parse_pdb_command(env, sig, signode):
"""Transform a pdb command signature into RST nodes."""
m = pdbcmd_sig_re.match(sig)
if m is None:
raise ValueError
name, args = m.groups()
fullname = name.replace('(', '').replace(')', '')
signode += addnodes.desc_name(name, name)
if args:
signode += addnodes.desc_addname(' '+args, ' '+args)
return fullname
def setup(app):
app.add_role('issue', issue_role)
app.add_role('source', source_role)
app.add_directive('impl-detail', ImplementationDetail)
app.add_builder(PydocTopicsBuilder)
app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
app.add_object_type('opcode', 'opcode', '%s (opcode)', parse_opcode_signature)
app.add_object_type('pdbcommand', 'pdbcmd', '%s (pdb command)', parse_pdb_command)
app.add_object_type('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
return {'version': '1.0', 'parallel_read_safe': True}

View File

@@ -0,0 +1,275 @@
"""
Try to detect suspicious constructs, resembling markup
that has leaked into the final output.
Suspicious lines are reported in a comma-separated-file,
``suspicious.csv``, located in the output directory.
The file is utf-8 encoded, and each line contains four fields:
* document name (normalized)
* line number in the source document
* problematic text
* complete line showing the problematic text in context
It is common to find many false positives. To avoid reporting them
again and again, they may be added to the ``ignored.csv`` file
(located in the configuration directory). The file has the same
format as ``suspicious.csv`` with a few differences:
- each line defines a rule; if the rule matches, the issue
is ignored.
- line number may be empty (that is, nothing between the
commas: ",,"). In this case, line numbers are ignored (the
rule matches anywhere in the file).
- the last field does not have to be a complete line; some
surrounding text (never more than a line) is enough for
context.
Rules are processed sequentially. A rule matches when:
* document names are the same
* problematic texts are the same
* line numbers are close to each other (5 lines up or down)
* the rule text is completely contained into the source line
The simplest way to create the ignored.csv file is by copying
undesired entries from suspicious.csv (possibly trimming the last
field.)
Copyright 2009 Gabriel A. Genellina
"""
import os
import re
import csv
import sys
from docutils import nodes
from sphinx.builders import Builder
import sphinx.util
detect_all = re.compile(r'''
::(?=[^=])| # two :: (but NOT ::=)
:[a-zA-Z][a-zA-Z0-9]+| # :foo
`| # ` (seldom used by itself)
(?<!\.)\.\.[ \t]*\w+: # .. foo: (but NOT ... else:)
''', re.UNICODE | re.VERBOSE).finditer
py3 = sys.version_info >= (3, 0)
class Rule:
def __init__(self, docname, lineno, issue, line):
"""A rule for ignoring issues"""
self.docname = docname # document to which this rule applies
self.lineno = lineno # line number in the original source;
# this rule matches only near that.
# None -> don't care
self.issue = issue # the markup fragment that triggered this rule
self.line = line # text of the container element (single line only)
self.used = False
def __repr__(self):
return '{0.docname},,{0.issue},{0.line}'.format(self)
class dialect(csv.excel):
"""Our dialect: uses only linefeed as newline."""
lineterminator = '\n'
class CheckSuspiciousMarkupBuilder(Builder):
"""
Checks for possibly invalid markup that may leak into the output.
"""
name = 'suspicious'
logger = sphinx.util.logging.getLogger("CheckSuspiciousMarkupBuilder")
def init(self):
# create output file
self.log_file_name = os.path.join(self.outdir, 'suspicious.csv')
open(self.log_file_name, 'w').close()
# load database of previously ignored issues
self.load_rules(os.path.join(os.path.dirname(__file__), '..',
'susp-ignored.csv'))
def get_outdated_docs(self):
return self.env.found_docs
def get_target_uri(self, docname, typ=None):
return ''
def prepare_writing(self, docnames):
pass
def write_doc(self, docname, doctree):
# set when any issue is encountered in this document
self.any_issue = False
self.docname = docname
visitor = SuspiciousVisitor(doctree, self)
doctree.walk(visitor)
def finish(self):
unused_rules = [rule for rule in self.rules if not rule.used]
if unused_rules:
self.warn('Found %s/%s unused rules:' %
(len(unused_rules), len(self.rules)))
for rule in unused_rules:
self.logger.info(repr(rule))
return
def check_issue(self, line, lineno, issue):
if not self.is_ignored(line, lineno, issue):
self.report_issue(line, lineno, issue)
def is_ignored(self, line, lineno, issue):
"""Determine whether this issue should be ignored."""
docname = self.docname
for rule in self.rules:
if rule.docname != docname: continue
if rule.issue != issue: continue
# Both lines must match *exactly*. This is rather strict,
# and probably should be improved.
# Doing fuzzy matches with levenshtein distance could work,
# but that means bringing other libraries...
# Ok, relax that requirement: just check if the rule fragment
# is contained in the document line
if rule.line not in line: continue
# Check both line numbers. If they're "near"
# this rule matches. (lineno=None means "don't care")
if (rule.lineno is not None) and \
abs(rule.lineno - lineno) > 5: continue
# if it came this far, the rule matched
rule.used = True
return True
return False
def report_issue(self, text, lineno, issue):
self.any_issue = True
self.write_log_entry(lineno, issue, text)
if py3:
self.warn('[%s:%d] "%s" found in "%-.120s"' %
(self.docname, lineno, issue, text))
else:
self.warn('[%s:%d] "%s" found in "%-.120s"' % (
self.docname.encode(sys.getdefaultencoding(),'replace'),
lineno,
issue.encode(sys.getdefaultencoding(),'replace'),
text.strip().encode(sys.getdefaultencoding(),'replace')))
self.app.statuscode = 1
def write_log_entry(self, lineno, issue, text):
if py3:
f = open(self.log_file_name, 'a')
writer = csv.writer(f, dialect)
writer.writerow([self.docname, lineno, issue, text.strip()])
f.close()
else:
f = open(self.log_file_name, 'ab')
writer = csv.writer(f, dialect)
writer.writerow([self.docname.encode('utf-8'),
lineno,
issue.encode('utf-8'),
text.strip().encode('utf-8')])
f.close()
def load_rules(self, filename):
"""Load database of previously ignored issues.
A csv file, with exactly the same format as suspicious.csv
Fields: document name (normalized), line number, issue, surrounding text
"""
self.logger.info("loading ignore rules... ", nonl=1)
self.rules = rules = []
try:
if py3:
f = open(filename, 'r')
else:
f = open(filename, 'rb')
except IOError:
return
for i, row in enumerate(csv.reader(f)):
if len(row) != 4:
raise ValueError(
"wrong format in %s, line %d: %s" % (filename, i+1, row))
docname, lineno, issue, text = row
if lineno:
lineno = int(lineno)
else:
lineno = None
if not py3:
docname = docname.decode('utf-8')
issue = issue.decode('utf-8')
text = text.decode('utf-8')
rule = Rule(docname, lineno, issue, text)
rules.append(rule)
f.close()
self.logger.info('done, %d rules loaded' % len(self.rules))
def get_lineno(node):
"""Obtain line number information for a node."""
lineno = None
while lineno is None and node:
node = node.parent
lineno = node.line
return lineno
def extract_line(text, index):
"""text may be a multiline string; extract
only the line containing the given character index.
>>> extract_line("abc\ndefgh\ni", 6)
>>> 'defgh'
>>> for i in (0, 2, 3, 4, 10):
... print extract_line("abc\ndefgh\ni", i)
abc
abc
abc
defgh
defgh
i
"""
p = text.rfind('\n', 0, index) + 1
q = text.find('\n', index)
if q < 0:
q = len(text)
return text[p:q]
class SuspiciousVisitor(nodes.GenericNodeVisitor):
lastlineno = 0
def __init__(self, document, builder):
nodes.GenericNodeVisitor.__init__(self, document)
self.builder = builder
def default_visit(self, node):
if isinstance(node, (nodes.Text, nodes.image)): # direct text containers
text = node.astext()
# lineno seems to go backwards sometimes (?)
self.lastlineno = lineno = max(get_lineno(node) or 0, self.lastlineno)
seen = set() # don't report the same issue more than only once per line
for match in detect_all(text):
issue = match.group()
line = extract_line(text, match.start())
if (issue, line) not in seen:
self.builder.check_issue(line, lineno, issue)
seen.add((issue, line))
unknown_visit = default_visit
def visit_document(self, node):
self.lastlineno = 0
def visit_comment(self, node):
# ignore comments -- too much false positives.
# (although doing this could miss some errors;
# there were two sections "commented-out" by mistake
# in the Python docs that would not be caught)
raise nodes.SkipNode

233
Doc/tools/rstlint.py Executable file
View File

@@ -0,0 +1,233 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Check for stylistic and formal issues in .rst and .py
# files included in the documentation.
#
# 01/2009, Georg Brandl
# TODO: - wrong versions in versionadded/changed
# - wrong markup after versionchanged directive
from __future__ import with_statement
import os
import re
import sys
import getopt
from os.path import join, splitext, abspath, exists
from collections import defaultdict
directives = [
# standard docutils ones
'admonition', 'attention', 'caution', 'class', 'compound', 'container',
'contents', 'csv-table', 'danger', 'date', 'default-role', 'epigraph',
'error', 'figure', 'footer', 'header', 'highlights', 'hint', 'image',
'important', 'include', 'line-block', 'list-table', 'meta', 'note',
'parsed-literal', 'pull-quote', 'raw', 'replace',
'restructuredtext-test-directive', 'role', 'rubric', 'sectnum', 'sidebar',
'table', 'target-notes', 'tip', 'title', 'topic', 'unicode', 'warning',
# Sphinx and Python docs custom ones
'acks', 'attribute', 'autoattribute', 'autoclass', 'autodata',
'autoexception', 'autofunction', 'automethod', 'automodule', 'centered',
'cfunction', 'class', 'classmethod', 'cmacro', 'cmdoption', 'cmember',
'code-block', 'confval', 'cssclass', 'ctype', 'currentmodule', 'cvar',
'data', 'decorator', 'decoratormethod', 'deprecated-removed',
'deprecated(?!-removed)', 'describe', 'directive', 'doctest', 'envvar',
'event', 'exception', 'function', 'glossary', 'highlight', 'highlightlang',
'impl-detail', 'index', 'literalinclude', 'method', 'miscnews', 'module',
'moduleauthor', 'opcode', 'pdbcommand', 'productionlist',
'tabularcolumns', 'testcode', 'testoutput', 'testsetup', 'toctree', 'todo',
'todolist', 'versionadded', 'versionchanged'
]
all_directives = '(' + '|'.join(directives) + ')'
seems_directive_re = re.compile(r'(?<!\.)\.\. %s([^a-z:]|:(?!:))' % all_directives)
default_role_re = re.compile(r'(^| )`\w([^`]*?\w)?`($| )')
leaked_markup_re = re.compile(r'[a-z]::\s|`|\.\.\s*\w+:')
checkers = {}
checker_props = {'severity': 1, 'falsepositives': False}
def checker(*suffixes, **kwds):
"""Decorator to register a function as a checker."""
def deco(func):
for suffix in suffixes:
checkers.setdefault(suffix, []).append(func)
for prop in checker_props:
setattr(func, prop, kwds.get(prop, checker_props[prop]))
return func
return deco
@checker('.py', severity=4)
def check_syntax(fn, lines):
"""Check Python examples for valid syntax."""
code = ''.join(lines)
if '\r' in code:
if os.name != 'nt':
yield 0, '\\r in code file'
code = code.replace('\r', '')
try:
compile(code, fn, 'exec')
except SyntaxError, err:
yield err.lineno, 'not compilable: %s' % err
@checker('.rst', severity=2)
def check_suspicious_constructs(fn, lines):
"""Check for suspicious reST constructs."""
inprod = False
for lno, line in enumerate(lines):
if seems_directive_re.search(line):
yield lno+1, 'comment seems to be intended as a directive'
if '.. productionlist::' in line:
inprod = True
elif not inprod and default_role_re.search(line):
yield lno+1, 'default role used'
elif inprod and not line.strip():
inprod = False
@checker('.py', '.rst')
def check_whitespace(fn, lines):
"""Check for whitespace and line length issues."""
for lno, line in enumerate(lines):
if '\r' in line:
yield lno+1, '\\r in line'
if '\t' in line:
yield lno+1, 'OMG TABS!!!1'
if line[:-1].rstrip(' \t') != line[:-1]:
yield lno+1, 'trailing whitespace'
@checker('.rst', severity=0)
def check_line_length(fn, lines):
"""Check for line length; this checker is not run by default."""
for lno, line in enumerate(lines):
if len(line) > 81:
# don't complain about tables, links and function signatures
if line.lstrip()[0] not in '+|' and \
'http://' not in line and \
not line.lstrip().startswith(('.. function',
'.. method',
'.. cfunction')):
yield lno+1, "line too long"
@checker('.html', severity=2, falsepositives=True)
def check_leaked_markup(fn, lines):
"""Check HTML files for leaked reST markup; this only works if
the HTML files have been built.
"""
for lno, line in enumerate(lines):
if leaked_markup_re.search(line):
yield lno+1, 'possibly leaked markup: %r' % line
def main(argv):
usage = '''\
Usage: %s [-v] [-f] [-s sev] [-i path]* [path]
Options: -v verbose (print all checked file names)
-f enable checkers that yield many false positives
-s sev only show problems with severity >= sev
-i path ignore subdir or file path
''' % argv[0]
try:
gopts, args = getopt.getopt(argv[1:], 'vfs:i:')
except getopt.GetoptError:
print usage
return 2
verbose = False
severity = 1
ignore = []
falsepos = False
for opt, val in gopts:
if opt == '-v':
verbose = True
elif opt == '-f':
falsepos = True
elif opt == '-s':
severity = int(val)
elif opt == '-i':
ignore.append(abspath(val))
if len(args) == 0:
path = '.'
elif len(args) == 1:
path = args[0]
else:
print usage
return 2
if not exists(path):
print 'Error: path %s does not exist' % path
return 2
count = defaultdict(int)
out = sys.stdout
for root, dirs, files in os.walk(path):
# ignore subdirs controlled by svn
if '.svn' in dirs:
dirs.remove('.svn')
# ignore subdirs in ignore list
if abspath(root) in ignore:
del dirs[:]
continue
for fn in files:
fn = join(root, fn)
if fn[:2] == './':
fn = fn[2:]
# ignore files in ignore list
if abspath(fn) in ignore:
continue
ext = splitext(fn)[1]
checkerlist = checkers.get(ext, None)
if not checkerlist:
continue
if verbose:
print 'Checking %s...' % fn
try:
with open(fn, 'r') as f:
lines = list(f)
except (IOError, OSError), err:
print '%s: cannot open: %s' % (fn, err)
count[4] += 1
continue
for checker in checkerlist:
if checker.falsepositives and not falsepos:
continue
csev = checker.severity
if csev >= severity:
for lno, msg in checker(fn, lines):
print >>out, '[%d] %s:%d: %s' % (csev, fn, lno, msg)
count[csev] += 1
if verbose:
print
if not count:
if severity > 1:
print 'No problems with severity >= %d found.' % severity
else:
print 'No problems found.'
else:
for severity in sorted(count):
number = count[severity]
print '%d problem%s with severity %d found.' % \
(number, number > 1 and 's' or '', severity)
return int(bool(count))
if __name__ == '__main__':
sys.exit(main(sys.argv))

450
Doc/tools/static/basic.css Normal file
View File

@@ -0,0 +1,450 @@
/**
* Sphinx stylesheet -- basic theme
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/* -- main layout ----------------------------------------------------------- */
div.clearer {
clear: both;
}
/* -- relbar ---------------------------------------------------------------- */
div.related {
width: 100%;
font-size: 90%;
}
div.related h3 {
display: none;
}
div.related ul {
margin: 0;
padding: 0 0 0 10px;
list-style: none;
}
div.related li {
display: inline;
}
div.related li.right {
float: right;
margin-right: 5px;
}
/* -- sidebar --------------------------------------------------------------- */
div.sphinxsidebarwrapper {
position: relative;
top: 0;
padding: 10px 5px 0 10px;
word-wrap: break-word;
}
div.sphinxsidebar {
float: left;
width: 230px;
margin-left: -100%;
font-size: 90%;
}
div.sphinxsidebar ul {
list-style: none;
}
div.sphinxsidebar ul ul,
div.sphinxsidebar ul.want-points {
margin-left: 20px;
list-style: square;
}
div.sphinxsidebar ul ul {
margin-top: 0;
margin-bottom: 0;
}
div.sphinxsidebar form {
margin-top: 10px;
}
div.sphinxsidebar input {
border: 1px solid #98dbcc;
font-family: sans-serif;
font-size: 1em;
}
img {
border: 0;
}
/* -- search page ----------------------------------------------------------- */
ul.search {
margin: 10px 0 0 20px;
padding: 0;
}
ul.search li {
padding: 5px 0 5px 20px;
background-image: url(file.png);
background-repeat: no-repeat;
background-position: 0 7px;
}
ul.search li a {
font-weight: bold;
}
ul.search li div.context {
color: #888;
margin: 2px 0 0 30px;
text-align: left;
}
ul.keywordmatches li.goodmatch a {
font-weight: bold;
}
/* -- index page ------------------------------------------------------------ */
table.contentstable {
width: 90%;
}
table.contentstable p.biglink {
line-height: 150%;
}
a.biglink {
font-size: 1.3em;
}
span.linkdescr {
font-style: italic;
padding-top: 5px;
font-size: 90%;
}
/* -- general index --------------------------------------------------------- */
table.indextable td {
text-align: left;
vertical-align: top;
}
table.indextable dl, table.indextable dd {
margin-top: 0;
margin-bottom: 0;
}
table.indextable tr.pcap {
height: 10px;
}
table.indextable tr.cap {
margin-top: 10px;
background-color: #f2f2f2;
}
img.toggler {
margin-right: 3px;
margin-top: 3px;
cursor: pointer;
}
/* -- general body styles --------------------------------------------------- */
a.headerlink {
visibility: hidden;
}
h1:hover > a.headerlink,
h2:hover > a.headerlink,
h3:hover > a.headerlink,
h4:hover > a.headerlink,
h5:hover > a.headerlink,
h6:hover > a.headerlink,
dt:hover > a.headerlink {
visibility: visible;
}
div.body p.caption {
text-align: inherit;
}
div.body td {
text-align: left;
}
.field-list ul {
padding-left: 1em;
}
.first {
margin-top: 0 !important;
}
p.rubric {
margin-top: 30px;
font-weight: bold;
}
/* -- sidebars -------------------------------------------------------------- */
div.sidebar {
margin: 0 0 0.5em 1em;
border: 1px solid #ddb;
padding: 7px 7px 0 7px;
background-color: #ffe;
width: 40%;
float: right;
}
p.sidebar-title {
font-weight: bold;
}
/* -- topics ---------------------------------------------------------------- */
div.topic {
border: 1px solid #ccc;
padding: 7px 7px 0 7px;
margin: 10px 0 10px 0;
}
p.topic-title {
font-size: 1.1em;
font-weight: bold;
margin-top: 10px;
}
/* -- admonitions ----------------------------------------------------------- */
div.admonition {
margin-top: 10px;
margin-bottom: 10px;
padding: 7px;
}
div.admonition dt {
font-weight: bold;
}
div.admonition dl {
margin-bottom: 0;
}
p.admonition-title {
margin: 0px 10px 5px 0px;
font-weight: bold;
}
div.body p.centered {
text-align: center;
margin-top: 25px;
}
/* -- tables ---------------------------------------------------------------- */
table.docutils {
border: 0 solid #dce;
border-collapse: collapse;
}
table.docutils td, table.docutils th {
padding: 2px 5px 2px 5px;
border-left: 0;
background-color: #eef;
}
table.docutils td p.last, table.docutils th p.last {
margin-bottom: 0;
}
table.field-list td, table.field-list th {
border: 0 !important;
}
table.footnote td, table.footnote th {
border: 0 !important;
}
table.docutils th {
border-top: 1px solid #cac;
background-color: #ede;
}
th {
text-align: left;
padding-right: 5px;
}
th.head {
text-align: center;
}
/* -- other body styles ----------------------------------------------------- */
dl {
margin-bottom: 15px;
}
dd p {
margin-top: 0px;
}
dd ul, dd table {
margin-bottom: 10px;
}
dd {
margin-top: 3px;
margin-bottom: 10px;
margin-left: 30px;
}
dt:target, .highlighted {
background-color: #fbe54e;
}
dl.glossary dt {
font-weight: bold;
font-size: 1.1em;
}
.field-list ul {
margin: 0;
padding-left: 1em;
}
.field-list p {
margin: 0;
}
.refcount {
color: #060;
}
.optional {
font-size: 1.3em;
}
.versionmodified {
font-style: italic;
}
.deprecated {
background-color: #ffe4e4;
border: 1px solid #f66;
padding: 7px;
}
div.deprecated p {
margin-bottom: 0;
}
.system-message {
background-color: #fda;
padding: 5px;
border: 3px solid red;
}
.footnote:target {
background-color: #ffa;
}
.impl-detail {
margin-top: 10px;
margin-bottom: 10px;
padding: 7px;
border: 1px solid #ccc;
}
.impl-detail .compound-first {
margin-top: 0;
}
.impl-detail .compound-last {
margin-bottom: 0;
}
/* -- code displays --------------------------------------------------------- */
pre {
overflow: auto;
overflow-y: hidden;
}
td.linenos pre {
padding: 5px 0px;
border: 0;
background-color: transparent;
color: #aaa;
}
table.highlighttable {
margin-left: 0.5em;
}
table.highlighttable td {
padding: 0 0.5em 0 0.5em;
}
code.descname {
background-color: transparent;
font-weight: bold;
font-size: 1.2em;
}
code.descclassname {
background-color: transparent;
}
code.xref, a code {
background-color: transparent;
font-weight: bold;
}
h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
background-color: transparent;
}
.highlight {
background: none !important;
}
/* -- math display ---------------------------------------------------------- */
img.math {
vertical-align: middle;
}
div.body div.math p {
text-align: center;
}
span.eqno {
float: right;
}
/* -- printout stylesheet --------------------------------------------------- */
@media print {
div.document,
div.documentwrapper,
div.bodywrapper {
margin: 0 !important;
width: 100%;
}
div.sphinxsidebar,
div.related,
div.footer,
#top-link {
display: none;
}
}

View File

@@ -0,0 +1,61 @@
$(document).ready(function() {
/* Add a [>>>] button on the top-right corner of code samples to hide
* the >>> and ... prompts and the output and thus make the code
* copyable. */
var div = $('.highlight-python .highlight,' +
'.highlight-python3 .highlight')
var pre = div.find('pre');
// get the styles from the current theme
pre.parent().parent().css('position', 'relative');
var hide_text = 'Hide the prompts and output';
var show_text = 'Show the prompts and output';
var border_width = pre.css('border-top-width');
var border_style = pre.css('border-top-style');
var border_color = pre.css('border-top-color');
var button_styles = {
'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0',
'border-color': border_color, 'border-style': border_style,
'border-width': border_width, 'color': border_color, 'text-size': '75%',
'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em'
}
// create and add the button to all the code blocks that contain >>>
div.each(function(index) {
var jthis = $(this);
if (jthis.find('.gp').length > 0) {
var button = $('<span class="copybutton">&gt;&gt;&gt;</span>');
button.css(button_styles)
button.attr('title', hide_text);
button.data('hidden', 'false');
jthis.prepend(button);
}
// tracebacks (.gt) contain bare text elements that need to be
// wrapped in a span to work with .nextUntil() (see later)
jthis.find('pre:has(.gt)').contents().filter(function() {
return ((this.nodeType == 3) && (this.data.trim().length > 0));
}).wrap('<span>');
});
// define the behavior of the button when it's clicked
$('.copybutton').click(function(e){
e.preventDefault();
var button = $(this);
if (button.data('hidden') === 'false') {
// hide the code output
button.parent().find('.go, .gp, .gt').hide();
button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');
button.css('text-decoration', 'line-through');
button.attr('title', show_text);
button.data('hidden', 'true');
} else {
// show the code output
button.parent().find('.go, .gp, .gt').show();
button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');
button.css('text-decoration', 'none');
button.attr('title', hide_text);
button.data('hidden', 'false');
}
});
});

BIN
Doc/tools/static/py.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 695 B

198
Doc/tools/static/sidebar.js Normal file
View File

@@ -0,0 +1,198 @@
/*
* sidebar.js
* ~~~~~~~~~~
*
* This script makes the Sphinx sidebar collapsible and implements
* intelligent scrolling.
*
* .sphinxsidebar contains .sphinxsidebarwrapper. This script adds
* in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton
* used to collapse and expand the sidebar.
*
* When the sidebar is collapsed the .sphinxsidebarwrapper is hidden
* and the width of the sidebar and the margin-left of the document
* are decreased. When the sidebar is expanded the opposite happens.
* This script saves a per-browser/per-session cookie used to
* remember the position of the sidebar among the pages.
* Once the browser is closed the cookie is deleted and the position
* reset to the default (expanded).
*
* :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
$(function() {
// global elements used by the functions.
// the 'sidebarbutton' element is defined as global after its
// creation, in the add_sidebar_button function
var jwindow = $(window);
var jdocument = $(document);
var bodywrapper = $('.bodywrapper');
var sidebar = $('.sphinxsidebar');
var sidebarwrapper = $('.sphinxsidebarwrapper');
// original margin-left of the bodywrapper and width of the sidebar
// with the sidebar expanded
var bw_margin_expanded = bodywrapper.css('margin-left');
var ssb_width_expanded = sidebar.width();
// margin-left of the bodywrapper and width of the sidebar
// with the sidebar collapsed
var bw_margin_collapsed = '.8em';
var ssb_width_collapsed = '.8em';
// colors used by the current theme
var dark_color = $('.related').css('background-color');
var light_color = $('.document').css('background-color');
// set position: sticky on sidebar
// (browsers that don't support this will fall-back to
// positioning via scroll_sidebar)
var supportsPositionSticky = (window.CSS && window.CSS.supports &&
window.CSS.supports('position', 'sticky'));
if (supportsPositionSticky) {
sidebarwrapper.css('position', 'sticky');
}
function get_viewport_height() {
if (window.innerHeight)
return window.innerHeight;
else
return jwindow.height();
}
function sidebar_is_collapsed() {
return sidebarwrapper.is(':not(:visible)');
}
function toggle_sidebar() {
if (sidebar_is_collapsed())
expand_sidebar();
else
collapse_sidebar();
// adjust the scrolling of the sidebar
scroll_sidebar();
}
function collapse_sidebar() {
sidebarwrapper.hide();
sidebar.css('width', ssb_width_collapsed);
bodywrapper.css('margin-left', bw_margin_collapsed);
sidebarbutton.css({
'margin-left': '0',
'height': bodywrapper.height()
});
sidebarbutton.find('span').text('»');
sidebarbutton.attr('title', _('Expand sidebar'));
document.cookie = 'sidebar=collapsed';
}
function expand_sidebar() {
bodywrapper.css('margin-left', bw_margin_expanded);
sidebar.css('width', ssb_width_expanded);
sidebarwrapper.show();
sidebarbutton.css({
'margin-left': ssb_width_expanded-12,
'height': bodywrapper.height()
});
sidebarbutton.find('span').text('«');
sidebarbutton.attr('title', _('Collapse sidebar'));
document.cookie = 'sidebar=expanded';
}
function add_sidebar_button() {
sidebarwrapper.css({
'float': 'left',
'margin-right': '0',
'width': ssb_width_expanded - 28
});
// create the button
sidebar.append(
'<div id="sidebarbutton"><span>&laquo;</span></div>'
);
var sidebarbutton = $('#sidebarbutton');
light_color = sidebarbutton.css('background-color');
// find the height of the viewport to center the '<<' in the page
var viewport_height = get_viewport_height();
sidebarbutton.find('span').css({
'display': 'block',
'margin-top': (viewport_height - sidebar.position().top - 20) / 2
});
sidebarbutton.click(toggle_sidebar);
sidebarbutton.attr('title', _('Collapse sidebar'));
sidebarbutton.css({
'color': '#FFFFFF',
'border-left': '1px solid ' + dark_color,
'font-size': '1.2em',
'cursor': 'pointer',
'height': bodywrapper.height(),
'padding-top': '1px',
'margin-left': ssb_width_expanded - 12
});
sidebarbutton.hover(
function () {
$(this).css('background-color', dark_color);
},
function () {
$(this).css('background-color', light_color);
}
);
}
function set_position_from_cookie() {
if (!document.cookie)
return;
var items = document.cookie.split(';');
for(var k=0; k<items.length; k++) {
var key_val = items[k].split('=');
var key = key_val[0];
if (key == 'sidebar') {
var value = key_val[1];
if ((value == 'collapsed') && (!sidebar_is_collapsed()))
collapse_sidebar();
else if ((value == 'expanded') && (sidebar_is_collapsed()))
expand_sidebar();
}
}
}
add_sidebar_button();
var sidebarbutton = $('#sidebarbutton');
set_position_from_cookie();
/* intelligent scrolling */
function scroll_sidebar() {
if (supportsPositionSticky) {
return;
}
var sidebar_height = sidebarwrapper.height();
var viewport_height = get_viewport_height();
var offset = sidebar.position()['top'];
var wintop = jwindow.scrollTop();
var winbot = wintop + viewport_height;
var curtop = sidebarwrapper.position()['top'];
var curbot = curtop + sidebar_height;
// does sidebar fit in window?
if (sidebar_height < viewport_height) {
// yes: easy case -- always keep at the top
sidebarwrapper.css('top', $u.min([$u.max([0, wintop - offset - 10]),
jdocument.height() - sidebar_height - 200]));
}
else {
// no: only scroll if top/bottom edge of sidebar is at
// top/bottom edge of window
if (curtop > wintop && curbot > winbot) {
sidebarwrapper.css('top', $u.max([wintop - offset - 10, 0]));
}
else if (curtop < wintop && curbot < winbot) {
sidebarwrapper.css('top', $u.min([winbot - sidebar_height - offset - 20,
jdocument.height() - sidebar_height - 200]));
}
}
}
jwindow.scroll(scroll_sidebar);
});

View File

@@ -0,0 +1,153 @@
(function() {
'use strict';
// Parses versions in URL segments like:
// "3", "dev", "release/2.7" or "3.6rc2"
var version_regexs = [
'(?:\\d)',
'(?:\\d\\.\\d[\\w\\d\\.]*)',
'(?:dev)',
'(?:release/\\d.\\d[\\x\\d\\.]*)'];
var all_versions = {
'3.9': 'dev (3.9)',
'3.8': '3.8',
'3.7': '3.7',
'3.6': '3.6',
'3.5': '3.5',
'2.7': '2.7',
};
var all_languages = {
'en': 'English',
'fr': 'French',
'ja': 'Japanese',
};
function build_version_select(current_version, current_release) {
var buf = ['<select>'];
$.each(all_versions, function(version, title) {
buf.push('<option value="' + version + '"');
if (version == current_version)
buf.push(' selected="selected">' + current_release + '</option>');
else
buf.push('>' + title + '</option>');
});
buf.push('</select>');
return buf.join('');
}
function build_language_select(current_language) {
var buf = ['<select>'];
$.each(all_languages, function(language, title) {
if (language == current_language)
buf.push('<option value="' + language + '" selected="selected">' +
all_languages[current_language] + '</option>');
else
buf.push('<option value="' + language + '">' + title + '</option>');
});
if (!(current_language in all_languages)) {
// In case we're browsing a language that is not yet in all_languages.
buf.push('<option value="' + current_language + '" selected="selected">' +
current_language + '</option>');
all_languages[current_language] = current_language;
}
buf.push('</select>');
return buf.join('');
}
function navigate_to_first_existing(urls) {
// Navigate to the first existing URL in urls.
var url = urls.shift();
if (urls.length == 0) {
window.location.href = url;
return;
}
$.ajax({
url: url,
success: function() {
window.location.href = url;
},
error: function() {
navigate_to_first_existing(urls);
}
});
}
function on_version_switch() {
var selected_version = $(this).children('option:selected').attr('value') + '/';
var url = window.location.href;
var current_language = language_segment_from_url(url);
var current_version = version_segment_in_url(url);
var new_url = url.replace('.org/' + current_language + current_version,
'.org/' + current_language + selected_version);
if (new_url != url) {
navigate_to_first_existing([
new_url,
url.replace('.org/' + current_language + current_version,
'.org/' + selected_version),
'https://docs.python.org/' + current_language + selected_version,
'https://docs.python.org/' + selected_version,
'https://docs.python.org/'
]);
}
}
function on_language_switch() {
var selected_language = $(this).children('option:selected').attr('value') + '/';
var url = window.location.href;
var current_language = language_segment_from_url(url);
var current_version = version_segment_in_url(url);
if (selected_language == 'en/') // Special 'default' case for english.
selected_language = '';
var new_url = url.replace('.org/' + current_language + current_version,
'.org/' + selected_language + current_version);
if (new_url != url) {
navigate_to_first_existing([
new_url,
'https://docs.python.org/'
]);
}
}
// Returns the path segment of the language as a string, like 'fr/'
// or '' if not found.
function language_segment_from_url(url) {
var language_regexp = '\.org/([a-z]{2}(?:-[a-z]{2})?/)';
var match = url.match(language_regexp);
if (match !== null)
return match[1];
return '';
}
// Returns the path segment of the version as a string, like '3.6/'
// or '' if not found.
function version_segment_in_url(url) {
var language_segment = '(?:[a-z]{2}(?:-[a-z]{2})?/)';
var version_segment = '(?:(?:' + version_regexs.join('|') + ')/)';
var version_regexp = '\\.org/' + language_segment + '?(' + version_segment + ')';
var match = url.match(version_regexp);
if (match !== null)
return match[1];
return ''
}
$(document).ready(function() {
var release = DOCUMENTATION_OPTIONS.VERSION;
var language_segment = language_segment_from_url(window.location.href);
var current_language = language_segment.replace(/\/+$/g, '') || 'en';
var version = release.substr(0, 3);
var version_select = build_version_select(version, release);
$('.version_switcher_placeholder').html(version_select);
$('.version_switcher_placeholder select').bind('change', on_version_switch);
var language_select = build_language_select(current_language);
$('.language_switcher_placeholder').html(language_select);
$('.language_switcher_placeholder select').bind('change', on_language_switch);
});
})();

197
Doc/tools/susp-ignored.csv Normal file
View File

@@ -0,0 +1,197 @@
c-api/arg,,:ref,"PyArg_ParseTuple(args, ""O|O:ref"", &object, &callback)"
c-api/list,,:high,list[low:high]
c-api/sequence,,:i2,o[i1:i2]
c-api/tuple,,:high,p[low:high]
c-api/unicode,,:end,str[start:end]
distutils/setupscript,,::,
extending/embedding,,:numargs,"if(!PyArg_ParseTuple(args, "":numargs""))"
extending/extending,,:set,"if (PyArg_ParseTuple(args, ""O:set_callback"", &temp)) {"
extending/extending,,:myfunction,"PyArg_ParseTuple(args, ""D:myfunction"", &c);"
extending/newtypes,,:call,"if (!PyArg_ParseTuple(args, ""sss:call"", &arg1, &arg2, &arg3)) {"
faq/programming,,:reduce,"print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,"
faq/programming,,:reduce,"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,"
faq/programming,,:chr,">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr("
faq/programming,,::,for x in sequence[::-1]:
howto/cporting,,:encode,"if (!PyArg_ParseTuple(args, ""O:encode_object"", &myobj))"
howto/cporting,,:say,"if (!PyArg_ParseTuple(args, ""U:say_hello"", &name))"
howto/curses,,:black,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and"
howto/curses,,:blue,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and"
howto/curses,,:cyan,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and"
howto/curses,,:green,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and"
howto/curses,,:magenta,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and"
howto/curses,,:red,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and"
howto/curses,,:white,"7:white."
howto/curses,,:yellow,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and"
howto/logging,,:root,WARNING:root:Watch out!
howto/logging,,:Watch,WARNING:root:Watch out!
howto/logging,,:root,DEBUG:root:This message should go to the log file
howto/logging,,:root,INFO:root:So should this
howto/logging,,:So,INFO:root:So should this
howto/logging,,:root,"WARNING:root:And this, too"
howto/logging,,:And,"WARNING:root:And this, too"
howto/logging,,:root,INFO:root:Started
howto/logging,,:Started,INFO:root:Started
howto/logging,,:root,INFO:root:Doing something
howto/logging,,:Doing,INFO:root:Doing something
howto/logging,,:root,INFO:root:Finished
howto/logging,,:Finished,INFO:root:Finished
howto/logging,,:root,WARNING:root:Look before you leap!
howto/logging,,:Look,WARNING:root:Look before you leap!
howto/logging,,:This,DEBUG:This message should appear on the console
howto/logging,,:So,INFO:So should this
howto/logging,,:And,"WARNING:And this, too"
howto/logging,,:logger,severity:logger name:message
howto/logging,,:message,severity:logger name:message
howto/logging,,:This,DEBUG:root:This message should go to the log file
howto/pyporting,,::,Programming Language :: Python :: 2
howto/pyporting,,::,Programming Language :: Python :: 3
howto/regex,,::,
howto/regex,,:foo,(?:foo)
howto/urllib2,,:password,"""joe:password@example.com"""
library/audioop,,:ipos,"# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],"
library/bisect,,:hi,all(val >= x for val in a[i:hi])
library/bisect,,:hi,all(val > x for val in a[i:hi])
library/cookie,,`,!#$%&'*+-.^_`|~
library/datetime,,:MM,
library/datetime,,:SS,
library/decimal,,:optional,"trailneg:optional trailing minus indicator"
library/difflib,,:ahi,a[alo:ahi]
library/difflib,,:bhi,b[blo:bhi]
library/difflib,,:i2,
library/difflib,,:j2,
library/difflib,,:i1,
library/dis,,:TOS,
library/dis,,`,TOS = `TOS`
library/doctest,,`,``factorial`` from the ``example`` module:
library/doctest,,`,The ``example`` module
library/doctest,,`,Using ``factorial``
library/exceptions,,:err,err.object[err.start:err.end]
library/functions,,:step,a[start:stop:step]
library/functions,,:stop,"a[start:stop, i]"
library/functions,,:stop,a[start:stop:step]
library/hotshot,,:lineno,"ncalls tottime percall cumtime percall filename:lineno(function)"
library/httplib,,:port,host:port
library/imaplib,,:MM,"""DD-Mmm-YYYY HH:MM:SS"
library/imaplib,,:SS,"""DD-Mmm-YYYY HH:MM:SS"
library/itertools,,:stop,elements from seq[start:stop:step]
library/itertools,,:step,elements from seq[start:stop:step]
library/linecache,,:sys,"sys:x:3:3:sys:/dev:/bin/sh"
library/logging.handlers,,:port,host:port
library/mmap,,:i2,obj[i1:i2]
library/multiprocessing,,:queue,">>> QueueManager.register('get_queue', callable=lambda:queue)"
library/multiprocessing,,`,">>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`"
library/multiprocessing,,`,">>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`"
library/multiprocessing,,`,# `BaseManager`.
library/multiprocessing,,`,# `Pool.imap()` (which will save on the amount of code needed anyway).
library/multiprocessing,,`,# A test file for the `multiprocessing` package
library/multiprocessing,,`,# A test of `multiprocessing.Pool` class
library/multiprocessing,,`,# Add more tasks using `put()`
library/multiprocessing,,`,# in the original order then consider using `Pool.map()` or
library/multiprocessing,,`,# Not sure if we should synchronize access to `socket.accept()` method by
library/multiprocessing,,`,# object. (We import `multiprocessing.reduction` to enable this pickling.)
library/multiprocessing,,`,# register the Foo class; make `f()` and `g()` accessible via proxy
library/multiprocessing,,`,# register the Foo class; make `g()` and `_h()` accessible via proxy
library/multiprocessing,,`,# register the generator function baz; use `GeneratorProxy` to make proxies
library/optparse,,:len,"del parser.rargs[:len(value)]"
library/os.path,,:foo,c:foo
library/pdb,,:lineno,filename:lineno
library/posix,,`,"CFLAGS=""`getconf LFS_CFLAGS`"" OPT=""-g -O2 $CFLAGS"""
library/profile,,:lineno,ncalls tottime percall cumtime percall filename:lineno(function)
library/profile,,:lineno,filename:lineno(function)
library/pyexpat,,:elem1,<py:elem1 />
library/pyexpat,,:py,"xmlns:py = ""http://www.python.org/ns/"">"
library/re,,`,!#$%&'*+-.^_`|~:
library/re,,`,[abcdefghijklmnopqrstuvwxyz0123456789\!\#\$\%\&\'\*\+\-\.\^\_\`\|\~\:]+
library/smtplib,,:port,method must support that as well as a regular host:port
library/socket,,::,'5aef:2b::8'
library/sqlite3,,:memory,
library/sqlite3,,:who,"cur.execute(""select * from people where name_last=:who and age=:age"", {""who"": who, ""age"": age})"
library/sqlite3,,:age,"cur.execute(""select * from people where name_last=:who and age=:age"", {""who"": who, ""age"": age})"
library/ssl,,:My,"Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc."
library/ssl,,:My,"Organizational Unit Name (eg, section) []:My Group"
library/ssl,,:myserver,"Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com"
library/ssl,,:MyState,State or Province Name (full name) [Some-State]:MyState
library/ssl,,:ops,Email Address []:ops@myserver.mygroup.myorganization.com
library/ssl,,:Some,"Locality Name (eg, city) []:Some City"
library/ssl,,:US,Country Name (2 letter code) [AU]:US
library/stdtypes,,:len,s[len(s):len(s)]
library/stdtypes,,:end,s[start:end]
library/string,,:end,s[start:end]
library/subprocess,,`,"output=`mycmd myarg`"
library/subprocess,,`,"output=`dmesg | grep hda`"
library/tarfile,,:compression,filemode[:compression]
library/tarfile,,:gz,
library/tarfile,,:bz2,
library/time,,:mm,
library/time,,:ss,
library/turtle,,::,Example::
library/urllib,,:port,:port
library/urllib2,,:password,"""joe:password@python.org"""
library/urllib2,,:close,Connection:close
library/uuid,,:uuid,urn:uuid:12345678-1234-5678-1234-567812345678
library/xml.etree.elementtree,,:sometag,prefix:sometag
library/xml.etree.elementtree,,:fictional,"<actors xmlns:fictional=""http://characters.example.com"""
library/xml.etree.elementtree,,:character,<fictional:character>Lancelot</fictional:character>
library/xml.etree.elementtree,,:character,<fictional:character>Archie Leach</fictional:character>
library/xml.etree.elementtree,,:character,<fictional:character>Sir Robin</fictional:character>
library/xml.etree.elementtree,,:character,<fictional:character>Gunther</fictional:character>
library/xml.etree.elementtree,,:character,<fictional:character>Commander Clement</fictional:character>
library/xml.etree.elementtree,,:actor,"for actor in root.findall('real_person:actor', ns):"
library/xml.etree.elementtree,,:name,"name = actor.find('real_person:name', ns)"
library/xml.etree.elementtree,,:character,"for char in actor.findall('role:character', ns):"
library/xmlrpclib,,:pass,http://user:pass@host:port/path
library/xmlrpclib,,:pass,user:pass
library/xmlrpclib,,:port,http://user:pass@host:port/path
license,,`,THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
license,,:zooko,mailto:zooko@zooko.com
license,,`,THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
license,,`,* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
license,,`,* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
license,,`,"``Software''), to deal in the Software without restriction, including"
license,,`,"THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,"
reference/datamodel,,:step,a[i:j:step]
reference/datamodel,,:max,
reference/expressions,,:index,x[index:index]
reference/expressions,,`,`expressions...`
reference/expressions,350,`,`
reference/grammar,,`,'`' testlist1 '`'
reference/lexical_analysis,,:fileencoding,# vim:fileencoding=<encoding-name>
reference/lexical_analysis,,`,", : . ` = ;"
tutorial/datastructures,,:value,key:value pairs within the braces adds initial key:value pairs
tutorial/datastructures,,:value,It is also possible to delete a key:value
tutorial/stdlib2,,:start,"fields = struct.unpack('<IIIHH', data[start:start+16])"
tutorial/stdlib2,,:start,extra = data[start:start+extra_size]
tutorial/stdlib2,,:start,filename = data[start:start+filenamesize]
tutorial/stdlib2,,:config,"logging.warning('Warning:config file %s not found', 'server.conf')"
tutorial/stdlib2,,:config,WARNING:root:Warning:config file server.conf not found
tutorial/stdlib2,,:Critical,CRITICAL:root:Critical error -- shutting down
tutorial/stdlib2,,:Error,ERROR:root:Error occurred
tutorial/stdlib2,,:root,CRITICAL:root:Critical error -- shutting down
tutorial/stdlib2,,:root,ERROR:root:Error occurred
tutorial/stdlib2,,:root,WARNING:root:Warning:config file server.conf not found
tutorial/stdlib2,,:Warning,WARNING:root:Warning:config file server.conf not found
using/cmdline,,:line,file:line: category: message
using/cmdline,,:category,action:message:category:module:line
using/cmdline,,:line,action:message:category:module:line
using/cmdline,,:message,action:message:category:module:line
using/cmdline,,:module,action:message:category:module:line
using/cmdline,,:errorhandler,:errorhandler
using/unix,,:Packaging,https://en.opensuse.org/Portal:Packaging
whatsnew/2.0,418,:len,
whatsnew/2.3,,::,
whatsnew/2.3,,:config,
whatsnew/2.3,,:Critical,
whatsnew/2.3,,:Error,
whatsnew/2.3,,:Problem,
whatsnew/2.3,,:root,
whatsnew/2.3,,:Warning,
whatsnew/2.4,,::,
whatsnew/2.4,,:System,
whatsnew/2.5,,:memory,:memory:
whatsnew/2.5,,:step,[start:stop:step]
whatsnew/2.5,,:stop,[start:stop:step]
whatsnew/2.7,,:Sunday,'2009:4:Sunday'
whatsnew/2.7,,::,"export PYTHONWARNINGS=all,error:::Cookie:0"
whatsnew/2.7,,:Cookie,"export PYTHONWARNINGS=all,error:::Cookie:0"
whatsnew/2.7,,::,>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
whatsnew/2.7,,::,"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',"
1 c-api/arg :ref PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
2 c-api/list :high list[low:high]
3 c-api/sequence :i2 o[i1:i2]
4 c-api/tuple :high p[low:high]
5 c-api/unicode :end str[start:end]
6 distutils/setupscript ::
7 extending/embedding :numargs if(!PyArg_ParseTuple(args, ":numargs"))
8 extending/extending :set if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
9 extending/extending :myfunction PyArg_ParseTuple(args, "D:myfunction", &c);
10 extending/newtypes :call if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
11 faq/programming :reduce print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
12 faq/programming :reduce Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
13 faq/programming :chr >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
14 faq/programming :: for x in sequence[::-1]:
15 howto/cporting :encode if (!PyArg_ParseTuple(args, "O:encode_object", &myobj))
16 howto/cporting :say if (!PyArg_ParseTuple(args, "U:say_hello", &name))
17 howto/curses :black They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
18 howto/curses :blue They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
19 howto/curses :cyan They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
20 howto/curses :green They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
21 howto/curses :magenta They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
22 howto/curses :red They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
23 howto/curses :white 7:white.
24 howto/curses :yellow They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
25 howto/logging :root WARNING:root:Watch out!
26 howto/logging :Watch WARNING:root:Watch out!
27 howto/logging :root DEBUG:root:This message should go to the log file
28 howto/logging :root INFO:root:So should this
29 howto/logging :So INFO:root:So should this
30 howto/logging :root WARNING:root:And this, too
31 howto/logging :And WARNING:root:And this, too
32 howto/logging :root INFO:root:Started
33 howto/logging :Started INFO:root:Started
34 howto/logging :root INFO:root:Doing something
35 howto/logging :Doing INFO:root:Doing something
36 howto/logging :root INFO:root:Finished
37 howto/logging :Finished INFO:root:Finished
38 howto/logging :root WARNING:root:Look before you leap!
39 howto/logging :Look WARNING:root:Look before you leap!
40 howto/logging :This DEBUG:This message should appear on the console
41 howto/logging :So INFO:So should this
42 howto/logging :And WARNING:And this, too
43 howto/logging :logger severity:logger name:message
44 howto/logging :message severity:logger name:message
45 howto/logging :This DEBUG:root:This message should go to the log file
46 howto/pyporting :: Programming Language :: Python :: 2
47 howto/pyporting :: Programming Language :: Python :: 3
48 howto/regex ::
49 howto/regex :foo (?:foo)
50 howto/urllib2 :password "joe:password@example.com"
51 library/audioop :ipos # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
52 library/bisect :hi all(val >= x for val in a[i:hi])
53 library/bisect :hi all(val > x for val in a[i:hi])
54 library/cookie ` !#$%&'*+-.^_`|~
55 library/datetime :MM
56 library/datetime :SS
57 library/decimal :optional trailneg:optional trailing minus indicator
58 library/difflib :ahi a[alo:ahi]
59 library/difflib :bhi b[blo:bhi]
60 library/difflib :i2
61 library/difflib :j2
62 library/difflib :i1
63 library/dis :TOS
64 library/dis ` TOS = `TOS`
65 library/doctest ` ``factorial`` from the ``example`` module:
66 library/doctest ` The ``example`` module
67 library/doctest ` Using ``factorial``
68 library/exceptions :err err.object[err.start:err.end]
69 library/functions :step a[start:stop:step]
70 library/functions :stop a[start:stop, i]
71 library/functions :stop a[start:stop:step]
72 library/hotshot :lineno ncalls tottime percall cumtime percall filename:lineno(function)
73 library/httplib :port host:port
74 library/imaplib :MM "DD-Mmm-YYYY HH:MM:SS
75 library/imaplib :SS "DD-Mmm-YYYY HH:MM:SS
76 library/itertools :stop elements from seq[start:stop:step]
77 library/itertools :step elements from seq[start:stop:step]
78 library/linecache :sys sys:x:3:3:sys:/dev:/bin/sh
79 library/logging.handlers :port host:port
80 library/mmap :i2 obj[i1:i2]
81 library/multiprocessing :queue >>> QueueManager.register('get_queue', callable=lambda:queue)
82 library/multiprocessing ` >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
83 library/multiprocessing ` >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
84 library/multiprocessing ` # `BaseManager`.
85 library/multiprocessing ` # `Pool.imap()` (which will save on the amount of code needed anyway).
86 library/multiprocessing ` # A test file for the `multiprocessing` package
87 library/multiprocessing ` # A test of `multiprocessing.Pool` class
88 library/multiprocessing ` # Add more tasks using `put()`
89 library/multiprocessing ` # in the original order then consider using `Pool.map()` or
90 library/multiprocessing ` # Not sure if we should synchronize access to `socket.accept()` method by
91 library/multiprocessing ` # object. (We import `multiprocessing.reduction` to enable this pickling.)
92 library/multiprocessing ` # register the Foo class; make `f()` and `g()` accessible via proxy
93 library/multiprocessing ` # register the Foo class; make `g()` and `_h()` accessible via proxy
94 library/multiprocessing ` # register the generator function baz; use `GeneratorProxy` to make proxies
95 library/optparse :len del parser.rargs[:len(value)]
96 library/os.path :foo c:foo
97 library/pdb :lineno filename:lineno
98 library/posix ` CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS"
99 library/profile :lineno ncalls tottime percall cumtime percall filename:lineno(function)
100 library/profile :lineno filename:lineno(function)
101 library/pyexpat :elem1 <py:elem1 />
102 library/pyexpat :py xmlns:py = "http://www.python.org/ns/">
103 library/re ` !#$%&'*+-.^_`|~:
104 library/re ` [abcdefghijklmnopqrstuvwxyz0123456789\!\#\$\%\&\'\*\+\-\.\^\_\`\|\~\:]+
105 library/smtplib :port method must support that as well as a regular host:port
106 library/socket :: '5aef:2b::8'
107 library/sqlite3 :memory
108 library/sqlite3 :who cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
109 library/sqlite3 :age cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
110 library/ssl :My Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
111 library/ssl :My Organizational Unit Name (eg, section) []:My Group
112 library/ssl :myserver Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
113 library/ssl :MyState State or Province Name (full name) [Some-State]:MyState
114 library/ssl :ops Email Address []:ops@myserver.mygroup.myorganization.com
115 library/ssl :Some Locality Name (eg, city) []:Some City
116 library/ssl :US Country Name (2 letter code) [AU]:US
117 library/stdtypes :len s[len(s):len(s)]
118 library/stdtypes :end s[start:end]
119 library/string :end s[start:end]
120 library/subprocess ` output=`mycmd myarg`
121 library/subprocess ` output=`dmesg | grep hda`
122 library/tarfile :compression filemode[:compression]
123 library/tarfile :gz
124 library/tarfile :bz2
125 library/time :mm
126 library/time :ss
127 library/turtle :: Example::
128 library/urllib :port :port
129 library/urllib2 :password "joe:password@python.org"
130 library/urllib2 :close Connection:close
131 library/uuid :uuid urn:uuid:12345678-1234-5678-1234-567812345678
132 library/xml.etree.elementtree :sometag prefix:sometag
133 library/xml.etree.elementtree :fictional <actors xmlns:fictional="http://characters.example.com"
134 library/xml.etree.elementtree :character <fictional:character>Lancelot</fictional:character>
135 library/xml.etree.elementtree :character <fictional:character>Archie Leach</fictional:character>
136 library/xml.etree.elementtree :character <fictional:character>Sir Robin</fictional:character>
137 library/xml.etree.elementtree :character <fictional:character>Gunther</fictional:character>
138 library/xml.etree.elementtree :character <fictional:character>Commander Clement</fictional:character>
139 library/xml.etree.elementtree :actor for actor in root.findall('real_person:actor', ns):
140 library/xml.etree.elementtree :name name = actor.find('real_person:name', ns)
141 library/xml.etree.elementtree :character for char in actor.findall('role:character', ns):
142 library/xmlrpclib :pass http://user:pass@host:port/path
143 library/xmlrpclib :pass user:pass
144 library/xmlrpclib :port http://user:pass@host:port/path
145 license ` THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
146 license :zooko mailto:zooko@zooko.com
147 license ` THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
148 license ` * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
149 license ` * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
150 license ` ``Software''), to deal in the Software without restriction, including
151 license ` THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
152 reference/datamodel :step a[i:j:step]
153 reference/datamodel :max
154 reference/expressions :index x[index:index]
155 reference/expressions ` `expressions...`
156 reference/expressions 350 ` `
157 reference/grammar ` '`' testlist1 '`'
158 reference/lexical_analysis :fileencoding # vim:fileencoding=<encoding-name>
159 reference/lexical_analysis ` , : . ` = ;
160 tutorial/datastructures :value key:value pairs within the braces adds initial key:value pairs
161 tutorial/datastructures :value It is also possible to delete a key:value
162 tutorial/stdlib2 :start fields = struct.unpack('<IIIHH', data[start:start+16])
163 tutorial/stdlib2 :start extra = data[start:start+extra_size]
164 tutorial/stdlib2 :start filename = data[start:start+filenamesize]
165 tutorial/stdlib2 :config logging.warning('Warning:config file %s not found', 'server.conf')
166 tutorial/stdlib2 :config WARNING:root:Warning:config file server.conf not found
167 tutorial/stdlib2 :Critical CRITICAL:root:Critical error -- shutting down
168 tutorial/stdlib2 :Error ERROR:root:Error occurred
169 tutorial/stdlib2 :root CRITICAL:root:Critical error -- shutting down
170 tutorial/stdlib2 :root ERROR:root:Error occurred
171 tutorial/stdlib2 :root WARNING:root:Warning:config file server.conf not found
172 tutorial/stdlib2 :Warning WARNING:root:Warning:config file server.conf not found
173 using/cmdline :line file:line: category: message
174 using/cmdline :category action:message:category:module:line
175 using/cmdline :line action:message:category:module:line
176 using/cmdline :message action:message:category:module:line
177 using/cmdline :module action:message:category:module:line
178 using/cmdline :errorhandler :errorhandler
179 using/unix :Packaging https://en.opensuse.org/Portal:Packaging
180 whatsnew/2.0 418 :len
181 whatsnew/2.3 ::
182 whatsnew/2.3 :config
183 whatsnew/2.3 :Critical
184 whatsnew/2.3 :Error
185 whatsnew/2.3 :Problem
186 whatsnew/2.3 :root
187 whatsnew/2.3 :Warning
188 whatsnew/2.4 ::
189 whatsnew/2.4 :System
190 whatsnew/2.5 :memory :memory:
191 whatsnew/2.5 :step [start:stop:step]
192 whatsnew/2.5 :stop [start:stop:step]
193 whatsnew/2.7 :Sunday '2009:4:Sunday'
194 whatsnew/2.7 :: export PYTHONWARNINGS=all,error:::Cookie:0
195 whatsnew/2.7 :Cookie export PYTHONWARNINGS=all,error:::Cookie:0
196 whatsnew/2.7 :: >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
197 whatsnew/2.7 :: ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',

View File

@@ -0,0 +1,102 @@
{% extends "layout.html" %}
{% set title = 'Download' %}
{% if daily is defined %}
{% set dlbase = pathto('archives', 1) %}
{% else %}
{% set dlbase = 'https://docs.python.org/ftp/python/doc/' + release %}
{% endif %}
{% block body %}
<h1>{% trans %}Download Python {{ release }} Documentation{% endtrans %}</h1>
{% if last_updated %}
<p><b>{% trans %}Last updated on: {{ last_updated }}.{% endtrans %}</b></p>
{% endif %}
<p>{% trans %}To download an archive containing all the documents for
this version of Python in one of various formats, follow one of links
in this table. The numbers in the table are the size of the download
files in megabytes.{% endtrans %}</p>
<table class="docutils">
<tr><th>{% trans %}Format{% endtrans %}</th>
<th>{% trans %}Packed as .zip{% endtrans %}</th>
<th>{% trans %}Packed as .tar.bz2{% endtrans %}</th>
</tr>
<tr><td>{% trans %}PDF (US-Letter paper size){% endtrans %}</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.zip">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 11 MB){% endtrans %}
</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.tar.bz2">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 11 MB){% endtrans %}
</td>
</tr>
<tr><td>{% trans %}PDF (A4 paper size){% endtrans %}</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.zip">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 11 MB){% endtrans %}</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.tar.bz2">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 11 MB){% endtrans %}</td>
</tr>
<tr><td>{% trans %}HTML{% endtrans %}</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-html.zip">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 7.5 MB){% endtrans %}
</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-html.tar.bz2">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 5 MB){% endtrans %}
</td>
</tr>
<tr>
<td>{% trans %}Plain Text{% endtrans %}</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-text.zip">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 2.5 MB){% endtrans %}
</td>
<td>
<a href="{{ dlbase }}/python-{{ release }}-docs-text.tar.bz2">
{% trans %}Download{% endtrans %}
</a> {% trans %}(ca. 2 MB){% endtrans %}
</td>
</tr>
</table>
<p>{% trans %}These archives contain all the content in the
documentation.{% endtrans %}</p>
<p>{% trans download_page="https://www.python.org/downloads/release/python-" + release.replace('.', '') + "/" %}HTML Help
(<tt>.chm</tt>) files are made available in the "Files" section
on the <a href="{{ download_page }}">Python download page</a>.{% endtrans %}</p>
<h2>{% trans %}Unpacking{% endtrans %}</h2>
<p>{% trans %}Unix users should download the .tar.bz2 archives; these
are bzipped tar archives and can be handled in the usual way using tar
and the bzip2 program. The <a href="http://www.info-zip.org">InfoZIP</a> unzip
program can be used to handle the ZIP archives if desired. The
.tar.bz2 archives provide the best compression and fastest download
times.{% endtrans %}</p>
<p>{% trans %}Windows users can use the ZIP archives since those are
customary on that platform. These are created on Unix using the
InfoZIP zip program.{% endtrans %}</p>
<h2>{% trans %}Problems{% endtrans %}</h2>
<p>{% trans %}If you have comments or suggestions for the Python
documentation, please send email to
<a href="mailto:docs@python.org">docs@python.org</a>.{% endtrans %}</p>
{% endblock %}

View File

@@ -0,0 +1,66 @@
{% extends "layout.html" %}
{%- block htmltitle -%}
<title>{{ shorttitle }}</title>
{%- endblock -%}
{% block body %}
<h1>{{ docstitle|e }}</h1>
<p>
{% trans %}Welcome! This is the documentation for Python {{ release }}.{% endtrans %}
</p>
<p><strong>{% trans %}Parts of the documentation:{% endtrans %}</strong></p>
<table class="contentstable" align="center"><tr>
<td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("whatsnew/" + version) }}">{% trans %}What's new in Python {{ version }}?{% endtrans %}</a><br/>
<span class="linkdescr">{% trans whatsnew_index=pathto("whatsnew/index") %}or <a href="{{ whatsnew_index }}">all "What's new" documents</a> since 2.0{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("tutorial/index") }}">{% trans %}Tutorial{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}start here{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("library/index") }}">{% trans %}Library Reference{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}keep this under your pillow{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("reference/index") }}">{% trans %}Language Reference{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}describes syntax and language elements{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("using/index") }}">{% trans %}Python Setup and Usage{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}how to use Python on different platforms{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("howto/index") }}">{% trans %}Python HOWTOs{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}in-depth documents on specific topics{% endtrans %}</span></p>
</td><td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("installing/index") }}">{% trans %}Installing Python Modules{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}installing from the Python Package Index &amp; other sources{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("distributing/index") }}">{% trans %}Distributing Python Modules{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}publishing modules for installation by others{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("extending/index") }}">{% trans %}Extending and Embedding{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}tutorial for C/C++ programmers{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("c-api/index") }}">{% trans %}Python/C API{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}reference for C/C++ programmers{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("faq/index") }}">{% trans %}FAQs{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}frequently asked questions (with answers!){% endtrans %}</span></p>
</td></tr>
</table>
<p><strong>{% trans %}Indices and tables:{% endtrans %}</strong></p>
<table class="contentstable" align="center"><tr>
<td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("py-modindex") }}">{% trans %}Global Module Index{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}quick access to all modules{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("genindex") }}">{% trans %}General Index{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}all functions, classes, terms{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("glossary") }}">{% trans %}Glossary{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}the most important terms explained{% endtrans %}</span></p>
</td><td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("search") }}">{% trans %}Search page{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}search this documentation{% endtrans %}</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">{% trans %}Complete Table of Contents{% endtrans %}</a><br/>
<span class="linkdescr">{% trans %}lists all sections and subsections{% endtrans %}</span></p>
</td></tr>
</table>
<p><strong>{% trans %}Meta information:{% endtrans %}</strong></p>
<table class="contentstable" align="center"><tr>
<td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("bugs") }}">{% trans %}Reporting bugs{% endtrans %}</a></p>
<p class="biglink"><a class="biglink" href="{{ pathto("about") }}">{% trans %}About the documentation{% endtrans %}</a></p>
</td><td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("license") }}">{% trans %}History and License of Python{% endtrans %}</a></p>
<p class="biglink"><a class="biglink" href="{{ pathto("copyright") }}">{% trans %}Copyright{% endtrans %}</a></p>
</td></tr>
</table>
{% endblock %}

View File

@@ -0,0 +1,21 @@
<h3>{% trans %}Download{% endtrans %}</h3>
<p><a href="{{ pathto('download') }}">{% trans %}Download these documents{% endtrans %}</a></p>
<h3>{% trans %}Docs by version{% endtrans %}</h3>
<ul>
<li><a href="https://docs.python.org/3.9/">{% trans %}Python 3.9 (in development){% endtrans %}</a></li>
<li><a href="https://docs.python.org/3.8/">{% trans %}Python 3.8 (stable){% endtrans %}</a></li>
<li><a href="https://docs.python.org/3.7/">{% trans %}Python 3.7 (stable){% endtrans %}</a></li>
<li><a href="https://docs.python.org/3.6/">{% trans %}Python 3.6 (security-fixes){% endtrans %}</a></li>
<li><a href="https://docs.python.org/3.5/">{% trans %}Python 3.5 (security-fixes){% endtrans %}</a></li>
<li><a href="https://docs.python.org/2.7/">{% trans %}Python 2.7 (EOL){% endtrans %}</a></li>
<li><a href="https://www.python.org/doc/versions/">{% trans %}All versions{% endtrans %}</a></li>
</ul>
<h3>{% trans %}Other resources{% endtrans %}</h3>
<ul>
{# XXX: many of these should probably be merged in the main docs #}
<li><a href="https://www.python.org/dev/peps/">{% trans %}PEP Index{% endtrans %}</a></li>
<li><a href="https://wiki.python.org/moin/BeginnersGuide">{% trans %}Beginner's Guide{% endtrans %}</a></li>
<li><a href="https://wiki.python.org/moin/PythonBooks">{% trans %}Book List{% endtrans %}</a></li>
<li><a href="https://www.python.org/doc/av/">{% trans %}Audio/Visual Talks{% endtrans %}</a></li>
</ul>

View File

@@ -0,0 +1,64 @@
{% extends "!layout.html" %}
{% block header %}
{%- if outdated %}
<div id="outdated-warning" style="padding: .5em; text-align: center; background-color: #FFBABA; color: #6A0E0E;">
{% trans %}This document is for an old version of Python that is {% endtrans %}<a href="https://devguide.python.org/devcycle/#end-of-life-branches">{% trans %}no longer supported{% endtrans %}</a>.
{% trans %}You should upgrade and read the {% endtrans %}
<a href="https://docs.python.org/{{ language + '/' if language and language != 'en' else '' }}3/{{ pagename }}{{ file_suffix }}">{% trans %} Python documentation for the current stable release{% endtrans %}</a>.
</div>
{%- endif %}
{% endblock %}
{% block rootrellink %}
<li><img src="{{ pathto('_static/py.png', 1) }}" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a>{{ reldelim1 }}</li>
<li>
{%- if switchers is defined %}
<span class="language_switcher_placeholder">{{ language or 'en' }}</span>
<span class="version_switcher_placeholder">{{ release }}</span>
<a href="{{ pathto('index') }}">{% trans %}Documentation{% endtrans %}</a>{{ reldelim1 }}
{%- else %}
<a href="{{ pathto('index') }}">{{ shorttitle }}</a>{{ reldelim1 }}
{%- endif %}
</li>
{% endblock %}
{% block relbar1 %} {% if builder != 'qthelp' %} {{ relbar() }} {% endif %} {% endblock %}
{% block relbar2 %} {% if builder != 'qthelp' %} {{ relbar() }} {% endif %} {% endblock %}
{% block extrahead %}
<link rel="shortcut icon" type="image/png" href="{{ pathto('_static/py.png', 1) }}" />
<link rel="canonical" href="https://docs.python.org/2/{{pagename}}.html" />
{% if not embedded %}<script type="text/javascript" src="{{ pathto('_static/copybutton.js', 1) }}"></script>{% endif %}
{% if switchers is defined and not embedded %}<script type="text/javascript" src="{{ pathto('_static/switchers.js', 1) }}"></script>{% endif %}
{{ super() }}
{% if builder == 'qthelp' %}
<style type="text/css">
body { background-color: white; }
div.document { background-color: white; }
</style>
{% endif %}
{% endblock %}
{% block footer %}
<div class="footer">
&copy; <a href="{{ pathto('copyright') }}">{% trans %}Copyright{% endtrans %}</a> {{ copyright|e }}.
<br />
{% trans %}The Python Software Foundation is a non-profit corporation.{% endtrans %}
<a href="https://www.python.org/psf/donations/">{% trans %}Please donate.{% endtrans %}</a>
<br />
{% trans last_update=last_updated|e %}Last updated on {{ last_update }}.{% endtrans %}
{% trans pathto_bugs=pathto('bugs') %}<a href="{{ pathto_bugs }}">Found a bug</a>?{% endtrans %}
<br />
{% trans sphinx_version=sphinx_version|e %}Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> {{ sphinx_version }}.{% endtrans %}
</div>
{% endblock %}
{% block sidebarsourcelink %}
{%- if show_source and has_source and sourcename %}
<h3>{{ _('This Page') }}</h3>
<ul class="this-page-menu">
<li><a href="{{ pathto('bugs') }}">{% trans %}Report a Bug{% endtrans %}</a></li>
<li><a href="https://github.com/python/cpython/blob/{{ version }}/Doc/{{ sourcename|replace('.rst.txt', '.rst') }}"
rel="nofollow">{% trans %}Show Source{% endtrans %}</a>
</li>
</ul>
{%- endif %}
{% endblock %}

View File

@@ -0,0 +1,4 @@
{% extends "!opensearch.xml" %}
{% block extra -%}
<Image height="16" width="16" type="image/x-icon">https://www.python.org/images/favicon16x16.ico</Image>
{%- endblock %}