Issue #26462: Doc: reduce literal_block warnings, fix syntax highlighting.

Patch by Julien Palard.
This commit is contained in:
Martin Panter 2016-07-26 11:18:21 +02:00
parent 87ec85f420
commit 1050d2d0c7
47 changed files with 329 additions and 128 deletions

View file

@ -245,7 +245,9 @@ Let's take an example with a simple script::
setup(name='foobar')
Running the ``check`` command will display some warnings::
Running the ``check`` command will display some warnings:
.. code-block:: shell-session
$ python setup.py check
running check
@ -274,7 +276,9 @@ For example, if the :file:`setup.py` script is changed like this::
url='http://example.com', long_description=desc)
Where the long description is broken, ``check`` will be able to detect it
by using the :mod:`docutils` parser::
by using the :mod:`docutils` parser:
.. code-block:: shell-session
$ python setup.py check --restructuredtext
running check
@ -286,7 +290,9 @@ Reading the metadata
The :func:`distutils.core.setup` function provides a command-line interface
that allows you to query the metadata fields of a project through the
``setup.py`` script of a given project::
``setup.py`` script of a given project:
.. code-block:: shell-session
$ python setup.py --name
distribute

View file

@ -233,7 +233,9 @@ in the root of the package besides :file:`setup.py`.
To prevent registering broken reStructuredText content, you can use the
:program:`rst2html` program that is provided by the :mod:`docutils` package and
check the ``long_description`` from the command line::
check the ``long_description`` from the command line:
.. code-block:: shell-session
$ python setup.py --long-description | rst2html.py > output.html

View file

@ -133,7 +133,9 @@ described above does not apply in this case.
The manifest template has one command per line, where each command specifies a
set of files to include or exclude from the source distribution. For an
example, again we turn to the Distutils' own manifest template::
example, again we turn to the Distutils' own manifest template:
.. code-block:: none
include *.txt
recursive-include examples *.txt *.py

View file

@ -55,7 +55,9 @@ Since distutils also supports creation of binary packages, users don't
necessarily need a compiler and distutils to install the extension.
A distutils package contains a driver script, :file:`setup.py`. This is a plain
Python file, which, in the most simple case, could look like this::
Python file, which, in the most simple case, could look like this:
.. code-block:: python3
from distutils.core import setup, Extension
@ -96,7 +98,9 @@ file, :file:`demo.c`.
In many cases, building an extension is more complex, since additional
preprocessor defines and libraries may be needed. This is demonstrated in the
example below. ::
example below.
.. code-block:: python3
from distutils.core import setup, Extension
@ -161,4 +165,3 @@ commands can be used to do so. ::
python setup.py bdist_wininst
python setup.py bdist_rpm
python setup.py bdist_dumb

View file

@ -155,7 +155,9 @@ script, such as:
c = c + b
return c
then the result should be::
then the result should be:
.. code-block:: shell-session
$ call multiply multiply 3 2
Will compute 3 times 2
@ -289,16 +291,20 @@ available). This script has several options, of which the following will
be directly useful to you:
* ``pythonX.Y-config --cflags`` will give you the recommended flags when
compiling::
compiling:
$ /opt/bin/python3.4-config --cflags
-I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
.. code-block:: shell-session
$ /opt/bin/python3.4-config --cflags
-I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
* ``pythonX.Y-config --ldflags`` will give you the recommended flags when
linking::
linking:
$ /opt/bin/python3.4-config --ldflags
-L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
.. code-block:: shell-session
$ /opt/bin/python3.4-config --ldflags
-L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
.. note::
To avoid confusion between several Python installations (and especially

View file

@ -792,7 +792,9 @@ the format string is empty, it returns ``None``; if it contains exactly one
format unit, it returns whatever object is described by that format unit. To
force it to return a tuple of size 0 or one, parenthesize the format string.
Examples (to the left the call, to the right the resulting Python value)::
Examples (to the left the call, to the right the resulting Python value):
.. code-block:: none
Py_BuildValue("") None
Py_BuildValue("i", 123) 123
@ -1348,4 +1350,3 @@ code distribution).
.. [#] These guarantees don't hold when you use the "old" style calling convention ---
this is still found in much existing code.

View file

@ -209,7 +209,9 @@ That's it! All that remains is to build it; put the above code in a file called
setup(name="noddy", version="1.0",
ext_modules=[Extension("noddy", ["noddy.c"])])
in a file called :file:`setup.py`; then typing ::
in a file called :file:`setup.py`; then typing
.. code-block:: shell-session
$ python setup.py build
@ -1513,4 +1515,3 @@ might be something like the following::
.. [#] Even in the third version, we aren't guaranteed to avoid cycles. Instances of
string subclasses are allowed and string subclasses could allow cycles even if
normal strings don't.

View file

@ -146,7 +146,9 @@ this object to :data:`sys.stdout` and :data:`sys.stderr`. Call print_error, or
just allow the standard traceback mechanism to work. Then, the output will go
wherever your ``write()`` method sends it.
The easiest way to do this is to use the :class:`io.StringIO` class::
The easiest way to do this is to use the :class:`io.StringIO` class:
.. code-block:: pycon
>>> import io, sys
>>> sys.stdout = io.StringIO()
@ -156,7 +158,9 @@ The easiest way to do this is to use the :class:`io.StringIO` class::
foo
hello world!
A custom object to do the same would look like this::
A custom object to do the same would look like this:
.. code-block:: pycon
>>> import io, sys
>>> class StdoutCatcher(io.TextIOBase):
@ -222,11 +226,15 @@ How do I debug an extension?
When using GDB with dynamically loaded extensions, you can't set a breakpoint in
your extension until your extension is loaded.
In your ``.gdbinit`` file (or interactively), add the command::
In your ``.gdbinit`` file (or interactively), add the command:
.. code-block:: none
br _PyImport_LoadDynamicModule
Then, when you run GDB::
Then, when you run GDB:
.. code-block:: shell-session
$ gdb /local/bin/python
gdb) run myscript.py

View file

@ -152,7 +152,9 @@ Let's dive in!
For my example I'm using ``_pickle.Pickler.dump()``.
2. If the call to the ``PyArg_Parse`` function uses any of the
following format units::
following format units:
.. code-block:: none
O&
O!

View file

@ -377,7 +377,9 @@ An example of using these two classes follows (imports omitted)::
root.warning('Look out!')
listener.stop()
which, when run, will produce::
which, when run, will produce:
.. code-block:: none
MainThread: Look out!
@ -1860,7 +1862,9 @@ script, ``chowntest.py``::
logger = logging.getLogger('mylogger')
logger.debug('A debug message')
To run this, you will probably need to run as ``root``::
To run this, you will probably need to run as ``root``:
.. code-block:: shell-session
$ sudo python3.3 chowntest.py
$ cat chowntest.log
@ -2485,7 +2489,9 @@ via ``stderr`` and once via ``stdout``). After the ``with`` statement's
completion, the status is as it was before so message #6 appears (like message
#1) whereas message #7 doesn't (just like message #2).
If we run the resulting script, the result is as follows::
If we run the resulting script, the result is as follows:
.. code-block:: shell-session
$ python logctx.py
1. This should appear just once on stderr.
@ -2495,12 +2501,16 @@ If we run the resulting script, the result is as follows::
6. This should appear just once on stderr.
If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
which is the only message written to ``stdout``::
which is the only message written to ``stdout``:
.. code-block:: shell-session
$ python logctx.py 2>/dev/null
5. This should appear twice - once on stderr and once on stdout.
Once again, but piping ``stdout`` to ``/dev/null``, we get::
Once again, but piping ``stdout`` to ``/dev/null``, we get:
.. code-block:: shell-session
$ python logctx.py >/dev/null
1. This should appear just once on stderr.

View file

@ -106,7 +106,9 @@ A very simple example is::
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
If you type these lines into a script and run it, you'll see::
If you type these lines into a script and run it, you'll see:
.. code-block:: none
WARNING:root:Watch out!
@ -230,7 +232,9 @@ append the variable data as arguments. For example::
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
will display::
will display:
.. code-block:: none
WARNING:root:Look before you leap!
@ -594,7 +598,9 @@ logger, a console handler, and a simple formatter using Python code::
logger.error('error message')
logger.critical('critical message')
Running this module from the command line produces the following output::
Running this module from the command line produces the following output:
.. code-block:: shell-session
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
@ -653,7 +659,9 @@ Here is the logging.conf file::
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
The output is nearly identical to that of the non-config-file-based example::
The output is nearly identical to that of the non-config-file-based example:
.. code-block:: shell-session
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
@ -1073,4 +1081,3 @@ take up any memory.
Useful handlers included with the logging module.
:ref:`A logging cookbook <logging-cookbook>`

View file

@ -74,7 +74,9 @@ of the RE by repeating them or changing their meaning. Much of this document is
devoted to discussing various metacharacters and what they do.
Here's a complete list of the metacharacters; their meanings will be discussed
in the rest of this HOWTO. ::
in the rest of this HOWTO.
.. code-block:: none
. ^ $ * + ? { } [ ] \ | ( )

View file

@ -613,7 +613,9 @@ program::
print(os.listdir(b'.'))
print(os.listdir('.'))
will produce the following output::
will produce the following output:
.. code-block:: shell-session
amk:~$ python t.py
[b'filename\xe4\x94\x80abc', ...]

View file

@ -33,14 +33,18 @@ Here is a sample Python 2.x source file, :file:`example.py`::
name = raw_input()
greet(name)
It can be converted to Python 3.x code via 2to3 on the command line::
It can be converted to Python 3.x code via 2to3 on the command line:
.. code-block:: shell-session
$ 2to3 example.py
A diff against the original source file is printed. 2to3 can also write the
needed modifications right back to the source file. (A backup of the original
file is made unless :option:`-n` is also given.) Writing the changes back is
enabled with the :option:`-w` flag::
enabled with the :option:`-w` flag:
.. code-block:: shell-session
$ 2to3 -w example.py
@ -57,17 +61,23 @@ Comments and exact indentation are preserved throughout the translation process.
By default, 2to3 runs a set of :ref:`predefined fixers <2to3-fixers>`. The
:option:`!-l` flag lists all available fixers. An explicit set of fixers to run
can be given with :option:`-f`. Likewise the :option:`!-x` explicitly disables a
fixer. The following example runs only the ``imports`` and ``has_key`` fixers::
fixer. The following example runs only the ``imports`` and ``has_key`` fixers:
.. code-block:: shell-session
$ 2to3 -f imports -f has_key example.py
This command runs every fixer except the ``apply`` fixer::
This command runs every fixer except the ``apply`` fixer:
.. code-block:: shell-session
$ 2to3 -x apply example.py
Some fixers are *explicit*, meaning they aren't run by default and must be
listed on the command line to be run. Here, in addition to the default fixers,
the ``idioms`` fixer is run::
the ``idioms`` fixer is run:
.. code-block:: shell-session
$ 2to3 -f all -f idioms example.py
@ -113,7 +123,9 @@ This option implies the :option:`-w` flag as it would not make sense otherwise.
The :option:`--add-suffix` option specifies a string to append to all output
filenames. The :option:`-n` flag is required when specifying this as backups
are not necessary when writing to different filenames. Example::
are not necessary when writing to different filenames. Example:
.. code-block:: shell-session
$ 2to3 -n -W --add-suffix=3 example.py
@ -122,7 +134,9 @@ Will cause a converted file named ``example.py3`` to be written.
.. versionadded:: 3.2.3
The :option:`--add-suffix` option was added.
To translate an entire project from one directory tree to another use::
To translate an entire project from one directory tree to another use:
.. code-block:: shell-session
$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode

View file

@ -45,7 +45,9 @@ produces either the sum or the max::
print(args.accumulate(args.integers))
Assuming the Python code above is saved into a file called ``prog.py``, it can
be run at the command line and provides useful help messages::
be run at the command line and provides useful help messages:
.. code-block:: shell-session
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
@ -60,7 +62,9 @@ be run at the command line and provides useful help messages::
--sum sum the integers (default: find the max)
When run with the appropriate arguments, it prints either the sum or the max of
the command-line integers::
the command-line integers:
.. code-block:: shell-session
$ python prog.py 1 2 3 4
4
@ -68,7 +72,9 @@ the command-line integers::
$ python prog.py 1 2 3 4 --sum
10
If invalid arguments are passed in, it will issue an error::
If invalid arguments are passed in, it will issue an error:
.. code-block:: shell-session
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
@ -194,7 +200,9 @@ invoked on the command line. For example, consider a file named
args = parser.parse_args()
The help for this program will display ``myprogram.py`` as the program name
(regardless of where the program was invoked from)::
(regardless of where the program was invoked from):
.. code-block:: shell-session
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
@ -596,7 +604,9 @@ the parser's help message. For example, consider a file named
args = parser.parse_args()
If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
help will be printed::
help will be printed:
.. code-block:: shell-session
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

View file

@ -99,6 +99,7 @@ Abstract Grammar
The abstract grammar is currently defined as follows:
.. literalinclude:: ../../Parser/Python.asdl
:language: none
:mod:`ast` Helpers

View file

@ -321,14 +321,18 @@ operations::
print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
loop.close()
Expected output::
Expected output:
.. code-block:: none
(1) create file
(2) write into file
(3) close file
Pending tasks at exit: set()
Actual output::
Actual output:
.. code-block:: none
(3) close file
(2) write into file
@ -369,13 +373,17 @@ Pending task destroyed
If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
<coroutine>` did not complete. It is probably a bug and so a warning is logged.
Example of log::
Example of log:
.. code-block:: none
Task was destroyed but it is pending!
task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()]>>
:ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
traceback where the task was created. Example of log in debug mode::
traceback where the task was created. Example of log in debug mode:
.. code-block:: none
Task was destroyed but it is pending!
source_traceback: Object created at (most recent call last):

View file

@ -442,7 +442,9 @@ installing a copy of this module file (:file:`cgi.py`) as a CGI script. When
invoked as a script, the file will dump its environment and the contents of the
form in HTML form. Give it the right mode etc, and send it a request. If it's
installed in the standard :file:`cgi-bin` directory, it should be possible to
send it a request by entering a URL into your browser of the form::
send it a request by entering a URL into your browser of the form:
.. code-block:: none
http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
@ -534,4 +536,3 @@ Common problems and solutions
order the field values should be supplied in, but knowing whether a request
was received from a conforming browser, or even from a browser at all, is
tedious and error-prone.

View file

@ -314,7 +314,9 @@ immediate playback::
Here is a sample session with the turtle shell showing the help functions, using
blank lines to repeat commands, and the simple record and playback facility::
blank lines to repeat commands, and the simple record and playback facility:
.. code-block:: none
Welcome to the turtle shell. Type help or ? to list commands.
@ -373,4 +375,3 @@ blank lines to repeat commands, and the simple record and playback facility::
(turtle) bye
Thank you for using Turtle

View file

@ -163,7 +163,7 @@ an exception::
>>> c.traps[FloatOperation] = True
>>> Decimal(3.14)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') < 3.7
Traceback (most recent call last):

View file

@ -88,14 +88,18 @@ Here's a complete but small example module::
doctest.testmod()
If you run :file:`example.py` directly from the command line, :mod:`doctest`
works its magic::
works its magic:
.. code-block:: shell-session
$ python example.py
$
There's no output! That's normal, and it means all the examples worked. Pass
``-v`` to the script, and :mod:`doctest` prints a detailed log of what
it's trying, and prints a summary at the end::
it's trying, and prints a summary at the end:
.. code-block:: shell-session
$ python example.py -v
Trying:
@ -109,7 +113,9 @@ it's trying, and prints a summary at the end::
[1, 1, 2, 6, 24, 120]
ok
And so on, eventually ending with::
And so on, eventually ending with:
.. code-block:: none
Trying:
factorial(1e100)
@ -196,7 +202,9 @@ file. This can be done with the :func:`testfile` function::
That short script executes and verifies any interactive Python examples
contained in the file :file:`example.txt`. The file content is treated as if it
were a single giant docstring; the file doesn't need to contain a Python
program! For example, perhaps :file:`example.txt` contains this::
program! For example, perhaps :file:`example.txt` contains this:
.. code-block:: none
The ``example`` module
======================

View file

@ -59,7 +59,9 @@ way we could process it:
.. literalinclude:: ../includes/email-read-alternative-new-api.py
Up to the prompt, the output from the above is::
Up to the prompt, the output from the above is:
.. code-block:: none
To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
From: Pepé Le Pew <pepe@example.com>

View file

@ -61,7 +61,9 @@ as they are encountered::
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
The output will then be::
The output will then be:
.. code-block:: none
Encountered a start tag: html
Encountered a start tag: head

View file

@ -524,7 +524,7 @@ functions to be used from IDLE's Python shell.
Command line usage
^^^^^^^^^^^^^^^^^^
::
.. code-block:: none
idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...

View file

@ -243,7 +243,9 @@ otherwise, the context is used to determine what to instantiate.
handler.
All *other* keys are passed through as keyword arguments to the
handler's constructor. For example, given the snippet::
handler's constructor. For example, given the snippet:
.. code-block:: yaml
handlers:
console:
@ -352,7 +354,9 @@ it unambiguously, and then using the id in the source object's
configuration to indicate that a connection exists between the source
and the destination object with that id.
So, for example, consider the following YAML snippet::
So, for example, consider the following YAML snippet:
.. code-block:: yaml
formatters:
brief:
@ -409,7 +413,9 @@ to provide a 'factory' - a callable which is called with a
configuration dictionary and which returns the instantiated object.
This is signalled by an absolute import path to the factory being
made available under the special key ``'()'``. Here's a concrete
example::
example:
.. code-block:: yaml
formatters:
brief:
@ -626,7 +632,9 @@ configuration must be specified in a section called ``[logger_root]``.
:func:`dictConfig`, so it's worth considering transitioning to this newer
API when it's convenient to do so.
Examples of these sections in the file are given below. ::
Examples of these sections in the file are given below.
.. code-block:: ini
[loggers]
keys=root,log02,log03,log04,log05,log06,log07
@ -638,7 +646,9 @@ Examples of these sections in the file are given below. ::
keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
The root logger must specify a level and a list of handlers. An example of a
root logger section is given below. ::
root logger section is given below.
.. code-block:: ini
[logger_root]
level=NOTSET
@ -655,7 +665,9 @@ appear in the ``[handlers]`` section. These names must appear in the
file.
For loggers other than the root logger, some additional information is required.
This is illustrated by the following example. ::
This is illustrated by the following example.
.. code-block:: ini
[logger_parser]
level=DEBUG
@ -673,7 +685,8 @@ indicate that messages are **not** propagated to handlers up the hierarchy. The
say the name used by the application to get the logger.
Sections which specify handler configuration are exemplified by the following.
::
.. code-block:: ini
[handler_hand01]
class=StreamHandler
@ -693,7 +706,9 @@ a corresponding section in the configuration file.
The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
package's namespace, is the list of arguments to the constructor for the handler
class. Refer to the constructors for the relevant handlers, or to the examples
below, to see how typical entries are constructed. ::
below, to see how typical entries are constructed.
.. code-block:: ini
[handler_hand02]
class=FileHandler
@ -744,7 +759,9 @@ below, to see how typical entries are constructed. ::
formatter=form09
args=('localhost:9022', '/log', 'GET')
Sections which specify formatter configuration are typified by the following. ::
Sections which specify formatter configuration are typified by the following.
.. code-block:: ini
[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s
@ -780,5 +797,3 @@ condensed format.
Module :mod:`logging.handlers`
Useful handlers included with the logging module.

View file

@ -678,7 +678,9 @@ automatically adds a ``--version`` option to your parser. If it encounters
this option on the command line, it expands your ``version`` string (by
replacing ``%prog``), prints it to stdout, and exits.
For example, if your script is called ``/usr/bin/foo``::
For example, if your script is called ``/usr/bin/foo``:
.. code-block:: shell-session
$ /usr/bin/foo --version
foo 1.0
@ -728,14 +730,18 @@ program's usage message and an error message to standard error and exits with
error status 2.
Consider the first example above, where the user passes ``4x`` to an option
that takes an integer::
that takes an integer:
.. code-block:: shell-session
$ /usr/bin/foo -n 4x
Usage: foo [options]
foo: error: option -n: invalid integer value: '4x'
Or, where the user fails to pass a value at all::
Or, where the user fails to pass a value at all:
.. code-block:: shell-session
$ /usr/bin/foo -n
Usage: foo [options]

View file

@ -30,7 +30,9 @@ However, when the pickle file that you want to examine comes from an
untrusted source, ``-m pickletools`` is a safer option because it does
not execute pickle bytecode.
For example, with a tuple ``(1, 2)`` pickled in file ``x.pickle``::
For example, with a tuple ``(1, 2)`` pickled in file ``x.pickle``:
.. code-block:: shell-session
$ python -m pickle x.pickle
(1, 2)
@ -106,4 +108,3 @@ Programmatic Interface
Returns a new equivalent pickle string after eliminating unused ``PUT``
opcodes. The optimized pickle is shorter, takes less transmission time,
requires less storage space, and unpickles more efficiently.

View file

@ -86,7 +86,9 @@ The :mod:`xml.parsers.expat` module contains two functions:
separator.
For example, if *namespace_separator* is set to a space character (``' '``) and
the following document is parsed::
the following document is parsed:
.. code-block:: xml
<?xml version="1.0"?>
<root xmlns = "http://default-namespace.org/"

View file

@ -603,7 +603,9 @@ found in the :file:`.ssh` directory of the user::
>>> make_archive(archive_name, 'gztar', root_dir)
'/Users/tarek/myarchive.tar.gz'
The resulting archive contains::
The resulting archive contains:
.. code-block:: shell-session
$ tar -tzvf /Users/tarek/myarchive.tar.gz
drwx------ tarek/staff 0 2010-02-01 16:23:40 ./

View file

@ -479,7 +479,9 @@ This is the client side::
The output of the example should look something like this:
Server::
Server:
.. code-block:: shell-session
$ python TCPServer.py
127.0.0.1 wrote:
@ -487,7 +489,9 @@ Server::
127.0.0.1 wrote:
b'python is nice'
Client::
Client:
.. code-block:: shell-session
$ python TCPClient.py hello world with TCP
Sent: hello world with TCP
@ -599,7 +603,9 @@ An example for the :class:`ThreadingMixIn` class::
server.server_close()
The output of the example should look something like this::
The output of the example should look something like this:
.. code-block:: shell-session
$ python ThreadedTCPServer.py
Server loop running in thread: Thread-1

View file

@ -950,20 +950,23 @@ been imported from the :mod:`subprocess` module.
Replacing /bin/sh shell backquote
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
.. code-block:: bash
output=`mycmd myarg`
# becomes
output = check_output(["mycmd", "myarg"])
becomes::
output = check_output(["mycmd", "myarg"])
Replacing shell pipeline
^^^^^^^^^^^^^^^^^^^^^^^^
::
.. code-block:: bash
output=`dmesg | grep hda`
# becomes
becomes::
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
@ -973,10 +976,14 @@ The p1.stdout.close() call after starting the p2 is important in order for p1
to receive a SIGPIPE if p2 exits before p1.
Alternatively, for trusted input, the shell's own pipeline support may still
be used directly::
be used directly:
.. code-block:: bash
output=`dmesg | grep hda`
# becomes
becomes::
output=check_output("dmesg | grep hda", shell=True)

View file

@ -1282,7 +1282,9 @@ always available.
A dictionary of the various implementation-specific flags passed through
the :option:`-X` command-line option. Option names are either mapped to
their values, if given explicitly, or to :const:`True`. Example::
their values, if given explicitly, or to :const:`True`. Example:
.. code-block:: shell-session
$ ./python -Xa=b -Xc
Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)

View file

@ -229,7 +229,9 @@ Other functions
Using :mod:`sysconfig` as a script
----------------------------------
You can use :mod:`sysconfig` as a script with Python's *-m* option::
You can use :mod:`sysconfig` as a script with Python's *-m* option:
.. code-block:: shell-session
$ python -m sysconfig
Platform: "macosx-10.4-i386"

View file

@ -654,25 +654,35 @@ The :mod:`tarfile` module provides a simple command line interface to interact
with tar archives.
If you want to create a new tar archive, specify its name after the :option:`-c`
option and then list the filename(s) that should be included::
option and then list the filename(s) that should be included:
.. code-block:: shell-session
$ python -m tarfile -c monty.tar spam.txt eggs.txt
Passing a directory is also acceptable::
Passing a directory is also acceptable:
.. code-block:: shell-session
$ python -m tarfile -c monty.tar life-of-brian_1979/
If you want to extract a tar archive into the current directory, use
the :option:`-e` option::
the :option:`-e` option:
.. code-block:: shell-session
$ python -m tarfile -e monty.tar
You can also extract a tar archive into a different directory by passing the
directory's name::
directory's name:
.. code-block:: shell-session
$ python -m tarfile -e monty.tar other-dir/
For a list of the files in a tar archive, use the :option:`-l` option::
For a list of the files in a tar archive, use the :option:`-l` option:
.. code-block:: shell-session
$ python -m tarfile -l monty.tar

View file

@ -147,7 +147,9 @@ Examples
--------
Here is an example that imports a module from a ZIP archive - note that the
:mod:`zipimport` module is not explicitly used. ::
:mod:`zipimport` module is not explicitly used.
.. code-block:: shell-session
$ unzip -l example.zip
Archive: example.zip

View file

@ -1406,7 +1406,9 @@ Lambdas
Lambda expressions (sometimes called lambda forms) are used to create anonymous
functions. The expression ``lambda arguments: expression`` yields a function
object. The unnamed object behaves like a function object defined with ::
object. The unnamed object behaves like a function object defined with:
.. code-block:: none
def <lambda>(arguments):
return expression

View file

@ -689,7 +689,10 @@ Operators
.. index:: single: operators
The following tokens are operators::
The following tokens are operators:
.. code-block:: none
+ - * ** / // % @
<< >> & | ^ ~
@ -703,7 +706,9 @@ Delimiters
.. index:: single: delimiters
The following tokens serve as delimiters in the grammar::
The following tokens serve as delimiters in the grammar:
.. code-block:: none
( ) [ ] { }
, : . ; @ = ->
@ -716,12 +721,16 @@ of the list, the augmented assignment operators, serve lexically as delimiters,
but also perform an operation.
The following printing ASCII characters have special meaning as part of other
tokens or are otherwise significant to the lexical analyzer::
tokens or are otherwise significant to the lexical analyzer:
.. code-block:: none
' " # \
The following printing ASCII characters are not used in Python. Their
occurrence outside string literals and comments is an unconditional error::
occurrence outside string literals and comments is an unconditional error:
.. code-block:: none
$ ? `

View file

@ -501,7 +501,9 @@ It could be called like this::
client="John Cleese",
sketch="Cheese Shop Sketch")
and of course it would print::
and of course it would print:
.. code-block:: none
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger

View file

@ -94,7 +94,9 @@ mode*. In this mode it prompts for the next command with the *primary prompt*,
usually three greater-than signs (``>>>``); for continuation lines it prompts
with the *secondary prompt*, by default three dots (``...``). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt::
before printing the first prompt:
.. code-block:: shell-session
$ python3.5
Python 3.5 (default, Sep 16 2015, 09:25:04)

View file

@ -140,7 +140,9 @@ the end of your module::
you can make the file usable as a script as well as an importable module,
because the code that parses the command line only runs if the module is
executed as the "main" file::
executed as the "main" file:
.. code-block:: shell-session
$ python fibo.py 50
1 1 2 3 5 8 13 21 34

View file

@ -291,7 +291,9 @@ PEP 273: Importing Modules from ZIP Archives
The new :mod:`zipimport` module adds support for importing modules from a ZIP-
format archive. You don't need to import the module explicitly; it will be
automatically imported if a ZIP archive's filename is added to ``sys.path``.
For example::
For example:
.. code-block:: shell-session
amk@nyman:~/src/python$ unzip -l /tmp/example.zip
Archive: /tmp/example.zip
@ -1761,7 +1763,9 @@ This returns an object containing all of the option values, and a list of
strings containing the remaining arguments.
Invoking the script with the various arguments now works as you'd expect it to.
Note that the length argument is automatically converted to an integer. ::
Note that the length argument is automatically converted to an integer.
.. code-block:: shell-session
$ ./python opt.py -i data arg1
<Values at 0x400cad4c: {'input': 'data', 'length': None}>
@ -1771,7 +1775,9 @@ Note that the length argument is automatically converted to an integer. ::
[]
$
The help message is automatically generated for you::
The help message is automatically generated for you:
.. code-block:: shell-session
$ ./python opt.py --help
usage: opt.py [options]
@ -2078,4 +2084,3 @@ Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew
MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans
Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman
Suzi, Jason Tishler, Just van Rossum.

View file

@ -1425,7 +1425,9 @@ specifying the :const:`doctest.REPORT_UDIFF` (unified diffs),
print word
Running the above function's tests with :const:`doctest.REPORT_UDIFF` specified,
you get the following output::
you get the following output:
.. code-block:: none
**********************************************************************
File "t.py", line 15, in g

View file

@ -2290,7 +2290,9 @@ There is an existing data type already used for this,
written in pure Python could cause a segmentation fault by taking a
:c:type:`PyCObject` from module A and somehow substituting it for the
:c:type:`PyCObject` in module B. Capsules know their own name,
and getting the pointer requires providing the name::
and getting the pointer requires providing the name:
.. code-block:: c
void *vtable;
@ -2616,4 +2618,3 @@ The author would like to thank the following people for offering
suggestions, corrections and assistance with various drafts of this
article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
Hugh Secker-Walker.

View file

@ -117,7 +117,9 @@ You can also customize the separator between items, e.g.::
print("There are <", 2**32, "> possibilities!", sep="")
which produces::
which produces:
.. code-block:: none
There are <4294967296> possibilities!

View file

@ -160,6 +160,8 @@ each with their own argument patterns and help displays::
parser_m.add_argument('-c', '--course', type=int, required=True)
parser_m.add_argument('-s', '--speed', type=int, default=0)
.. code-block:: shell-session
$ ./helm.py --help # top level help (launch and move)
$ ./helm.py launch --help # help for launch options
$ ./helm.py launch --missiles # set missiles=True and torpedos=False
@ -478,7 +480,9 @@ Some smaller changes made to the core Python language are:
* The interpreter can now be started with a quiet option, ``-q``, to prevent
the copyright and version information from being displayed in the interactive
mode. The option can be introspected using the :attr:`sys.flags` attribute::
mode. The option can be introspected using the :attr:`sys.flags` attribute:
.. code-block:: shell-session
$ python -q
>>> sys.flags
@ -573,7 +577,9 @@ Some smaller changes made to the core Python language are:
by Benjamin Peterson in :issue:`8413`.)
* Warnings are now easier to control using the :envvar:`PYTHONWARNINGS`
environment variable as an alternative to using ``-W`` at the command line::
environment variable as an alternative to using ``-W`` at the command line:
.. code-block:: shell-session
$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'
@ -595,7 +601,9 @@ Some smaller changes made to the core Python language are:
object ensures it closes the underlying operating system resource
(usually, a file descriptor), the delay in deallocating the object could
produce various issues, especially under Windows. Here is an example
of enabling the warning from the command line::
of enabling the warning from the command line:
.. code-block:: shell-session
$ python -q -Wdefault
>>> f = open("foo", "wb")
@ -1720,7 +1728,9 @@ names.
test discovery can find tests within packages, locating any test importable
from the top-level directory. The top-level directory can be specified with
the `-t` option, a pattern for matching files with ``-p``, and a directory to
start discovery with ``-s``::
start discovery with ``-s``:
.. code-block:: shell-session
$ python -m unittest discover -s my_proj_dir -p _test.py
@ -1895,7 +1905,9 @@ pydoc
The :mod:`pydoc` module now provides a much-improved Web server interface, as
well as a new command-line option ``-b`` to automatically open a browser window
to display that server::
to display that server:
.. code-block:: shell-session
$ pydoc3.2 -b
@ -1998,7 +2010,9 @@ details of a given Python installation.
'/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'
Conveniently, some of site's functionality is accessible directly from the
command-line::
command-line:
.. code-block:: shell-session
$ python -m site --user-base
/Users/raymondhettinger/.local
@ -2031,7 +2045,9 @@ seven named schemes used by :mod:`distutils`. Those include *posix_prefix*,
* :func:`~sysconfig.get_config_vars` returns a dictionary of platform specific
variables.
There is also a convenient command-line interface::
There is also a convenient command-line interface:
.. code-block:: doscon
C:\Python32>python -m sysconfig
Platform: "win32"
@ -2265,7 +2281,9 @@ turtledemo
The demonstration code for the :mod:`turtle` module was moved from the *Demo*
directory to main library. It includes over a dozen sample scripts with
lively displays. Being on :attr:`sys.path`, it can now be run directly
from the command-line::
from the command-line:
.. code-block:: shell-session
$ python -m turtledemo
@ -2701,4 +2719,3 @@ require changes to your code:
* Due to the new :term:`GIL` implementation, :c:func:`PyEval_InitThreads()`
cannot be called before :c:func:`Py_Initialize()` anymore.

View file

@ -871,7 +871,9 @@ signal. Call :func:`faulthandler.enable` to install fault handlers for the
:envvar:`PYTHONFAULTHANDLER` environment variable or by using :option:`-X`
``faulthandler`` command line option.
Example of a segmentation fault on Linux: ::
Example of a segmentation fault on Linux:
.. code-block:: shell-session
$ python -q -X faulthandler
>>> import ctypes
@ -999,7 +1001,6 @@ byte of an invalid byte sequence. For example, ``b'\xff\n'.decode('gb2312',
Incremental CJK codec encoders are no longer reset at each call to their
encode() methods. For example::
$ ./python -q
>>> import codecs
>>> encoder = codecs.getincrementalencoder('hz')('strict')
>>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')

View file

@ -742,7 +742,9 @@ publicized, either at the time or since.
With the new module, bundling your application is as simple as putting all
the files, including a ``__main__.py`` file, into a directory ``myapp``
and running::
and running:
.. code-block:: shell-session
$ python -m zipapp myapp
$ python myapp.pyz