Patch by Julien Palard.
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
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
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
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
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
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
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
python setup.py bdist_wininst
python setup.py bdist_rpm
python setup.py bdist_dumb
-
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
be directly useful to you:
* ``pythonX.Y-config --cflags`` will give you the recommended flags when
- compiling::
+ compiling:
+
+ .. 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
+ $ /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:
+
+ .. 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
+ $ /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
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
.. [#] These guarantees don't hold when you use the "old" style calling convention ---
this is still found in much existing code.
-
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
.. [#] 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.
-
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()
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):
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
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!
root.warning('Look out!')
listener.stop()
-which, when run, will produce::
+which, when run, will produce:
+
+.. code-block:: none
MainThread: Look out!
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
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.
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.
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!
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
-will display::
+will display:
+
+.. code-block:: none
WARNING:root:Look before you leap!
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
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
Useful handlers included with the logging module.
:ref:`A logging cookbook <logging-cookbook>`
-
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
. ^ $ * + ? { } [ ] \ | ( )
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', ...]
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
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
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
.. 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
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 ...]
--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
$ 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 ...]
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]
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]
The abstract grammar is currently defined as follows:
.. literalinclude:: ../../Parser/Python.asdl
+ :language: none
:mod:`ast` Helpers
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
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):
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
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.
-
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.
(turtle) bye
Thank you for using Turtle
-
>>> 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):
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:
[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)
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
======================
.. 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>
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
Command line usage
^^^^^^^^^^^^^^^^^^
-::
+.. code-block:: none
idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...
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:
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:
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:
: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
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
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
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
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
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
Module :mod:`logging.handlers`
Useful handlers included with the logging module.
-
-
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
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]
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)
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.
-
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/"
>>> 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 ./
The output of the example should look something like this:
-Server::
+Server:
+
+.. code-block:: shell-session
$ python TCPServer.py
127.0.0.1 wrote:
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
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
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.
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)
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)
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"
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
--------
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
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
.. index:: single: operators
-The following tokens are operators::
+The following tokens are operators:
+
+.. code-block:: none
+
+ - * ** / // % @
<< >> & | ^ ~
.. index:: single: delimiters
-The following tokens serve as delimiters in the grammar::
+The following tokens serve as delimiters in the grammar:
+
+.. code-block:: none
( ) [ ] { }
, : . ; @ = ->
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
$ ? `
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
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)
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
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
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}>
[]
$
-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]
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.
-
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
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;
suggestions, corrections and assistance with various drafts of this
article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
Hugh Secker-Walker.
-
print("There are <", 2**32, "> possibilities!", sep="")
-which produces::
+which produces:
+
+.. code-block:: none
There are <4294967296> possibilities!
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
* 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
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::'
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")
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
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
'/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
* :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"
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
* Due to the new :term:`GIL` implementation, :c:func:`PyEval_InitThreads()`
cannot be called before :c:func:`Py_Initialize()` anymore.
-
: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
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.')
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