# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2016, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.6\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-10-17 21:44+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../Doc/howto/argparse.rst:3 msgid "Argparse Tutorial" msgstr "" #: ../Doc/howto/argparse.rst:5 msgid "Tshepang Lekhonkhobe" msgstr "" #: ../Doc/howto/argparse.rst:9 msgid "" "This tutorial is intended to be a gentle introduction to :mod:`argparse`, " "the recommended command-line parsing module in the Python standard library." msgstr "" #: ../Doc/howto/argparse.rst:14 msgid "" "There are two other modules that fulfill the same task, namely :mod:`getopt` " "(an equivalent for :c:func:`getopt` from the C language) and the deprecated :" "mod:`optparse`. Note also that :mod:`argparse` is based on :mod:`optparse`, " "and therefore very similar in terms of usage." msgstr "" #: ../Doc/howto/argparse.rst:22 msgid "Concepts" msgstr "" #: ../Doc/howto/argparse.rst:24 msgid "" "Let's show the sort of functionality that we are going to explore in this " "introductory tutorial by making use of the :command:`ls` command:" msgstr "" #: ../Doc/howto/argparse.rst:46 msgid "A few concepts we can learn from the four commands:" msgstr "" #: ../Doc/howto/argparse.rst:48 msgid "" "The :command:`ls` command is useful when run without any options at all. It " "defaults to displaying the contents of the current directory." msgstr "" #: ../Doc/howto/argparse.rst:51 msgid "" "If we want beyond what it provides by default, we tell it a bit more. In " "this case, we want it to display a different directory, ``pypy``. What we " "did is specify what is known as a positional argument. It's named so because " "the program should know what to do with the value, solely based on where it " "appears on the command line. This concept is more relevant to a command " "like :command:`cp`, whose most basic usage is ``cp SRC DEST``. The first " "position is *what you want copied,* and the second position is *where you " "want it copied to*." msgstr "" #: ../Doc/howto/argparse.rst:60 msgid "" "Now, say we want to change behaviour of the program. In our example, we " "display more info for each file instead of just showing the file names. The " "``-l`` in that case is known as an optional argument." msgstr "" #: ../Doc/howto/argparse.rst:64 msgid "" "That's a snippet of the help text. It's very useful in that you can come " "across a program you have never used before, and can figure out how it works " "simply by reading its help text." msgstr "" #: ../Doc/howto/argparse.rst:70 msgid "The basics" msgstr "" #: ../Doc/howto/argparse.rst:72 msgid "Let us start with a very simple example which does (almost) nothing::" msgstr "" #: ../Doc/howto/argparse.rst:78 ../Doc/howto/argparse.rst:186 #: ../Doc/howto/argparse.rst:207 msgid "Following is a result of running the code:" msgstr "" #: ../Doc/howto/argparse.rst:95 ../Doc/howto/argparse.rst:252 #: ../Doc/howto/argparse.rst:296 msgid "Here is what is happening:" msgstr "" #: ../Doc/howto/argparse.rst:97 msgid "" "Running the script without any options results in nothing displayed to " "stdout. Not so useful." msgstr "" #: ../Doc/howto/argparse.rst:100 msgid "" "The second one starts to display the usefulness of the :mod:`argparse` " "module. We have done almost nothing, but already we get a nice help message." msgstr "" #: ../Doc/howto/argparse.rst:103 msgid "" "The ``--help`` option, which can also be shortened to ``-h``, is the only " "option we get for free (i.e. no need to specify it). Specifying anything " "else results in an error. But even then, we do get a useful usage message, " "also for free." msgstr "" #: ../Doc/howto/argparse.rst:110 msgid "Introducing Positional arguments" msgstr "" #: ../Doc/howto/argparse.rst:112 msgid "An example::" msgstr "" #: ../Doc/howto/argparse.rst:120 msgid "And running the code:" msgstr "" #: ../Doc/howto/argparse.rst:138 msgid "Here is what's happening:" msgstr "" #: ../Doc/howto/argparse.rst:140 msgid "" "We've added the :meth:`add_argument` method, which is what we use to specify " "which command-line options the program is willing to accept. In this case, " "I've named it ``echo`` so that it's in line with its function." msgstr "" #: ../Doc/howto/argparse.rst:144 msgid "Calling our program now requires us to specify an option." msgstr "" #: ../Doc/howto/argparse.rst:146 msgid "" "The :meth:`parse_args` method actually returns some data from the options " "specified, in this case, ``echo``." msgstr "" #: ../Doc/howto/argparse.rst:149 msgid "" "The variable is some form of 'magic' that :mod:`argparse` performs for free " "(i.e. no need to specify which variable that value is stored in). You will " "also notice that its name matches the string argument given to the method, " "``echo``." msgstr "" #: ../Doc/howto/argparse.rst:154 msgid "" "Note however that, although the help display looks nice and all, it " "currently is not as helpful as it can be. For example we see that we got " "``echo`` as a positional argument, but we don't know what it does, other " "than by guessing or by reading the source code. So, let's make it a bit more " "useful::" msgstr "" #: ../Doc/howto/argparse.rst:165 msgid "And we get:" msgstr "" #: ../Doc/howto/argparse.rst:178 msgid "Now, how about doing something even more useful::" msgstr "" #: ../Doc/howto/argparse.rst:196 msgid "" "That didn't go so well. That's because :mod:`argparse` treats the options we " "give it as strings, unless we tell it otherwise. So, let's tell :mod:" "`argparse` to treat that input as an integer::" msgstr "" #: ../Doc/howto/argparse.rst:217 msgid "" "That went well. The program now even helpfully quits on bad illegal input " "before proceeding." msgstr "" #: ../Doc/howto/argparse.rst:222 msgid "Introducing Optional arguments" msgstr "" #: ../Doc/howto/argparse.rst:224 msgid "" "So far we, have been playing with positional arguments. Let us have a look " "on how to add optional ones::" msgstr "" #: ../Doc/howto/argparse.rst:234 ../Doc/howto/argparse.rst:280 #: ../Doc/howto/argparse.rst:396 ../Doc/howto/argparse.rst:430 msgid "And the output:" msgstr "" #: ../Doc/howto/argparse.rst:254 msgid "" "The program is written so as to display something when ``--verbosity`` is " "specified and display nothing when not." msgstr "" #: ../Doc/howto/argparse.rst:257 msgid "" "To show that the option is actually optional, there is no error when running " "the program without it. Note that by default, if an optional argument isn't " "used, the relevant variable, in this case :attr:`args.verbosity`, is given " "``None`` as a value, which is the reason it fails the truth test of the :" "keyword:`if` statement." msgstr "" #: ../Doc/howto/argparse.rst:263 msgid "The help message is a bit different." msgstr "" #: ../Doc/howto/argparse.rst:265 msgid "" "When using the ``--verbosity`` option, one must also specify some value, any " "value." msgstr "" #: ../Doc/howto/argparse.rst:268 msgid "" "The above example accepts arbitrary integer values for ``--verbosity``, but " "for our simple program, only two values are actually useful, ``True`` or " "``False``. Let's modify the code accordingly::" msgstr "" #: ../Doc/howto/argparse.rst:298 msgid "" "The option is now more of a flag than something that requires a value. We " "even changed the name of the option to match that idea. Note that we now " "specify a new keyword, ``action``, and give it the value ``\"store_true\"``. " "This means that, if the option is specified, assign the value ``True`` to :" "data:`args.verbose`. Not specifying it implies ``False``." msgstr "" #: ../Doc/howto/argparse.rst:305 msgid "" "It complains when you specify a value, in true spirit of what flags actually " "are." msgstr "" #: ../Doc/howto/argparse.rst:308 msgid "Notice the different help text." msgstr "" #: ../Doc/howto/argparse.rst:312 msgid "Short options" msgstr "" #: ../Doc/howto/argparse.rst:314 msgid "" "If you are familiar with command line usage, you will notice that I haven't " "yet touched on the topic of short versions of the options. It's quite " "simple::" msgstr "" #: ../Doc/howto/argparse.rst:326 msgid "And here goes:" msgstr "" #: ../Doc/howto/argparse.rst:339 msgid "Note that the new ability is also reflected in the help text." msgstr "" #: ../Doc/howto/argparse.rst:343 msgid "Combining Positional and Optional arguments" msgstr "" #: ../Doc/howto/argparse.rst:345 msgid "Our program keeps growing in complexity::" msgstr "" #: ../Doc/howto/argparse.rst:360 msgid "And now the output:" msgstr "" #: ../Doc/howto/argparse.rst:374 msgid "We've brought back a positional argument, hence the complaint." msgstr "" #: ../Doc/howto/argparse.rst:376 msgid "Note that the order does not matter." msgstr "" #: ../Doc/howto/argparse.rst:378 msgid "" "How about we give this program of ours back the ability to have multiple " "verbosity values, and actually get to use them::" msgstr "" #: ../Doc/howto/argparse.rst:412 msgid "" "These all look good except the last one, which exposes a bug in our program. " "Let's fix it by restricting the values the ``--verbosity`` option can " "accept::" msgstr "" #: ../Doc/howto/argparse.rst:448 msgid "" "Note that the change also reflects both in the error message as well as the " "help string." msgstr "" #: ../Doc/howto/argparse.rst:451 msgid "" "Now, let's use a different approach of playing with verbosity, which is " "pretty common. It also matches the way the CPython executable handles its " "own verbosity argument (check the output of ``python --help``)::" msgstr "" #: ../Doc/howto/argparse.rst:470 msgid "" "We have introduced another action, \"count\", to count the number of " "occurrences of a specific optional arguments:" msgstr "" #: ../Doc/howto/argparse.rst:498 msgid "" "Yes, it's now more of a flag (similar to ``action=\"store_true\"``) in the " "previous version of our script. That should explain the complaint." msgstr "" #: ../Doc/howto/argparse.rst:501 msgid "It also behaves similar to \"store_true\" action." msgstr "" #: ../Doc/howto/argparse.rst:503 msgid "" "Now here's a demonstration of what the \"count\" action gives. You've " "probably seen this sort of usage before." msgstr "" #: ../Doc/howto/argparse.rst:506 msgid "" "And if you don't specify the ``-v`` flag, that flag is considered to have " "``None`` value." msgstr "" #: ../Doc/howto/argparse.rst:509 msgid "" "As should be expected, specifying the long form of the flag, we should get " "the same output." msgstr "" #: ../Doc/howto/argparse.rst:512 msgid "" "Sadly, our help output isn't very informative on the new ability our script " "has acquired, but that can always be fixed by improving the documentation " "for our script (e.g. via the ``help`` keyword argument)." msgstr "" #: ../Doc/howto/argparse.rst:516 msgid "That last output exposes a bug in our program." msgstr "" #: ../Doc/howto/argparse.rst:519 msgid "Let's fix::" msgstr "" #: ../Doc/howto/argparse.rst:538 msgid "And this is what it gives:" msgstr "" #: ../Doc/howto/argparse.rst:553 msgid "" "First output went well, and fixes the bug we had before. That is, we want " "any value >= 2 to be as verbose as possible." msgstr "" #: ../Doc/howto/argparse.rst:556 msgid "Third output not so good." msgstr "" #: ../Doc/howto/argparse.rst:558 msgid "Let's fix that bug::" msgstr "" #: ../Doc/howto/argparse.rst:575 msgid "" "We've just introduced yet another keyword, ``default``. We've set it to " "``0`` in order to make it comparable to the other int values. Remember that " "by default, if an optional argument isn't specified, it gets the ``None`` " "value, and that cannot be compared to an int value (hence the :exc:" "`TypeError` exception)." msgstr "" #: ../Doc/howto/argparse.rst:582 msgid "And:" msgstr "" #: ../Doc/howto/argparse.rst:589 msgid "" "You can go quite far just with what we've learned so far, and we have only " "scratched the surface. The :mod:`argparse` module is very powerful, and " "we'll explore a bit more of it before we end this tutorial." msgstr "" #: ../Doc/howto/argparse.rst:596 msgid "Getting a little more advanced" msgstr "" #: ../Doc/howto/argparse.rst:598 msgid "" "What if we wanted to expand our tiny program to perform other powers, not " "just squares::" msgstr "" #: ../Doc/howto/argparse.rst:615 ../Doc/howto/argparse.rst:653 msgid "Output:" msgstr "Sortie :" #: ../Doc/howto/argparse.rst:636 msgid "" "Notice that so far we've been using verbosity level to *change* the text " "that gets displayed. The following example instead uses verbosity level to " "display *more* text instead::" msgstr "" #: ../Doc/howto/argparse.rst:667 msgid "Conflicting options" msgstr "" #: ../Doc/howto/argparse.rst:669 msgid "" "So far, we have been working with two methods of an :class:`argparse." "ArgumentParser` instance. Let's introduce a third one, :meth:" "`add_mutually_exclusive_group`. It allows for us to specify options that " "conflict with each other. Let's also change the rest of the program so that " "the new functionality makes more sense: we'll introduce the ``--quiet`` " "option, which will be the opposite of the ``--verbose`` one::" msgstr "" #: ../Doc/howto/argparse.rst:695 msgid "" "Our program is now simpler, and we've lost some functionality for the sake " "of demonstration. Anyways, here's the output:" msgstr "" #: ../Doc/howto/argparse.rst:713 msgid "" "That should be easy to follow. I've added that last output so you can see " "the sort of flexibility you get, i.e. mixing long form options with short " "form ones." msgstr "" #: ../Doc/howto/argparse.rst:717 msgid "" "Before we conclude, you probably want to tell your users the main purpose of " "your program, just in case they don't know::" msgstr "" #: ../Doc/howto/argparse.rst:738 msgid "" "Note that slight difference in the usage text. Note the ``[-v | -q]``, which " "tells us that we can either use ``-v`` or ``-q``, but not both at the same " "time:" msgstr "" #: ../Doc/howto/argparse.rst:760 msgid "Conclusion" msgstr "" #: ../Doc/howto/argparse.rst:762 msgid "" "The :mod:`argparse` module offers a lot more than shown here. Its docs are " "quite detailed and thorough, and full of examples. Having gone through this " "tutorial, you should easily digest them without feeling overwhelmed." msgstr "" #: ../Doc/howto/clinic.rst:3 msgid "Argument Clinic How-To" msgstr "" #: ../Doc/howto/clinic.rst:5 msgid "Larry Hastings" msgstr "" #: ../Doc/howto/clinic.rst:0 ../Doc/howto/cporting.rst:0 #: ../Doc/howto/curses.rst:0 ../Doc/howto/descriptor.rst:11 #: ../Doc/howto/pyporting.rst:0 ../Doc/howto/regex.rst:0 #: ../Doc/howto/sockets.rst:0 msgid "Abstract" msgstr "Résumé" #: ../Doc/howto/clinic.rst:10 msgid "" "Argument Clinic is a preprocessor for CPython C files. Its purpose is to " "automate all the boilerplate involved with writing argument parsing code for " "\"builtins\". This document shows you how to convert your first C function " "to work with Argument Clinic, and then introduces some advanced topics on " "Argument Clinic usage." msgstr "" #: ../Doc/howto/clinic.rst:17 msgid "" "Currently Argument Clinic is considered internal-only for CPython. Its use " "is not supported for files outside CPython, and no guarantees are made " "regarding backwards compatibility for future versions. In other words: if " "you maintain an external C extension for CPython, you're welcome to " "experiment with Argument Clinic in your own code. But the version of " "Argument Clinic that ships with CPython 3.5 *could* be totally incompatible " "and break all your code." msgstr "" #: ../Doc/howto/clinic.rst:27 msgid "The Goals Of Argument Clinic" msgstr "" #: ../Doc/howto/clinic.rst:29 msgid "" "Argument Clinic's primary goal is to take over responsibility for all " "argument parsing code inside CPython. This means that, when you convert a " "function to work with Argument Clinic, that function should no longer do any " "of its own argument parsing--the code generated by Argument Clinic should be " "a \"black box\" to you, where CPython calls in at the top, and your code " "gets called at the bottom, with ``PyObject *args`` (and maybe ``PyObject " "*kwargs``) magically converted into the C variables and types you need." msgstr "" #: ../Doc/howto/clinic.rst:39 msgid "" "In order for Argument Clinic to accomplish its primary goal, it must be easy " "to use. Currently, working with CPython's argument parsing library is a " "chore, requiring maintaining redundant information in a surprising number of " "places. When you use Argument Clinic, you don't have to repeat yourself." msgstr "" #: ../Doc/howto/clinic.rst:45 msgid "" "Obviously, no one would want to use Argument Clinic unless it's solving " "their problem--and without creating new problems of its own. So it's " "paramount that Argument Clinic generate correct code. It'd be nice if the " "code was faster, too, but at the very least it should not introduce a major " "speed regression. (Eventually Argument Clinic *should* make a major speedup " "possible--we could rewrite its code generator to produce tailor-made " "argument parsing code, rather than calling the general-purpose CPython " "argument parsing library. That would make for the fastest argument parsing " "possible!)" msgstr "" #: ../Doc/howto/clinic.rst:57 msgid "" "Additionally, Argument Clinic must be flexible enough to work with any " "approach to argument parsing. Python has some functions with some very " "strange parsing behaviors; Argument Clinic's goal is to support all of them." msgstr "" #: ../Doc/howto/clinic.rst:62 msgid "" "Finally, the original motivation for Argument Clinic was to provide " "introspection \"signatures\" for CPython builtins. It used to be, the " "introspection query functions would throw an exception if you passed in a " "builtin. With Argument Clinic, that's a thing of the past!" msgstr "" #: ../Doc/howto/clinic.rst:68 msgid "" "One idea you should keep in mind, as you work with Argument Clinic: the more " "information you give it, the better job it'll be able to do. Argument Clinic " "is admittedly relatively simple right now. But as it evolves it will get " "more sophisticated, and it should be able to do many interesting and smart " "things with all the information you give it." msgstr "" #: ../Doc/howto/clinic.rst:78 msgid "Basic Concepts And Usage" msgstr "" #: ../Doc/howto/clinic.rst:80 msgid "" "Argument Clinic ships with CPython; you'll find it in ``Tools/clinic/clinic." "py``. If you run that script, specifying a C file as an argument::" msgstr "" #: ../Doc/howto/clinic.rst:85 msgid "" "Argument Clinic will scan over the file looking for lines that look exactly " "like this::" msgstr "" #: ../Doc/howto/clinic.rst:90 msgid "" "When it finds one, it reads everything up to a line that looks exactly like " "this::" msgstr "" #: ../Doc/howto/clinic.rst:95 msgid "" "Everything in between these two lines is input for Argument Clinic. All of " "these lines, including the beginning and ending comment lines, are " "collectively called an Argument Clinic \"block\"." msgstr "" #: ../Doc/howto/clinic.rst:99 msgid "" "When Argument Clinic parses one of these blocks, it generates output. This " "output is rewritten into the C file immediately after the block, followed by " "a comment containing a checksum. The Argument Clinic block now looks like " "this::" msgstr "" #: ../Doc/howto/clinic.rst:110 msgid "" "If you run Argument Clinic on the same file a second time, Argument Clinic " "will discard the old output and write out the new output with a fresh " "checksum line. However, if the input hasn't changed, the output won't " "change either." msgstr "" #: ../Doc/howto/clinic.rst:114 msgid "" "You should never modify the output portion of an Argument Clinic block. " "Instead, change the input until it produces the output you want. (That's " "the purpose of the checksum--to detect if someone changed the output, as " "these edits would be lost the next time Argument Clinic writes out fresh " "output.)" msgstr "" #: ../Doc/howto/clinic.rst:119 msgid "" "For the sake of clarity, here's the terminology we'll use with Argument " "Clinic:" msgstr "" #: ../Doc/howto/clinic.rst:121 msgid "" "The first line of the comment (``/*[clinic input]``) is the *start line*." msgstr "" #: ../Doc/howto/clinic.rst:122 msgid "" "The last line of the initial comment (``[clinic start generated code]*/``) " "is the *end line*." msgstr "" #: ../Doc/howto/clinic.rst:123 msgid "" "The last line (``/*[clinic end generated code: checksum=...]*/``) is the " "*checksum line*." msgstr "" #: ../Doc/howto/clinic.rst:124 msgid "In between the start line and the end line is the *input*." msgstr "" #: ../Doc/howto/clinic.rst:125 msgid "In between the end line and the checksum line is the *output*." msgstr "" #: ../Doc/howto/clinic.rst:126 msgid "" "All the text collectively, from the start line to the checksum line " "inclusively, is the *block*. (A block that hasn't been successfully " "processed by Argument Clinic yet doesn't have output or a checksum line, but " "it's still considered a block.)" msgstr "" #: ../Doc/howto/clinic.rst:133 msgid "Converting Your First Function" msgstr "" #: ../Doc/howto/clinic.rst:135 msgid "" "The best way to get a sense of how Argument Clinic works is to convert a " "function to work with it. Here, then, are the bare minimum steps you'd need " "to follow to convert a function to work with Argument Clinic. Note that for " "code you plan to check in to CPython, you really should take the conversion " "farther, using some of the advanced concepts you'll see later on in the " "document (like \"return converters\" and \"self converters\"). But we'll " "keep it simple for this walkthrough so you can learn." msgstr "" #: ../Doc/howto/clinic.rst:144 msgid "Let's dive in!" msgstr "" #: ../Doc/howto/clinic.rst:146 msgid "" "Make sure you're working with a freshly updated checkout of the CPython " "trunk." msgstr "" #: ../Doc/howto/clinic.rst:149 msgid "" "Find a Python builtin that calls either :c:func:`PyArg_ParseTuple` or :c:" "func:`PyArg_ParseTupleAndKeywords`, and hasn't been converted to work with " "Argument Clinic yet. For my example I'm using ``_pickle.Pickler.dump()``." msgstr "" #: ../Doc/howto/clinic.rst:154 msgid "" "If the call to the ``PyArg_Parse`` function uses any of the following format " "units:" msgstr "" #: ../Doc/howto/clinic.rst:166 msgid "" "or if it has multiple calls to :c:func:`PyArg_ParseTuple`, you should choose " "a different function. Argument Clinic *does* support all of these " "scenarios. But these are advanced topics--let's do something simpler for " "your first function." msgstr "" #: ../Doc/howto/clinic.rst:171 msgid "" "Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple` or :c:" "func:`PyArg_ParseTupleAndKeywords` where it supports different types for the " "same argument, or if the function uses something besides PyArg_Parse " "functions to parse its arguments, it probably isn't suitable for conversion " "to Argument Clinic. Argument Clinic doesn't support generic functions or " "polymorphic parameters." msgstr "" #: ../Doc/howto/clinic.rst:178 msgid "Add the following boilerplate above the function, creating our block::" msgstr "" #: ../Doc/howto/clinic.rst:183 msgid "" "Cut the docstring and paste it in between the ``[clinic]`` lines, removing " "all the junk that makes it a properly quoted C string. When you're done you " "should have just the text, based at the left margin, with no line wider than " "80 characters. (Argument Clinic will preserve indents inside the docstring.)" msgstr "" #: ../Doc/howto/clinic.rst:189 msgid "" "If the old docstring had a first line that looked like a function signature, " "throw that line away. (The docstring doesn't need it anymore--when you use " "``help()`` on your builtin in the future, the first line will be built " "automatically based on the function's signature.)" msgstr "" #: ../Doc/howto/clinic.rst:195 ../Doc/howto/clinic.rst:216 #: ../Doc/howto/clinic.rst:240 ../Doc/howto/clinic.rst:294 #: ../Doc/howto/clinic.rst:334 ../Doc/howto/clinic.rst:361 #: ../Doc/howto/clinic.rst:470 ../Doc/howto/clinic.rst:522 msgid "Sample::" msgstr "" #: ../Doc/howto/clinic.rst:201 msgid "" "If your docstring doesn't have a \"summary\" line, Argument Clinic will " "complain. So let's make sure it has one. The \"summary\" line should be a " "paragraph consisting of a single 80-column line at the beginning of the " "docstring." msgstr "" #: ../Doc/howto/clinic.rst:206 msgid "" "(Our example docstring consists solely of a summary line, so the sample code " "doesn't have to change for this step.)" msgstr "" #: ../Doc/howto/clinic.rst:209 msgid "" "Above the docstring, enter the name of the function, followed by a blank " "line. This should be the Python name of the function, and should be the " "full dotted path to the function--it should start with the name of the " "module, include any sub-modules, and if the function is a method on a class " "it should include the class name too." msgstr "" #: ../Doc/howto/clinic.rst:224 msgid "" "If this is the first time that module or class has been used with Argument " "Clinic in this C file, you must declare the module and/or class. Proper " "Argument Clinic hygiene prefers declaring these in a separate block " "somewhere near the top of the C file, in the same way that include files and " "statics go at the top. (In our sample code we'll just show the two blocks " "next to each other.)" msgstr "" #: ../Doc/howto/clinic.rst:232 msgid "" "The name of the class and module should be the same as the one seen by " "Python. Check the name defined in the :c:type:`PyModuleDef` or :c:type:" "`PyTypeObject` as appropriate." msgstr "" #: ../Doc/howto/clinic.rst:236 msgid "" "When you declare a class, you must also specify two aspects of its type in " "C: the type declaration you'd use for a pointer to an instance of this " "class, and a pointer to the :c:type:`PyTypeObject` for this class." msgstr "" #: ../Doc/howto/clinic.rst:256 msgid "" "Declare each of the parameters to the function. Each parameter should get " "its own line. All the parameter lines should be indented from the function " "name and the docstring." msgstr "" #: ../Doc/howto/clinic.rst:260 msgid "The general form of these parameter lines is as follows::" msgstr "" #: ../Doc/howto/clinic.rst:264 msgid "If the parameter has a default value, add that after the converter::" msgstr "" #: ../Doc/howto/clinic.rst:269 msgid "" "Argument Clinic's support for \"default values\" is quite sophisticated; " "please see :ref:`the section below on default values ` for " "more information." msgstr "" #: ../Doc/howto/clinic.rst:273 msgid "Add a blank line below the parameters." msgstr "" #: ../Doc/howto/clinic.rst:275 msgid "" "What's a \"converter\"? It establishes both the type of the variable used " "in C, and the method to convert the Python value into a C value at runtime. " "For now you're going to use what's called a \"legacy converter\"--a " "convenience syntax intended to make porting old code into Argument Clinic " "easier." msgstr "" #: ../Doc/howto/clinic.rst:282 msgid "" "For each parameter, copy the \"format unit\" for that parameter from the " "``PyArg_Parse()`` format argument and specify *that* as its converter, as a " "quoted string. (\"format unit\" is the formal name for the one-to-three " "character substring of the ``format`` parameter that tells the argument " "parsing function what the type of the variable is and how to convert it. " "For more on format units please see :ref:`arg-parsing`.)" msgstr "" #: ../Doc/howto/clinic.rst:291 msgid "" "For multicharacter format units like ``z#``, use the entire two-or-three " "character string." msgstr "" #: ../Doc/howto/clinic.rst:309 msgid "" "If your function has ``|`` in the format string, meaning some parameters " "have default values, you can ignore it. Argument Clinic infers which " "parameters are optional based on whether or not they have default values." msgstr "" #: ../Doc/howto/clinic.rst:314 msgid "" "If your function has ``$`` in the format string, meaning it takes keyword-" "only arguments, specify ``*`` on a line by itself before the first keyword-" "only argument, indented the same as the parameter lines." msgstr "" #: ../Doc/howto/clinic.rst:319 msgid "(``_pickle.Pickler.dump`` has neither, so our sample is unchanged.)" msgstr "" #: ../Doc/howto/clinic.rst:322 msgid "" "If the existing C function calls :c:func:`PyArg_ParseTuple` (as opposed to :" "c:func:`PyArg_ParseTupleAndKeywords`), then all its arguments are positional-" "only." msgstr "" #: ../Doc/howto/clinic.rst:326 msgid "" "To mark all parameters as positional-only in Argument Clinic, add a ``/`` on " "a line by itself after the last parameter, indented the same as the " "parameter lines." msgstr "" #: ../Doc/howto/clinic.rst:330 msgid "" "Currently this is all-or-nothing; either all parameters are positional-only, " "or none of them are. (In the future Argument Clinic may relax this " "restriction.)" msgstr "" #: ../Doc/howto/clinic.rst:350 msgid "" "It's helpful to write a per-parameter docstring for each parameter. But per-" "parameter docstrings are optional; you can skip this step if you prefer." msgstr "" #: ../Doc/howto/clinic.rst:354 msgid "" "Here's how to add a per-parameter docstring. The first line of the per-" "parameter docstring must be indented further than the parameter definition. " "The left margin of this first line establishes the left margin for the whole " "per-parameter docstring; all the text you write will be outdented by this " "amount. You can write as much text as you like, across multiple lines if " "you wish." msgstr "" #: ../Doc/howto/clinic.rst:378 msgid "" "Save and close the file, then run ``Tools/clinic/clinic.py`` on it. With " "luck everything worked and your block now has output! Reopen the file in " "your text editor to see::" msgstr "" #: ../Doc/howto/clinic.rst:406 msgid "" "Obviously, if Argument Clinic didn't produce any output, it's because it " "found an error in your input. Keep fixing your errors and retrying until " "Argument Clinic processes your file without complaint." msgstr "" #: ../Doc/howto/clinic.rst:410 msgid "" "Double-check that the argument-parsing code Argument Clinic generated looks " "basically the same as the existing code." msgstr "" #: ../Doc/howto/clinic.rst:413 msgid "" "First, ensure both places use the same argument-parsing function. The " "existing code must call either :c:func:`PyArg_ParseTuple` or :c:func:" "`PyArg_ParseTupleAndKeywords`; ensure that the code generated by Argument " "Clinic calls the *exact* same function." msgstr "" #: ../Doc/howto/clinic.rst:419 msgid "" "Second, the format string passed in to :c:func:`PyArg_ParseTuple` or :c:func:" "`PyArg_ParseTupleAndKeywords` should be *exactly* the same as the hand-" "written one in the existing function, up to the colon or semi-colon." msgstr "" #: ../Doc/howto/clinic.rst:424 msgid "" "(Argument Clinic always generates its format strings with a ``:`` followed " "by the name of the function. If the existing code's format string ends with " "``;``, to provide usage help, this change is harmless--don't worry about it.)" msgstr "" #: ../Doc/howto/clinic.rst:429 msgid "" "Third, for parameters whose format units require two arguments (like a " "length variable, or an encoding string, or a pointer to a conversion " "function), ensure that the second argument is *exactly* the same between the " "two invocations." msgstr "" #: ../Doc/howto/clinic.rst:434 msgid "" "Fourth, inside the output portion of the block you'll find a preprocessor " "macro defining the appropriate static :c:type:`PyMethodDef` structure for " "this builtin::" msgstr "" #: ../Doc/howto/clinic.rst:441 msgid "" "This static structure should be *exactly* the same as the existing static :c:" "type:`PyMethodDef` structure for this builtin." msgstr "" #: ../Doc/howto/clinic.rst:444 msgid "" "If any of these items differ in *any way*, adjust your Argument Clinic " "function specification and rerun ``Tools/clinic/clinic.py`` until they *are* " "the same." msgstr "" #: ../Doc/howto/clinic.rst:449 msgid "" "Notice that the last line of its output is the declaration of your \"impl\" " "function. This is where the builtin's implementation goes. Delete the " "existing prototype of the function you're modifying, but leave the opening " "curly brace. Now delete its argument parsing code and the declarations of " "all the variables it dumps the arguments into. Notice how the Python " "arguments are now arguments to this impl function; if the implementation " "used different names for these variables, fix it." msgstr "" #: ../Doc/howto/clinic.rst:457 msgid "" "Let's reiterate, just because it's kind of weird. Your code should now look " "like this::" msgstr "" #: ../Doc/howto/clinic.rst:466 msgid "" "Argument Clinic generated the checksum line and the function prototype just " "above it. You should write the opening (and closing) curly braces for the " "function, and the implementation inside." msgstr "" #: ../Doc/howto/clinic.rst:511 msgid "" "Remember the macro with the :c:type:`PyMethodDef` structure for this " "function? Find the existing :c:type:`PyMethodDef` structure for this " "function and replace it with a reference to the macro. (If the builtin is " "at module scope, this will probably be very near the end of the file; if the " "builtin is a class method, this will probably be below but relatively near " "to the implementation.)" msgstr "" #: ../Doc/howto/clinic.rst:518 msgid "" "Note that the body of the macro contains a trailing comma. So when you " "replace the existing static :c:type:`PyMethodDef` structure with the macro, " "*don't* add a comma to the end." msgstr "" #: ../Doc/howto/clinic.rst:531 msgid "" "Compile, then run the relevant portions of the regression-test suite. This " "change should not introduce any new compile-time warnings or errors, and " "there should be no externally-visible change to Python's behavior." msgstr "" #: ../Doc/howto/clinic.rst:535 msgid "" "Well, except for one difference: ``inspect.signature()`` run on your " "function should now provide a valid signature!" msgstr "" #: ../Doc/howto/clinic.rst:538 msgid "" "Congratulations, you've ported your first function to work with Argument " "Clinic!" msgstr "" #: ../Doc/howto/clinic.rst:541 msgid "Advanced Topics" msgstr "" #: ../Doc/howto/clinic.rst:543 msgid "" "Now that you've had some experience working with Argument Clinic, it's time " "for some advanced topics." msgstr "" #: ../Doc/howto/clinic.rst:548 msgid "Symbolic default values" msgstr "" #: ../Doc/howto/clinic.rst:550 msgid "" "The default value you provide for a parameter can't be any arbitrary " "expression. Currently the following are explicitly supported:" msgstr "" #: ../Doc/howto/clinic.rst:553 msgid "Numeric constants (integer and float)" msgstr "" #: ../Doc/howto/clinic.rst:554 msgid "String constants" msgstr "Chaînes constantes" #: ../Doc/howto/clinic.rst:555 msgid "``True``, ``False``, and ``None``" msgstr "" #: ../Doc/howto/clinic.rst:556 msgid "" "Simple symbolic constants like ``sys.maxsize``, which must start with the " "name of the module" msgstr "" #: ../Doc/howto/clinic.rst:559 msgid "" "In case you're curious, this is implemented in ``from_builtin()`` in ``Lib/" "inspect.py``." msgstr "" #: ../Doc/howto/clinic.rst:562 msgid "" "(In the future, this may need to get even more elaborate, to allow full " "expressions like ``CONSTANT - 1``.)" msgstr "" #: ../Doc/howto/clinic.rst:567 msgid "Renaming the C functions and variables generated by Argument Clinic" msgstr "" #: ../Doc/howto/clinic.rst:569 msgid "" "Argument Clinic automatically names the functions it generates for you. " "Occasionally this may cause a problem, if the generated name collides with " "the name of an existing C function. There's an easy solution: override the " "names used for the C functions. Just add the keyword ``\"as\"`` to your " "function declaration line, followed by the function name you wish to use. " "Argument Clinic will use that function name for the base (generated) " "function, then add ``\"_impl\"`` to the end and use that for the name of the " "impl function." msgstr "" #: ../Doc/howto/clinic.rst:577 msgid "" "For example, if we wanted to rename the C function names generated for " "``pickle.Pickler.dump``, it'd look like this::" msgstr "" #: ../Doc/howto/clinic.rst:585 msgid "" "The base function would now be named ``pickler_dumper()``, and the impl " "function would now be named ``pickler_dumper_impl()``." msgstr "" #: ../Doc/howto/clinic.rst:589 msgid "" "Similarly, you may have a problem where you want to give a parameter a " "specific Python name, but that name may be inconvenient in C. Argument " "Clinic allows you to give a parameter different names in Python and in C, " "using the same ``\"as\"`` syntax::" msgstr "" #: ../Doc/howto/clinic.rst:603 msgid "" "Here, the name used in Python (in the signature and the ``keywords`` array) " "would be ``file``, but the C variable would be named ``file_obj``." msgstr "" #: ../Doc/howto/clinic.rst:606 msgid "You can use this to rename the ``self`` parameter too!" msgstr "" #: ../Doc/howto/clinic.rst:610 msgid "Converting functions using PyArg_UnpackTuple" msgstr "" #: ../Doc/howto/clinic.rst:612 msgid "" "To convert a function parsing its arguments with :c:func:" "`PyArg_UnpackTuple`, simply write out all the arguments, specifying each as " "an ``object``. You may specify the ``type`` argument to cast the type as " "appropriate. All arguments should be marked positional-only (add a ``/`` on " "a line by itself after the last argument)." msgstr "" #: ../Doc/howto/clinic.rst:618 msgid "" "Currently the generated code will use :c:func:`PyArg_ParseTuple`, but this " "will change soon." msgstr "" #: ../Doc/howto/clinic.rst:622 msgid "Optional Groups" msgstr "" #: ../Doc/howto/clinic.rst:624 msgid "" "Some legacy functions have a tricky approach to parsing their arguments: " "they count the number of positional arguments, then use a ``switch`` " "statement to call one of several different :c:func:`PyArg_ParseTuple` calls " "depending on how many positional arguments there are. (These functions " "cannot accept keyword-only arguments.) This approach was used to simulate " "optional arguments back before :c:func:`PyArg_ParseTupleAndKeywords` was " "created." msgstr "" #: ../Doc/howto/clinic.rst:631 msgid "" "While functions using this approach can often be converted to use :c:func:" "`PyArg_ParseTupleAndKeywords`, optional arguments, and default values, it's " "not always possible. Some of these legacy functions have behaviors :c:func:" "`PyArg_ParseTupleAndKeywords` doesn't directly support. The most obvious " "example is the builtin function ``range()``, which has an optional argument " "on the *left* side of its required argument! Another example is ``curses." "window.addch()``, which has a group of two arguments that must always be " "specified together. (The arguments are called ``x`` and ``y``; if you call " "the function passing in ``x``, you must also pass in ``y``--and if you don't " "pass in ``x`` you may not pass in ``y`` either.)" msgstr "" #: ../Doc/howto/clinic.rst:643 msgid "" "In any case, the goal of Argument Clinic is to support argument parsing for " "all existing CPython builtins without changing their semantics. Therefore " "Argument Clinic supports this alternate approach to parsing, using what are " "called *optional groups*. Optional groups are groups of arguments that must " "all be passed in together. They can be to the left or the right of the " "required arguments. They can *only* be used with positional-only parameters." msgstr "" #: ../Doc/howto/clinic.rst:651 msgid "" "Optional groups are *only* intended for use when converting functions that " "make multiple calls to :c:func:`PyArg_ParseTuple`! Functions that use *any* " "other approach for parsing arguments should *almost never* be converted to " "Argument Clinic using optional groups. Functions using optional groups " "currently cannot have accurate signatures in Python, because Python just " "doesn't understand the concept. Please avoid using optional groups wherever " "possible." msgstr "" #: ../Doc/howto/clinic.rst:660 msgid "" "To specify an optional group, add a ``[`` on a line by itself before the " "parameters you wish to group together, and a ``]`` on a line by itself after " "these parameters. As an example, here's how ``curses.window.addch`` uses " "optional groups to make the first two parameters and the last parameter " "optional::" msgstr "" #: ../Doc/howto/clinic.rst:689 msgid "Notes:" msgstr "Notes : " #: ../Doc/howto/clinic.rst:691 msgid "" "For every optional group, one additional parameter will be passed into the " "impl function representing the group. The parameter will be an int named " "``group_{direction}_{number}``, where ``{direction}`` is either ``right`` or " "``left`` depending on whether the group is before or after the required " "parameters, and ``{number}`` is a monotonically increasing number (starting " "at 1) indicating how far away the group is from the required parameters. " "When the impl is called, this parameter will be set to zero if this group " "was unused, and set to non-zero if this group was used. (By used or unused, " "I mean whether or not the parameters received arguments in this invocation.)" msgstr "" #: ../Doc/howto/clinic.rst:702 msgid "" "If there are no required arguments, the optional groups will behave as if " "they're to the right of the required arguments." msgstr "" #: ../Doc/howto/clinic.rst:705 msgid "" "In the case of ambiguity, the argument parsing code favors parameters on the " "left (before the required parameters)." msgstr "" #: ../Doc/howto/clinic.rst:708 msgid "Optional groups can only contain positional-only parameters." msgstr "" #: ../Doc/howto/clinic.rst:710 msgid "" "Optional groups are *only* intended for legacy code. Please do not use " "optional groups for new code." msgstr "" #: ../Doc/howto/clinic.rst:715 msgid "Using real Argument Clinic converters, instead of \"legacy converters\"" msgstr "" #: ../Doc/howto/clinic.rst:717 msgid "" "To save time, and to minimize how much you need to learn to achieve your " "first port to Argument Clinic, the walkthrough above tells you to use " "\"legacy converters\". \"Legacy converters\" are a convenience, designed " "explicitly to make porting existing code to Argument Clinic easier. And to " "be clear, their use is acceptable when porting code for Python 3.4." msgstr "" #: ../Doc/howto/clinic.rst:724 msgid "" "However, in the long term we probably want all our blocks to use Argument " "Clinic's real syntax for converters. Why? A couple reasons:" msgstr "" #: ../Doc/howto/clinic.rst:728 msgid "" "The proper converters are far easier to read and clearer in their intent." msgstr "" #: ../Doc/howto/clinic.rst:729 msgid "" "There are some format units that are unsupported as \"legacy converters\", " "because they require arguments, and the legacy converter syntax doesn't " "support specifying arguments." msgstr "" #: ../Doc/howto/clinic.rst:732 msgid "" "In the future we may have a new argument parsing library that isn't " "restricted to what :c:func:`PyArg_ParseTuple` supports; this flexibility " "won't be available to parameters using legacy converters." msgstr "" #: ../Doc/howto/clinic.rst:736 msgid "" "Therefore, if you don't mind a little extra effort, please use the normal " "converters instead of legacy converters." msgstr "" #: ../Doc/howto/clinic.rst:739 msgid "" "In a nutshell, the syntax for Argument Clinic (non-legacy) converters looks " "like a Python function call. However, if there are no explicit arguments to " "the function (all functions take their default values), you may omit the " "parentheses. Thus ``bool`` and ``bool()`` are exactly the same converters." msgstr "" #: ../Doc/howto/clinic.rst:745 msgid "" "All arguments to Argument Clinic converters are keyword-only. All Argument " "Clinic converters accept the following arguments:" msgstr "" #: ../Doc/howto/clinic.rst:753 ../Doc/howto/clinic.rst:1223 msgid "``c_default``" msgstr "" #: ../Doc/howto/clinic.rst:749 msgid "" "The default value for this parameter when defined in C. Specifically, this " "will be the initializer for the variable declared in the \"parse function" "\". See :ref:`the section on default values ` for how to " "use this. Specified as a string." msgstr "" #: ../Doc/howto/clinic.rst:758 msgid "``annotation``" msgstr "" #: ../Doc/howto/clinic.rst:756 msgid "" "The annotation value for this parameter. Not currently supported, because " "PEP 8 mandates that the Python library may not use annotations." msgstr "" #: ../Doc/howto/clinic.rst:760 msgid "" "In addition, some converters accept additional arguments. Here is a list of " "these arguments, along with their meanings:" msgstr "" #: ../Doc/howto/clinic.rst:769 msgid "``accept``" msgstr "" #: ../Doc/howto/clinic.rst:764 msgid "" "A set of Python types (and possibly pseudo-types); this restricts the " "allowable Python argument to values of these types. (This is not a general-" "purpose facility; as a rule it only supports specific lists of types as " "shown in the legacy converter table.)" msgstr "" #: ../Doc/howto/clinic.rst:769 msgid "To accept ``None``, add ``NoneType`` to this set." msgstr "" #: ../Doc/howto/clinic.rst:774 msgid "``bitwise``" msgstr "" #: ../Doc/howto/clinic.rst:772 msgid "" "Only supported for unsigned integers. The native integer value of this " "Python argument will be written to the parameter without any range checking, " "even for negative values." msgstr "" #: ../Doc/howto/clinic.rst:779 ../Doc/howto/clinic.rst:1237 msgid "``converter``" msgstr "" #: ../Doc/howto/clinic.rst:777 msgid "" "Only supported by the ``object`` converter. Specifies the name of a :ref:`C " "\"converter function\" ` to use to convert this object to a " "native type." msgstr "" #: ../Doc/howto/clinic.rst:784 msgid "``encoding``" msgstr "" #: ../Doc/howto/clinic.rst:782 msgid "" "Only supported for strings. Specifies the encoding to use when converting " "this string from a Python str (Unicode) value into a C ``char *`` value." msgstr "" #: ../Doc/howto/clinic.rst:788 msgid "``subclass_of``" msgstr "" #: ../Doc/howto/clinic.rst:787 msgid "" "Only supported for the ``object`` converter. Requires that the Python value " "be a subclass of a Python type, as expressed in C." msgstr "" #: ../Doc/howto/clinic.rst:793 ../Doc/howto/clinic.rst:1209 msgid "``type``" msgstr "``type``" #: ../Doc/howto/clinic.rst:791 msgid "" "Only supported for the ``object`` and ``self`` converters. Specifies the C " "type that will be used to declare the variable. Default value is ``" "\"PyObject *\"``." msgstr "" #: ../Doc/howto/clinic.rst:799 msgid "``zeroes``" msgstr "" #: ../Doc/howto/clinic.rst:796 msgid "" "Only supported for strings. If true, embedded NUL bytes (``'\\\\0'``) are " "permitted inside the value. The length of the string will be passed in to " "the impl function, just after the string parameter, as a parameter named " "``_length``." msgstr "" #: ../Doc/howto/clinic.rst:801 msgid "" "Please note, not every possible combination of arguments will work. Usually " "these arguments are implemented by specific ``PyArg_ParseTuple`` *format " "units*, with specific behavior. For example, currently you cannot call " "``unsigned_short`` without also specifying ``bitwise=True``. Although it's " "perfectly reasonable to think this would work, these semantics don't map to " "any existing format unit. So Argument Clinic doesn't support it. (Or, at " "least, not yet.)" msgstr "" #: ../Doc/howto/clinic.rst:809 msgid "" "Below is a table showing the mapping of legacy converters into real Argument " "Clinic converters. On the left is the legacy converter, on the right is the " "text you'd replace it with." msgstr "" #: ../Doc/howto/clinic.rst:814 msgid "``'B'``" msgstr "``'B'``" #: ../Doc/howto/clinic.rst:814 msgid "``unsigned_char(bitwise=True)``" msgstr "" #: ../Doc/howto/clinic.rst:815 msgid "``'b'``" msgstr "``'b'``" #: ../Doc/howto/clinic.rst:815 msgid "``unsigned_char``" msgstr "" #: ../Doc/howto/clinic.rst:816 msgid "``'c'``" msgstr "``'c'``" #: ../Doc/howto/clinic.rst:816 msgid "``char``" msgstr "" #: ../Doc/howto/clinic.rst:817 msgid "``'C'``" msgstr "" #: ../Doc/howto/clinic.rst:817 msgid "``int(accept={str})``" msgstr "" #: ../Doc/howto/clinic.rst:818 msgid "``'d'``" msgstr "``'d'``" #: ../Doc/howto/clinic.rst:818 msgid "``double``" msgstr "" #: ../Doc/howto/clinic.rst:819 msgid "``'D'``" msgstr "``'D'``" #: ../Doc/howto/clinic.rst:819 msgid "``Py_complex``" msgstr "" #: ../Doc/howto/clinic.rst:820 msgid "``'es'``" msgstr "" #: ../Doc/howto/clinic.rst:820 msgid "``str(encoding='name_of_encoding')``" msgstr "" #: ../Doc/howto/clinic.rst:821 msgid "``'es#'``" msgstr "" #: ../Doc/howto/clinic.rst:821 msgid "``str(encoding='name_of_encoding', zeroes=True)``" msgstr "" #: ../Doc/howto/clinic.rst:822 msgid "``'et'``" msgstr "" #: ../Doc/howto/clinic.rst:822 msgid "``str(encoding='name_of_encoding', accept={bytes, bytearray, str})``" msgstr "" #: ../Doc/howto/clinic.rst:823 msgid "``'et#'``" msgstr "" #: ../Doc/howto/clinic.rst:823 msgid "" "``str(encoding='name_of_encoding', accept={bytes, bytearray, str}, " "zeroes=True)``" msgstr "" #: ../Doc/howto/clinic.rst:824 msgid "``'f'``" msgstr "``'f'``" #: ../Doc/howto/clinic.rst:824 msgid "``float``" msgstr "" #: ../Doc/howto/clinic.rst:825 msgid "``'h'``" msgstr "``'h'``" #: ../Doc/howto/clinic.rst:825 msgid "``short``" msgstr "" #: ../Doc/howto/clinic.rst:826 msgid "``'H'``" msgstr "``'H'``" #: ../Doc/howto/clinic.rst:826 msgid "``unsigned_short(bitwise=True)``" msgstr "" #: ../Doc/howto/clinic.rst:827 msgid "``'i'``" msgstr "``'i'``" #: ../Doc/howto/clinic.rst:827 msgid "``int``" msgstr "``int``" #: ../Doc/howto/clinic.rst:828 msgid "``'I'``" msgstr "``'I'``" #: ../Doc/howto/clinic.rst:828 msgid "``unsigned_int(bitwise=True)``" msgstr "" #: ../Doc/howto/clinic.rst:829 msgid "``'k'``" msgstr "" #: ../Doc/howto/clinic.rst:829 msgid "``unsigned_long(bitwise=True)``" msgstr "" #: ../Doc/howto/clinic.rst:830 msgid "``'K'``" msgstr "" #: ../Doc/howto/clinic.rst:830 msgid "``unsigned_long_long(bitwise=True)``" msgstr "" #: ../Doc/howto/clinic.rst:831 msgid "``'l'``" msgstr "``'l'``" #: ../Doc/howto/clinic.rst:831 msgid "``long``" msgstr "``long``" #: ../Doc/howto/clinic.rst:832 msgid "``'L'``" msgstr "``'L'``" #: ../Doc/howto/clinic.rst:832 msgid "``long long``" msgstr "" #: ../Doc/howto/clinic.rst:833 msgid "``'n'``" msgstr "``'n'``" #: ../Doc/howto/clinic.rst:833 msgid "``Py_ssize_t``" msgstr "" #: ../Doc/howto/clinic.rst:834 msgid "``'O'``" msgstr "" #: ../Doc/howto/clinic.rst:834 msgid "``object``" msgstr "" #: ../Doc/howto/clinic.rst:835 msgid "``'O!'``" msgstr "" #: ../Doc/howto/clinic.rst:835 msgid "``object(subclass_of='&PySomething_Type')``" msgstr "" #: ../Doc/howto/clinic.rst:836 msgid "``'O&'``" msgstr "" #: ../Doc/howto/clinic.rst:836 msgid "``object(converter='name_of_c_function')``" msgstr "" #: ../Doc/howto/clinic.rst:837 msgid "``'p'``" msgstr "" #: ../Doc/howto/clinic.rst:837 msgid "``bool``" msgstr "" #: ../Doc/howto/clinic.rst:838 msgid "``'S'``" msgstr "``'S'``" #: ../Doc/howto/clinic.rst:838 msgid "``PyBytesObject``" msgstr "" #: ../Doc/howto/clinic.rst:839 msgid "``'s'``" msgstr "``'s'``" #: ../Doc/howto/clinic.rst:839 msgid "``str``" msgstr "" #: ../Doc/howto/clinic.rst:840 msgid "``'s#'``" msgstr "" #: ../Doc/howto/clinic.rst:840 msgid "``str(zeroes=True)``" msgstr "" #: ../Doc/howto/clinic.rst:841 msgid "``'s*'``" msgstr "" #: ../Doc/howto/clinic.rst:841 msgid "``Py_buffer(accept={buffer, str})``" msgstr "" #: ../Doc/howto/clinic.rst:842 msgid "``'U'``" msgstr "``'U'``" #: ../Doc/howto/clinic.rst:842 msgid "``unicode``" msgstr "" #: ../Doc/howto/clinic.rst:843 msgid "``'u'``" msgstr "``'u'``" #: ../Doc/howto/clinic.rst:843 msgid "``Py_UNICODE``" msgstr "" #: ../Doc/howto/clinic.rst:844 msgid "``'u#'``" msgstr "" #: ../Doc/howto/clinic.rst:844 msgid "``Py_UNICODE(zeroes=True)``" msgstr "" #: ../Doc/howto/clinic.rst:845 msgid "``'w*'``" msgstr "" #: ../Doc/howto/clinic.rst:845 msgid "``Py_buffer(accept={rwbuffer})``" msgstr "" #: ../Doc/howto/clinic.rst:846 msgid "``'Y'``" msgstr "" #: ../Doc/howto/clinic.rst:846 msgid "``PyByteArrayObject``" msgstr "" #: ../Doc/howto/clinic.rst:847 msgid "``'y'``" msgstr "" #: ../Doc/howto/clinic.rst:847 msgid "``str(accept={bytes})``" msgstr "" #: ../Doc/howto/clinic.rst:848 msgid "``'y#'``" msgstr "" #: ../Doc/howto/clinic.rst:848 msgid "``str(accept={robuffer}, zeroes=True)``" msgstr "" #: ../Doc/howto/clinic.rst:849 msgid "``'y*'``" msgstr "" #: ../Doc/howto/clinic.rst:849 msgid "``Py_buffer``" msgstr "" #: ../Doc/howto/clinic.rst:850 msgid "``'Z'``" msgstr "" #: ../Doc/howto/clinic.rst:850 msgid "``Py_UNICODE(accept={str, NoneType})``" msgstr "" #: ../Doc/howto/clinic.rst:851 msgid "``'Z#'``" msgstr "" #: ../Doc/howto/clinic.rst:851 msgid "``Py_UNICODE(accept={str, NoneType}, zeroes=True)``" msgstr "" #: ../Doc/howto/clinic.rst:852 msgid "``'z'``" msgstr "" #: ../Doc/howto/clinic.rst:852 msgid "``str(accept={str, NoneType})``" msgstr "" #: ../Doc/howto/clinic.rst:853 msgid "``'z#'``" msgstr "" #: ../Doc/howto/clinic.rst:853 msgid "``str(accept={str, NoneType}, zeroes=True)``" msgstr "" #: ../Doc/howto/clinic.rst:854 msgid "``'z*'``" msgstr "" #: ../Doc/howto/clinic.rst:854 msgid "``Py_buffer(accept={buffer, str, NoneType})``" msgstr "" #: ../Doc/howto/clinic.rst:857 msgid "" "As an example, here's our sample ``pickle.Pickler.dump`` using the proper " "converter::" msgstr "" #: ../Doc/howto/clinic.rst:870 msgid "" "Argument Clinic will show you all the converters it has available. For each " "converter it'll show you all the parameters it accepts, along with the " "default value for each parameter. Just run ``Tools/clinic/clinic.py --" "converters`` to see the full list." msgstr "" #: ../Doc/howto/clinic.rst:876 msgid "Py_buffer" msgstr "" #: ../Doc/howto/clinic.rst:878 msgid "" "When using the ``Py_buffer`` converter (or the ``'s*'``, ``'w*'``, ``'*y'``, " "or ``'z*'`` legacy converters), you *must* not call :c:func:" "`PyBuffer_Release` on the provided buffer. Argument Clinic generates code " "that does it for you (in the parsing function)." msgstr "" #: ../Doc/howto/clinic.rst:886 msgid "Advanced converters" msgstr "" #: ../Doc/howto/clinic.rst:888 msgid "" "Remember those format units you skipped for your first time because they " "were advanced? Here's how to handle those too." msgstr "" #: ../Doc/howto/clinic.rst:891 msgid "" "The trick is, all those format units take arguments--either conversion " "functions, or types, or strings specifying an encoding. (But \"legacy " "converters\" don't support arguments. That's why we skipped them for your " "first function.) The argument you specified to the format unit is now an " "argument to the converter; this argument is either ``converter`` (for " "``O&``), ``subclass_of`` (for ``O!``), or ``encoding`` (for all the format " "units that start with ``e``)." msgstr "" #: ../Doc/howto/clinic.rst:899 msgid "" "When using ``subclass_of``, you may also want to use the other custom " "argument for ``object()``: ``type``, which lets you set the type actually " "used for the parameter. For example, if you want to ensure that the object " "is a subclass of ``PyUnicode_Type``, you probably want to use the converter " "``object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')``." msgstr "" #: ../Doc/howto/clinic.rst:905 msgid "" "One possible problem with using Argument Clinic: it takes away some possible " "flexibility for the format units starting with ``e``. When writing a " "``PyArg_Parse`` call by hand, you could theoretically decide at runtime what " "encoding string to pass in to :c:func:`PyArg_ParseTuple`. But now this " "string must be hard-coded at Argument-Clinic-preprocessing-time. This " "limitation is deliberate; it made supporting this format unit much easier, " "and may allow for future optimizations. This restriction doesn't seem " "unreasonable; CPython itself always passes in static hard-coded encoding " "strings for parameters whose format units start with ``e``." msgstr "" #: ../Doc/howto/clinic.rst:918 msgid "Parameter default values" msgstr "" #: ../Doc/howto/clinic.rst:920 msgid "" "Default values for parameters can be any of a number of values. At their " "simplest, they can be string, int, or float literals::" msgstr "" #: ../Doc/howto/clinic.rst:927 msgid "They can also use any of Python's built-in constants::" msgstr "" #: ../Doc/howto/clinic.rst:933 msgid "" "There's also special support for a default value of ``NULL``, and for simple " "expressions, documented in the following sections." msgstr "" #: ../Doc/howto/clinic.rst:938 msgid "The ``NULL`` default value" msgstr "" #: ../Doc/howto/clinic.rst:940 msgid "" "For string and object parameters, you can set them to ``None`` to indicate " "that there's no default. However, that means the C variable will be " "initialized to ``Py_None``. For convenience's sakes, there's a special " "value called ``NULL`` for just this reason: from Python's perspective it " "behaves like a default value of ``None``, but the C variable is initialized " "with ``NULL``." msgstr "" #: ../Doc/howto/clinic.rst:948 msgid "Expressions specified as default values" msgstr "" #: ../Doc/howto/clinic.rst:950 msgid "" "The default value for a parameter can be more than just a literal value. It " "can be an entire expression, using math operators and looking up attributes " "on objects. However, this support isn't exactly simple, because of some non-" "obvious semantics." msgstr "" #: ../Doc/howto/clinic.rst:955 msgid "Consider the following example::" msgstr "" #: ../Doc/howto/clinic.rst:959 msgid "" "``sys.maxsize`` can have different values on different platforms. Therefore " "Argument Clinic can't simply evaluate that expression locally and hard-code " "it in C. So it stores the default in such a way that it will get evaluated " "at runtime, when the user asks for the function's signature." msgstr "" #: ../Doc/howto/clinic.rst:964 msgid "" "What namespace is available when the expression is evaluated? It's " "evaluated in the context of the module the builtin came from. So, if your " "module has an attribute called \"``max_widgets``\", you may simply use it::" msgstr "" #: ../Doc/howto/clinic.rst:970 msgid "" "If the symbol isn't found in the current module, it fails over to looking in " "``sys.modules``. That's how it can find ``sys.maxsize`` for example. " "(Since you don't know in advance what modules the user will load into their " "interpreter, it's best to restrict yourself to modules that are preloaded by " "Python itself.)" msgstr "" #: ../Doc/howto/clinic.rst:975 msgid "" "Evaluating default values only at runtime means Argument Clinic can't " "compute the correct equivalent C default value. So you need to tell it " "explicitly. When you use an expression, you must also specify the equivalent " "expression in C, using the ``c_default`` parameter to the converter::" msgstr "" #: ../Doc/howto/clinic.rst:982 msgid "" "Another complication: Argument Clinic can't know in advance whether or not " "the expression you supply is valid. It parses it to make sure it looks " "legal, but it can't *actually* know. You must be very careful when using " "expressions to specify values that are guaranteed to be valid at runtime!" msgstr "" #: ../Doc/howto/clinic.rst:987 msgid "" "Finally, because expressions must be representable as static C values, there " "are many restrictions on legal expressions. Here's a list of Python " "features you're not permitted to use:" msgstr "" #: ../Doc/howto/clinic.rst:991 msgid "Function calls." msgstr "" #: ../Doc/howto/clinic.rst:992 msgid "Inline if statements (``3 if foo else 5``)." msgstr "" #: ../Doc/howto/clinic.rst:993 msgid "Automatic sequence unpacking (``*[1, 2, 3]``)." msgstr "" #: ../Doc/howto/clinic.rst:994 msgid "List/set/dict comprehensions and generator expressions." msgstr "" #: ../Doc/howto/clinic.rst:995 msgid "Tuple/list/set/dict literals." msgstr "" #: ../Doc/howto/clinic.rst:1000 msgid "Using a return converter" msgstr "" #: ../Doc/howto/clinic.rst:1002 msgid "" "By default the impl function Argument Clinic generates for you returns " "``PyObject *``. But your C function often computes some C type, then " "converts it into the ``PyObject *`` at the last moment. Argument Clinic " "handles converting your inputs from Python types into native C types--why " "not have it convert your return value from a native C type into a Python " "type too?" msgstr "" #: ../Doc/howto/clinic.rst:1008 msgid "" "That's what a \"return converter\" does. It changes your impl function to " "return some C type, then adds code to the generated (non-impl) function to " "handle converting that value into the appropriate ``PyObject *``." msgstr "" #: ../Doc/howto/clinic.rst:1012 msgid "" "The syntax for return converters is similar to that of parameter converters. " "You specify the return converter like it was a return annotation on the " "function itself. Return converters behave much the same as parameter " "converters; they take arguments, the arguments are all keyword-only, and if " "you're not changing any of the default arguments you can omit the " "parentheses." msgstr "" #: ../Doc/howto/clinic.rst:1018 msgid "" "(If you use both ``\"as\"`` *and* a return converter for your function, the " "``\"as\"`` should come before the return converter.)" msgstr "" #: ../Doc/howto/clinic.rst:1021 msgid "" "There's one additional complication when using return converters: how do you " "indicate an error has occurred? Normally, a function returns a valid (non-" "``NULL``) pointer for success, and ``NULL`` for failure. But if you use an " "integer return converter, all integers are valid. How can Argument Clinic " "detect an error? Its solution: each return converter implicitly looks for a " "special value that indicates an error. If you return that value, and an " "error has been set (``PyErr_Occurred()`` returns a true value), then the " "generated code will propagate the error. Otherwise it will encode the value " "you return like normal." msgstr "" #: ../Doc/howto/clinic.rst:1030 msgid "Currently Argument Clinic supports only a few return converters::" msgstr "" #: ../Doc/howto/clinic.rst:1043 msgid "" "None of these take parameters. For the first three, return -1 to indicate " "error. For ``DecodeFSDefault``, the return type is ``char *``; return a " "NULL pointer to indicate an error." msgstr "" #: ../Doc/howto/clinic.rst:1047 msgid "" "(There's also an experimental ``NoneType`` converter, which lets you return " "``Py_None`` on success or ``NULL`` on failure, without having to increment " "the reference count on ``Py_None``. I'm not sure it adds enough clarity to " "be worth using.)" msgstr "" #: ../Doc/howto/clinic.rst:1052 msgid "" "To see all the return converters Argument Clinic supports, along with their " "parameters (if any), just run ``Tools/clinic/clinic.py --converters`` for " "the full list." msgstr "" #: ../Doc/howto/clinic.rst:1058 msgid "Cloning existing functions" msgstr "" #: ../Doc/howto/clinic.rst:1060 msgid "" "If you have a number of functions that look similar, you may be able to use " "Clinic's \"clone\" feature. When you clone an existing function, you reuse:" msgstr "" #: ../Doc/howto/clinic.rst:1064 msgid "its parameters, including" msgstr "" #: ../Doc/howto/clinic.rst:1066 msgid "their names," msgstr "" #: ../Doc/howto/clinic.rst:1068 msgid "their converters, with all parameters," msgstr "" #: ../Doc/howto/clinic.rst:1070 msgid "their default values," msgstr "" #: ../Doc/howto/clinic.rst:1072 msgid "their per-parameter docstrings," msgstr "" #: ../Doc/howto/clinic.rst:1074 msgid "" "their *kind* (whether they're positional only, positional or keyword, or " "keyword only), and" msgstr "" #: ../Doc/howto/clinic.rst:1077 msgid "its return converter." msgstr "" #: ../Doc/howto/clinic.rst:1079 msgid "" "The only thing not copied from the original function is its docstring; the " "syntax allows you to specify a new docstring." msgstr "" #: ../Doc/howto/clinic.rst:1082 msgid "Here's the syntax for cloning a function::" msgstr "" #: ../Doc/howto/clinic.rst:1090 msgid "" "(The functions can be in different modules or classes. I wrote ``module." "class`` in the sample just to illustrate that you must use the full path to " "*both* functions.)" msgstr "" #: ../Doc/howto/clinic.rst:1094 msgid "" "Sorry, there's no syntax for partially-cloning a function, or cloning a " "function then modifying it. Cloning is an all-or nothing proposition." msgstr "" #: ../Doc/howto/clinic.rst:1097 msgid "" "Also, the function you are cloning from must have been previously defined in " "the current file." msgstr "" #: ../Doc/howto/clinic.rst:1101 msgid "Calling Python code" msgstr "" #: ../Doc/howto/clinic.rst:1103 msgid "" "The rest of the advanced topics require you to write Python code which lives " "inside your C file and modifies Argument Clinic's runtime state. This is " "simple: you simply define a Python block." msgstr "" #: ../Doc/howto/clinic.rst:1107 msgid "" "A Python block uses different delimiter lines than an Argument Clinic " "function block. It looks like this::" msgstr "" #: ../Doc/howto/clinic.rst:1114 msgid "" "All the code inside the Python block is executed at the time it's parsed. " "All text written to stdout inside the block is redirected into the \"output" "\" after the block." msgstr "" #: ../Doc/howto/clinic.rst:1118 msgid "" "As an example, here's a Python block that adds a static integer variable to " "the C code::" msgstr "" #: ../Doc/howto/clinic.rst:1129 msgid "Using a \"self converter\"" msgstr "" #: ../Doc/howto/clinic.rst:1131 msgid "" "Argument Clinic automatically adds a \"self\" parameter for you using a " "default converter. It automatically sets the ``type`` of this parameter to " "the \"pointer to an instance\" you specified when you declared the type. " "However, you can override Argument Clinic's converter and specify one " "yourself. Just add your own ``self`` parameter as the first parameter in a " "block, and ensure that its converter is an instance of ``self_converter`` or " "a subclass thereof." msgstr "" #: ../Doc/howto/clinic.rst:1140 msgid "" "What's the point? This lets you override the type of ``self``, or give it a " "different default name." msgstr "" #: ../Doc/howto/clinic.rst:1143 msgid "" "How do you specify the custom type you want to cast ``self`` to? If you only " "have one or two functions with the same type for ``self``, you can directly " "use Argument Clinic's existing ``self`` converter, passing in the type you " "want to use as the ``type`` parameter::" msgstr "" #: ../Doc/howto/clinic.rst:1159 msgid "" "On the other hand, if you have a lot of functions that will use the same " "type for ``self``, it's best to create your own converter, subclassing " "``self_converter`` but overwriting the ``type`` member::" msgstr "" #: ../Doc/howto/clinic.rst:1182 msgid "Writing a custom converter" msgstr "" #: ../Doc/howto/clinic.rst:1184 msgid "" "As we hinted at in the previous section... you can write your own " "converters! A converter is simply a Python class that inherits from " "``CConverter``. The main purpose of a custom converter is if you have a " "parameter using the ``O&`` format unit--parsing this parameter means calling " "a :c:func:`PyArg_ParseTuple` \"converter function\"." msgstr "" #: ../Doc/howto/clinic.rst:1190 msgid "" "Your converter class should be named ``*something*_converter``. If the name " "follows this convention, then your converter class will be automatically " "registered with Argument Clinic; its name will be the name of your class " "with the ``_converter`` suffix stripped off. (This is accomplished with a " "metaclass.)" msgstr "" #: ../Doc/howto/clinic.rst:1196 msgid "" "You shouldn't subclass ``CConverter.__init__``. Instead, you should write a " "``converter_init()`` function. ``converter_init()`` always accepts a " "``self`` parameter; after that, all additional parameters *must* be keyword-" "only. Any arguments passed in to the converter in Argument Clinic will be " "passed along to your ``converter_init()``." msgstr "" #: ../Doc/howto/clinic.rst:1203 msgid "" "There are some additional members of ``CConverter`` you may wish to specify " "in your subclass. Here's the current list:" msgstr "" #: ../Doc/howto/clinic.rst:1207 msgid "" "The C type to use for this variable. ``type`` should be a Python string " "specifying the type, e.g. ``int``. If this is a pointer type, the type " "string should end with ``' *'``." msgstr "" #: ../Doc/howto/clinic.rst:1213 msgid "``default``" msgstr "" #: ../Doc/howto/clinic.rst:1212 msgid "" "The Python default value for this parameter, as a Python value. Or the magic " "value ``unspecified`` if there is no default." msgstr "" #: ../Doc/howto/clinic.rst:1218 msgid "``py_default``" msgstr "" #: ../Doc/howto/clinic.rst:1216 msgid "" "``default`` as it should appear in Python code, as a string. Or ``None`` if " "there is no default." msgstr "" #: ../Doc/howto/clinic.rst:1221 msgid "" "``default`` as it should appear in C code, as a string. Or ``None`` if there " "is no default." msgstr "" #: ../Doc/howto/clinic.rst:1234 msgid "``c_ignored_default``" msgstr "" #: ../Doc/howto/clinic.rst:1226 msgid "" "The default value used to initialize the C variable when there is no " "default, but not specifying a default may result in an \"uninitialized " "variable\" warning. This can easily happen when using option groups--" "although properly-written code will never actually use this value, the " "variable does get passed in to the impl, and the C compiler will complain " "about the \"use\" of the uninitialized value. This value should always be a " "non-empty string." msgstr "" #: ../Doc/howto/clinic.rst:1237 msgid "The name of the C converter function, as a string." msgstr "" #: ../Doc/howto/clinic.rst:1242 msgid "``impl_by_reference``" msgstr "" #: ../Doc/howto/clinic.rst:1240 msgid "" "A boolean value. If true, Argument Clinic will add a ``&`` in front of the " "name of the variable when passing it into the impl function." msgstr "" #: ../Doc/howto/clinic.rst:1248 msgid "``parse_by_reference``" msgstr "" #: ../Doc/howto/clinic.rst:1245 msgid "" "A boolean value. If true, Argument Clinic will add a ``&`` in front of the " "name of the variable when passing it into :c:func:`PyArg_ParseTuple`." msgstr "" #: ../Doc/howto/clinic.rst:1250 msgid "" "Here's the simplest example of a custom converter, from ``Modules/zlibmodule." "c``::" msgstr "" #: ../Doc/howto/clinic.rst:1261 msgid "" "This block adds a converter to Argument Clinic named ``ssize_t``. " "Parameters declared as ``ssize_t`` will be declared as type ``Py_ssize_t``, " "and will be parsed by the ``'O&'`` format unit, which will call the " "``ssize_t_converter`` converter function. ``ssize_t`` variables " "automatically support default values." msgstr "" #: ../Doc/howto/clinic.rst:1267 msgid "" "More sophisticated custom converters can insert custom C code to handle " "initialization and cleanup. You can see more examples of custom converters " "in the CPython source tree; grep the C files for the string ``CConverter``." msgstr "" #: ../Doc/howto/clinic.rst:1273 msgid "Writing a custom return converter" msgstr "" #: ../Doc/howto/clinic.rst:1275 msgid "" "Writing a custom return converter is much like writing a custom converter. " "Except it's somewhat simpler, because return converters are themselves much " "simpler." msgstr "" #: ../Doc/howto/clinic.rst:1279 msgid "" "Return converters must subclass ``CReturnConverter``. There are no examples " "yet of custom return converters, because they are not widely used yet. If " "you wish to write your own return converter, please read ``Tools/clinic/" "clinic.py``, specifically the implementation of ``CReturnConverter`` and all " "its subclasses." msgstr "" #: ../Doc/howto/clinic.rst:1287 msgid "METH_O and METH_NOARGS" msgstr "" #: ../Doc/howto/clinic.rst:1289 msgid "" "To convert a function using ``METH_O``, make sure the function's single " "argument is using the ``object`` converter, and mark the arguments as " "positional-only::" msgstr "" #: ../Doc/howto/clinic.rst:1301 msgid "" "To convert a function using ``METH_NOARGS``, just don't specify any " "arguments." msgstr "" #: ../Doc/howto/clinic.rst:1304 msgid "" "You can still use a self converter, a return converter, and specify a " "``type`` argument to the object converter for ``METH_O``." msgstr "" #: ../Doc/howto/clinic.rst:1308 msgid "tp_new and tp_init functions" msgstr "" #: ../Doc/howto/clinic.rst:1310 msgid "" "You can convert ``tp_new`` and ``tp_init`` functions. Just name them " "``__new__`` or ``__init__`` as appropriate. Notes:" msgstr "" #: ../Doc/howto/clinic.rst:1313 msgid "" "The function name generated for ``__new__`` doesn't end in ``__new__`` like " "it would by default. It's just the name of the class, converted into a " "valid C identifier." msgstr "" #: ../Doc/howto/clinic.rst:1317 msgid "No ``PyMethodDef`` ``#define`` is generated for these functions." msgstr "" #: ../Doc/howto/clinic.rst:1319 msgid "``__init__`` functions return ``int``, not ``PyObject *``." msgstr "" #: ../Doc/howto/clinic.rst:1321 msgid "Use the docstring as the class docstring." msgstr "" #: ../Doc/howto/clinic.rst:1323 msgid "" "Although ``__new__`` and ``__init__`` functions must always accept both the " "``args`` and ``kwargs`` objects, when converting you may specify any " "signature for these functions that you like. (If your function doesn't " "support keywords, the parsing function generated will throw an exception if " "it receives any.)" msgstr "" #: ../Doc/howto/clinic.rst:1330 msgid "Changing and redirecting Clinic's output" msgstr "" #: ../Doc/howto/clinic.rst:1332 msgid "" "It can be inconvenient to have Clinic's output interspersed with your " "conventional hand-edited C code. Luckily, Clinic is configurable: you can " "buffer up its output for printing later (or earlier!), or write its output " "to a separate file. You can also add a prefix or suffix to every line of " "Clinic's generated output." msgstr "" #: ../Doc/howto/clinic.rst:1338 msgid "" "While changing Clinic's output in this manner can be a boon to readability, " "it may result in Clinic code using types before they are defined, or your " "code attempting to use Clinic-generated code before it is defined. These " "problems can be easily solved by rearranging the declarations in your file, " "or moving where Clinic's generated code goes. (This is why the default " "behavior of Clinic is to output everything into the current block; while " "many people consider this hampers readability, it will never require " "rearranging your code to fix definition-before-use problems.)" msgstr "" #: ../Doc/howto/clinic.rst:1347 msgid "Let's start with defining some terminology:" msgstr "" #: ../Doc/howto/clinic.rst:1372 msgid "*field*" msgstr "" #: ../Doc/howto/clinic.rst:1350 msgid "" "A field, in this context, is a subsection of Clinic's output. For example, " "the ``#define`` for the ``PyMethodDef`` structure is a field, called " "``methoddef_define``. Clinic has seven different fields it can output per " "function definition::" msgstr "" #: ../Doc/howto/clinic.rst:1363 msgid "" "All the names are of the form ``\"_\"``, where ``\"\"`` is the " "semantic object represented (the parsing function, the impl function, the " "docstring, or the methoddef structure) and ``\"\"`` represents what kind " "of statement the field is. Field names that end in ``\"_prototype\"`` " "represent forward declarations of that thing, without the actual body/data " "of the thing; field names that end in ``\"_definition\"`` represent the " "actual definition of the thing, with the body/data of the thing. (``" "\"methoddef\"`` is special, it's the only one that ends with ``\"_define" "\"``, representing that it's a preprocessor #define.)" msgstr "" #: ../Doc/howto/clinic.rst:1406 msgid "*destination*" msgstr "" #: ../Doc/howto/clinic.rst:1375 msgid "" "A destination is a place Clinic can write output to. There are five built-" "in destinations:" msgstr "" #: ../Doc/howto/clinic.rst:1380 ../Doc/howto/clinic.rst:1449 #: ../Doc/howto/clinic.rst:1523 msgid "``block``" msgstr "" #: ../Doc/howto/clinic.rst:1379 msgid "" "The default destination: printed in the output section of the current Clinic " "block." msgstr "" #: ../Doc/howto/clinic.rst:1386 ../Doc/howto/clinic.rst:1476 #: ../Doc/howto/clinic.rst:1526 msgid "``buffer``" msgstr "" #: ../Doc/howto/clinic.rst:1383 msgid "" "A text buffer where you can save text for later. Text sent here is appended " "to the end of any existing text. It's an error to have any text left in the " "buffer when Clinic finishes processing a file." msgstr "" #: ../Doc/howto/clinic.rst:1397 ../Doc/howto/clinic.rst:1462 #: ../Doc/howto/clinic.rst:1552 msgid "``file``" msgstr "" #: ../Doc/howto/clinic.rst:1389 msgid "" "A separate \"clinic file\" that will be created automatically by Clinic. The " "filename chosen for the file is ``{basename}.clinic{extension}``, where " "``basename`` and ``extension`` were assigned the output from ``os.path." "splitext()`` run on the current file. (Example: the ``file`` destination " "for ``_pickle.c`` would be written to ``_pickle.clinic.c``.)" msgstr "" #: ../Doc/howto/clinic.rst:1396 msgid "" "**Important: When using a** ``file`` **destination, you** *must check in* " "**the generated file!**" msgstr "" #: ../Doc/howto/clinic.rst:1402 ../Doc/howto/clinic.rst:1489 #: ../Doc/howto/clinic.rst:1556 msgid "``two-pass``" msgstr "" #: ../Doc/howto/clinic.rst:1400 msgid "" "A buffer like ``buffer``. However, a two-pass buffer can only be written " "once, and it prints out all text sent to it during all of processing, even " "from Clinic blocks *after* the" msgstr "" #: ../Doc/howto/clinic.rst:1406 ../Doc/howto/clinic.rst:1519 msgid "``suppress``" msgstr "" #: ../Doc/howto/clinic.rst:1405 msgid "The text is suppressed--thrown away." msgstr "" #: ../Doc/howto/clinic.rst:1408 msgid "Clinic defines five new directives that let you reconfigure its output." msgstr "" #: ../Doc/howto/clinic.rst:1410 msgid "The first new directive is ``dump``::" msgstr "" #: ../Doc/howto/clinic.rst:1414 msgid "" "This dumps the current contents of the named destination into the output of " "the current block, and empties it. This only works with ``buffer`` and " "``two-pass`` destinations." msgstr "" #: ../Doc/howto/clinic.rst:1418 msgid "" "The second new directive is ``output``. The most basic form of ``output`` " "is like this::" msgstr "" #: ../Doc/howto/clinic.rst:1423 msgid "" "This tells Clinic to output *field* to *destination*. ``output`` also " "supports a special meta-destination, called ``everything``, which tells " "Clinic to output *all* fields to that *destination*." msgstr "" #: ../Doc/howto/clinic.rst:1427 msgid "``output`` has a number of other functions::" msgstr "" #: ../Doc/howto/clinic.rst:1434 msgid "" "``output push`` and ``output pop`` allow you to push and pop configurations " "on an internal configuration stack, so that you can temporarily modify the " "output configuration, then easily restore the previous configuration. " "Simply push before your change to save the current configuration, then pop " "when you wish to restore the previous configuration." msgstr "" #: ../Doc/howto/clinic.rst:1441 msgid "" "``output preset`` sets Clinic's output to one of several built-in preset " "configurations, as follows:" msgstr "" #: ../Doc/howto/clinic.rst:1445 msgid "" "Clinic's original starting configuration. Writes everything immediately " "after the input block." msgstr "" #: ../Doc/howto/clinic.rst:1448 msgid "" "Suppress the ``parser_prototype`` and ``docstring_prototype``, write " "everything else to ``block``." msgstr "" #: ../Doc/howto/clinic.rst:1452 msgid "" "Designed to write everything to the \"clinic file\" that it can. You then " "``#include`` this file near the top of your file. You may need to rearrange " "your file to make this work, though usually this just means creating forward " "declarations for various ``typedef`` and ``PyTypeObject`` definitions." msgstr "" #: ../Doc/howto/clinic.rst:1458 msgid "" "Suppress the ``parser_prototype`` and ``docstring_prototype``, write the " "``impl_definition`` to ``block``, and write everything else to ``file``." msgstr "" #: ../Doc/howto/clinic.rst:1462 msgid "The default filename is ``\"{dirname}/clinic/{basename}.h\"``." msgstr "" #: ../Doc/howto/clinic.rst:1465 msgid "" "Save up all most of the output from Clinic, to be written into your file " "near the end. For Python files implementing modules or builtin types, it's " "recommended that you dump the buffer just above the static structures for " "your module or builtin type; these are normally very near the end. Using " "``buffer`` may require even more editing than ``file``, if your file has " "static ``PyMethodDef`` arrays defined in the middle of the file." msgstr "" #: ../Doc/howto/clinic.rst:1474 msgid "" "Suppress the ``parser_prototype``, ``impl_prototype``, and " "``docstring_prototype``, write the ``impl_definition`` to ``block``, and " "write everything else to ``file``." msgstr "" #: ../Doc/howto/clinic.rst:1479 msgid "" "Similar to the ``buffer`` preset, but writes forward declarations to the " "``two-pass`` buffer, and definitions to the ``buffer``. This is similar to " "the ``buffer`` preset, but may require less editing than ``buffer``. Dump " "the ``two-pass`` buffer near the top of your file, and dump the ``buffer`` " "near the end just like you would when using the ``buffer`` preset." msgstr "" #: ../Doc/howto/clinic.rst:1486 msgid "" "Suppresses the ``impl_prototype``, write the ``impl_definition`` to " "``block``, write ``docstring_prototype``, ``methoddef_define``, and " "``parser_prototype`` to ``two-pass``, write everything else to ``buffer``." msgstr "" #: ../Doc/howto/clinic.rst:1500 msgid "``partial-buffer``" msgstr "" #: ../Doc/howto/clinic.rst:1492 msgid "" "Similar to the ``buffer`` preset, but writes more things to ``block``, only " "writing the really big chunks of generated code to ``buffer``. This avoids " "the definition-before-use problem of ``buffer`` completely, at the small " "cost of having slightly more stuff in the block's output. Dump the " "``buffer`` near the end, just like you would when using the ``buffer`` " "preset." msgstr "" #: ../Doc/howto/clinic.rst:1499 msgid "" "Suppresses the ``impl_prototype``, write the ``docstring_definition`` and " "``parser_definition`` to ``buffer``, write everything else to ``block``." msgstr "" #: ../Doc/howto/clinic.rst:1502 msgid "The third new directive is ``destination``::" msgstr "" #: ../Doc/howto/clinic.rst:1506 msgid "This performs an operation on the destination named ``name``." msgstr "" #: ../Doc/howto/clinic.rst:1508 msgid "There are two defined subcommands: ``new`` and ``clear``." msgstr "" #: ../Doc/howto/clinic.rst:1510 msgid "The ``new`` subcommand works like this::" msgstr "" #: ../Doc/howto/clinic.rst:1514 msgid "" "This creates a new destination with name ```` and type ````." msgstr "" #: ../Doc/howto/clinic.rst:1516 msgid "There are five destination types:" msgstr "" #: ../Doc/howto/clinic.rst:1519 msgid "Throws the text away." msgstr "" #: ../Doc/howto/clinic.rst:1522 msgid "" "Writes the text to the current block. This is what Clinic originally did." msgstr "" #: ../Doc/howto/clinic.rst:1526 msgid "A simple text buffer, like the \"buffer\" builtin destination above." msgstr "" #: ../Doc/howto/clinic.rst:1529 msgid "" "A text file. The file destination takes an extra argument, a template to " "use for building the filename, like so:" msgstr "" #: ../Doc/howto/clinic.rst:1532 msgid "destination new " msgstr "" #: ../Doc/howto/clinic.rst:1534 msgid "" "The template can use three strings internally that will be replaced by bits " "of the filename:" msgstr "" #: ../Doc/howto/clinic.rst:1537 msgid "{path}" msgstr "" #: ../Doc/howto/clinic.rst:1538 msgid "The full path to the file, including directory and full filename." msgstr "" #: ../Doc/howto/clinic.rst:1539 msgid "{dirname}" msgstr "" #: ../Doc/howto/clinic.rst:1540 msgid "The name of the directory the file is in." msgstr "" #: ../Doc/howto/clinic.rst:1541 msgid "{basename}" msgstr "" #: ../Doc/howto/clinic.rst:1542 msgid "Just the name of the file, not including the directory." msgstr "" #: ../Doc/howto/clinic.rst:1544 msgid "{basename_root}" msgstr "" #: ../Doc/howto/clinic.rst:1544 msgid "" "Basename with the extension clipped off (everything up to but not including " "the last '.')." msgstr "" #: ../Doc/howto/clinic.rst:1548 msgid "{basename_extension}" msgstr "" #: ../Doc/howto/clinic.rst:1547 msgid "" "The last '.' and everything after it. If the basename does not contain a " "period, this will be the empty string." msgstr "" #: ../Doc/howto/clinic.rst:1550 msgid "" "If there are no periods in the filename, {basename} and {filename} are the " "same, and {extension} is empty. \"{basename}{extension}\" is always exactly " "the same as \"{filename}\".\"" msgstr "" #: ../Doc/howto/clinic.rst:1555 msgid "A two-pass buffer, like the \"two-pass\" builtin destination above." msgstr "" #: ../Doc/howto/clinic.rst:1558 msgid "The ``clear`` subcommand works like this::" msgstr "" #: ../Doc/howto/clinic.rst:1562 msgid "" "It removes all the accumulated text up to this point in the destination. (I " "don't know what you'd need this for, but I thought maybe it'd be useful " "while someone's experimenting.)" msgstr "" #: ../Doc/howto/clinic.rst:1566 msgid "The fourth new directive is ``set``::" msgstr "" #: ../Doc/howto/clinic.rst:1571 msgid "" "``set`` lets you set two internal variables in Clinic. ``line_prefix`` is a " "string that will be prepended to every line of Clinic's output; " "``line_suffix`` is a string that will be appended to every line of Clinic's " "output." msgstr "" #: ../Doc/howto/clinic.rst:1575 msgid "Both of these support two format strings:" msgstr "" #: ../Doc/howto/clinic.rst:1578 msgid "``{block comment start}``" msgstr "" #: ../Doc/howto/clinic.rst:1578 msgid "" "Turns into the string ``/*``, the start-comment text sequence for C files." msgstr "" #: ../Doc/howto/clinic.rst:1581 msgid "``{block comment end}``" msgstr "" #: ../Doc/howto/clinic.rst:1581 msgid "" "Turns into the string ``*/``, the end-comment text sequence for C files." msgstr "" #: ../Doc/howto/clinic.rst:1583 msgid "" "The final new directive is one you shouldn't need to use directly, called " "``preserve``::" msgstr "" #: ../Doc/howto/clinic.rst:1588 msgid "" "This tells Clinic that the current contents of the output should be kept, " "unmodified. This is used internally by Clinic when dumping output into " "``file`` files; wrapping it in a Clinic block lets Clinic use its existing " "checksum functionality to ensure the file was not modified by hand before it " "gets overwritten." msgstr "" #: ../Doc/howto/clinic.rst:1595 msgid "The #ifdef trick" msgstr "" #: ../Doc/howto/clinic.rst:1597 msgid "" "If you're converting a function that isn't available on all platforms, " "there's a trick you can use to make life a little easier. The existing code " "probably looks like this::" msgstr "" #: ../Doc/howto/clinic.rst:1608 msgid "" "And then in the ``PyMethodDef`` structure at the bottom the existing code " "will have::" msgstr "" #: ../Doc/howto/clinic.rst:1615 msgid "" "In this scenario, you should enclose the body of your impl function inside " "the ``#ifdef``, like so::" msgstr "" #: ../Doc/howto/clinic.rst:1629 msgid "" "Then, remove those three lines from the ``PyMethodDef`` structure, replacing " "them with the macro Argument Clinic generated::" msgstr "" #: ../Doc/howto/clinic.rst:1634 msgid "" "(You can find the real name for this macro inside the generated code. Or you " "can calculate it yourself: it's the name of your function as defined on the " "first line of your block, but with periods changed to underscores, " "uppercased, and ``\"_METHODDEF\"`` added to the end.)" msgstr "" #: ../Doc/howto/clinic.rst:1639 msgid "" "Perhaps you're wondering: what if ``HAVE_FUNCTIONNAME`` isn't defined? The " "``MODULE_FUNCTIONNAME_METHODDEF`` macro won't be defined either!" msgstr "" #: ../Doc/howto/clinic.rst:1642 msgid "" "Here's where Argument Clinic gets very clever. It actually detects that the " "Argument Clinic block might be deactivated by the ``#ifdef``. When that " "happens, it generates a little extra code that looks like this::" msgstr "" #: ../Doc/howto/clinic.rst:1650 msgid "" "That means the macro always works. If the function is defined, this turns " "into the correct structure, including the trailing comma. If the function " "is undefined, this turns into nothing." msgstr "" #: ../Doc/howto/clinic.rst:1654 msgid "" "However, this causes one ticklish problem: where should Argument Clinic put " "this extra code when using the \"block\" output preset? It can't go in the " "output block, because that could be deactivated by the ``#ifdef``. (That's " "the whole point!)" msgstr "" #: ../Doc/howto/clinic.rst:1658 msgid "" "In this situation, Argument Clinic writes the extra code to the \"buffer\" " "destination. This may mean that you get a complaint from Argument Clinic::" msgstr "" #: ../Doc/howto/clinic.rst:1664 msgid "" "When this happens, just open your file, find the ``dump buffer`` block that " "Argument Clinic added to your file (it'll be at the very bottom), then move " "it above the ``PyMethodDef`` structure where that macro is used." msgstr "" #: ../Doc/howto/clinic.rst:1671 msgid "Using Argument Clinic in Python files" msgstr "" #: ../Doc/howto/clinic.rst:1673 msgid "" "It's actually possible to use Argument Clinic to preprocess Python files. " "There's no point to using Argument Clinic blocks, of course, as the output " "wouldn't make any sense to the Python interpreter. But using Argument " "Clinic to run Python blocks lets you use Python as a Python preprocessor!" msgstr "" #: ../Doc/howto/clinic.rst:1678 msgid "" "Since Python comments are different from C comments, Argument Clinic blocks " "embedded in Python files look slightly different. They look like this::" msgstr "" #: ../Doc/howto/cporting.rst:7 msgid "Porting Extension Modules to Python 3" msgstr "" #: ../Doc/howto/cporting.rst:9 msgid "Benjamin Peterson" msgstr "Benjamin Peterson" #: ../Doc/howto/cporting.rst:14 msgid "" "Although changing the C-API was not one of Python 3's objectives, the many " "Python-level changes made leaving Python 2's API intact impossible. In " "fact, some changes such as :func:`int` and :func:`long` unification are more " "obvious on the C level. This document endeavors to document " "incompatibilities and how they can be worked around." msgstr "" #: ../Doc/howto/cporting.rst:23 msgid "Conditional compilation" msgstr "" #: ../Doc/howto/cporting.rst:25 msgid "" "The easiest way to compile only some code for Python 3 is to check if :c:" "macro:`PY_MAJOR_VERSION` is greater than or equal to 3. ::" msgstr "" #: ../Doc/howto/cporting.rst:32 msgid "" "API functions that are not present can be aliased to their equivalents " "within conditional blocks." msgstr "" #: ../Doc/howto/cporting.rst:37 msgid "Changes to Object APIs" msgstr "" #: ../Doc/howto/cporting.rst:39 msgid "" "Python 3 merged together some types with similar functions while cleanly " "separating others." msgstr "" #: ../Doc/howto/cporting.rst:44 msgid "str/unicode Unification" msgstr "" #: ../Doc/howto/cporting.rst:46 msgid "" "Python 3's :func:`str` type is equivalent to Python 2's :func:`unicode`; the " "C functions are called ``PyUnicode_*`` for both. The old 8-bit string type " "has become :func:`bytes`, with C functions called ``PyBytes_*``. Python 2.6 " "and later provide a compatibility header, :file:`bytesobject.h`, mapping " "``PyBytes`` names to ``PyString`` ones. For best compatibility with Python " "3, :c:type:`PyUnicode` should be used for textual data and :c:type:`PyBytes` " "for binary data. It's also important to remember that :c:type:`PyBytes` " "and :c:type:`PyUnicode` in Python 3 are not interchangeable like :c:type:" "`PyString` and :c:type:`PyUnicode` are in Python 2. The following example " "shows best practices with regards to :c:type:`PyUnicode`, :c:type:" "`PyString`, and :c:type:`PyBytes`. ::" msgstr "" #: ../Doc/howto/cporting.rst:95 msgid "long/int Unification" msgstr "" #: ../Doc/howto/cporting.rst:97 msgid "" "Python 3 has only one integer type, :func:`int`. But it actually " "corresponds to Python 2's :func:`long` type--the :func:`int` type used in " "Python 2 was removed. In the C-API, ``PyInt_*`` functions are replaced by " "their ``PyLong_*`` equivalents." msgstr "" #: ../Doc/howto/cporting.rst:104 msgid "Module initialization and state" msgstr "" #: ../Doc/howto/cporting.rst:106 msgid "" "Python 3 has a revamped extension module initialization system. (See :pep:" "`3121`.) Instead of storing module state in globals, they should be stored " "in an interpreter specific structure. Creating modules that act correctly " "in both Python 2 and Python 3 is tricky. The following simple example " "demonstrates how. ::" msgstr "" #: ../Doc/howto/cporting.rst:197 msgid "CObject replaced with Capsule" msgstr "" #: ../Doc/howto/cporting.rst:199 msgid "" "The :c:type:`Capsule` object was introduced in Python 3.1 and 2.7 to " "replace :c:type:`CObject`. CObjects were useful, but the :c:type:`CObject` " "API was problematic: it didn't permit distinguishing between valid CObjects, " "which allowed mismatched CObjects to crash the interpreter, and some of its " "APIs relied on undefined behavior in C. (For further reading on the " "rationale behind Capsules, please see :issue:`5630`.)" msgstr "" #: ../Doc/howto/cporting.rst:206 msgid "" "If you're currently using CObjects, and you want to migrate to 3.1 or newer, " "you'll need to switch to Capsules. :c:type:`CObject` was deprecated in 3.1 " "and 2.7 and completely removed in Python 3.2. If you only support 2.7, or " "3.1 and above, you can simply switch to :c:type:`Capsule`. If you need to " "support Python 3.0, or versions of Python earlier than 2.7, you'll have to " "support both CObjects and Capsules. (Note that Python 3.0 is no longer " "supported, and it is not recommended for production use.)" msgstr "" #: ../Doc/howto/cporting.rst:216 msgid "" "The following example header file :file:`capsulethunk.h` may solve the " "problem for you. Simply write your code against the :c:type:`Capsule` API " "and include this header file after :file:`Python.h`. Your code will " "automatically use Capsules in versions of Python with Capsules, and switch " "to CObjects when Capsules are unavailable." msgstr "" #: ../Doc/howto/cporting.rst:223 msgid "" ":file:`capsulethunk.h` simulates Capsules using CObjects. However, :c:type:" "`CObject` provides no place to store the capsule's \"name\". As a result " "the simulated :c:type:`Capsule` objects created by :file:`capsulethunk.h` " "behave slightly differently from real Capsules. Specifically:" msgstr "" #: ../Doc/howto/cporting.rst:228 msgid "The name parameter passed in to :c:func:`PyCapsule_New` is ignored." msgstr "" #: ../Doc/howto/cporting.rst:230 msgid "" "The name parameter passed in to :c:func:`PyCapsule_IsValid` and :c:func:" "`PyCapsule_GetPointer` is ignored, and no error checking of the name is " "performed." msgstr "" #: ../Doc/howto/cporting.rst:234 msgid ":c:func:`PyCapsule_GetName` always returns NULL." msgstr "" #: ../Doc/howto/cporting.rst:236 msgid "" ":c:func:`PyCapsule_SetName` always raises an exception and returns failure. " "(Since there's no way to store a name in a CObject, noisy failure of :c:func:" "`PyCapsule_SetName` was deemed preferable to silent failure here. If this " "is inconvenient, feel free to modify your local copy as you see fit.)" msgstr "" #: ../Doc/howto/cporting.rst:243 msgid "" "You can find :file:`capsulethunk.h` in the Python source distribution as :" "source:`Doc/includes/capsulethunk.h`. We also include it here for your " "convenience:" msgstr "" #: ../Doc/howto/cporting.rst:252 msgid "Other options" msgstr "" #: ../Doc/howto/cporting.rst:254 msgid "" "If you are writing a new extension module, you might consider `Cython " "`_. It translates a Python-like language to C. The " "extension modules it creates are compatible with Python 3 and Python 2." msgstr "" #: ../Doc/howto/curses.rst:5 msgid "Curses Programming with Python" msgstr "" #: ../Doc/howto/curses.rst:7 msgid "A.M. Kuchling, Eric S. Raymond" msgstr "" #: ../Doc/howto/curses.rst:8 msgid "2.04" msgstr "" #: ../Doc/howto/curses.rst:13 msgid "" "This document describes how to use the :mod:`curses` extension module to " "control text-mode displays." msgstr "" #: ../Doc/howto/curses.rst:18 msgid "What is curses?" msgstr "" #: ../Doc/howto/curses.rst:20 msgid "" "The curses library supplies a terminal-independent screen-painting and " "keyboard-handling facility for text-based terminals; such terminals include " "VT100s, the Linux console, and the simulated terminal provided by various " "programs. Display terminals support various control codes to perform common " "operations such as moving the cursor, scrolling the screen, and erasing " "areas. Different terminals use widely differing codes, and often have their " "own minor quirks." msgstr "" #: ../Doc/howto/curses.rst:28 msgid "" "In a world of graphical displays, one might ask \"why bother\"? It's true " "that character-cell display terminals are an obsolete technology, but there " "are niches in which being able to do fancy things with them are still " "valuable. One niche is on small-footprint or embedded Unixes that don't run " "an X server. Another is tools such as OS installers and kernel " "configurators that may have to run before any graphical support is available." msgstr "" #: ../Doc/howto/curses.rst:36 msgid "" "The curses library provides fairly basic functionality, providing the " "programmer with an abstraction of a display containing multiple non-" "overlapping windows of text. The contents of a window can be changed in " "various ways---adding text, erasing it, changing its appearance---and the " "curses library will figure out what control codes need to be sent to the " "terminal to produce the right output. curses doesn't provide many user-" "interface concepts such as buttons, checkboxes, or dialogs; if you need such " "features, consider a user interface library such as `Urwid `_." msgstr "" #: ../Doc/howto/curses.rst:46 msgid "" "The curses library was originally written for BSD Unix; the later System V " "versions of Unix from AT&T added many enhancements and new functions. BSD " "curses is no longer maintained, having been replaced by ncurses, which is an " "open-source implementation of the AT&T interface. If you're using an open-" "source Unix such as Linux or FreeBSD, your system almost certainly uses " "ncurses. Since most current commercial Unix versions are based on System V " "code, all the functions described here will probably be available. The " "older versions of curses carried by some proprietary Unixes may not support " "everything, though." msgstr "" #: ../Doc/howto/curses.rst:56 msgid "" "The Windows version of Python doesn't include the :mod:`curses` module. A " "ported version called `UniCurses `_ " "is available. You could also try `the Console module `_ written by Fredrik Lundh, which doesn't use the " "same API as curses but provides cursor-addressable text output and full " "support for mouse and keyboard input." msgstr "" #: ../Doc/howto/curses.rst:66 msgid "The Python curses module" msgstr "" #: ../Doc/howto/curses.rst:68 msgid "" "Thy Python module is a fairly simple wrapper over the C functions provided " "by curses; if you're already familiar with curses programming in C, it's " "really easy to transfer that knowledge to Python. The biggest difference is " "that the Python interface makes things simpler by merging different C " "functions such as :c:func:`addstr`, :c:func:`mvaddstr`, and :c:func:" "`mvwaddstr` into a single :meth:`~curses.window.addstr` method. You'll see " "this covered in more detail later." msgstr "" #: ../Doc/howto/curses.rst:76 msgid "" "This HOWTO is an introduction to writing text-mode programs with curses and " "Python. It doesn't attempt to be a complete guide to the curses API; for " "that, see the Python library guide's section on ncurses, and the C manual " "pages for ncurses. It will, however, give you the basic ideas." msgstr "" #: ../Doc/howto/curses.rst:83 msgid "Starting and ending a curses application" msgstr "" #: ../Doc/howto/curses.rst:85 msgid "" "Before doing anything, curses must be initialized. This is done by calling " "the :func:`~curses.initscr` function, which will determine the terminal " "type, send any required setup codes to the terminal, and create various " "internal data structures. If successful, :func:`initscr` returns a window " "object representing the entire screen; this is usually called ``stdscr`` " "after the name of the corresponding C variable. ::" msgstr "" #: ../Doc/howto/curses.rst:96 msgid "" "Usually curses applications turn off automatic echoing of keys to the " "screen, in order to be able to read keys and only display them under certain " "circumstances. This requires calling the :func:`~curses.noecho` function. ::" msgstr "" #: ../Doc/howto/curses.rst:103 msgid "" "Applications will also commonly need to react to keys instantly, without " "requiring the Enter key to be pressed; this is called cbreak mode, as " "opposed to the usual buffered input mode. ::" msgstr "" #: ../Doc/howto/curses.rst:109 msgid "" "Terminals usually return special keys, such as the cursor keys or navigation " "keys such as Page Up and Home, as a multibyte escape sequence. While you " "could write your application to expect such sequences and process them " "accordingly, curses can do it for you, returning a special value such as :" "const:`curses.KEY_LEFT`. To get curses to do the job, you'll have to enable " "keypad mode. ::" msgstr "" #: ../Doc/howto/curses.rst:118 msgid "" "Terminating a curses application is much easier than starting one. You'll " "need to call::" msgstr "" #: ../Doc/howto/curses.rst:125 msgid "" "to reverse the curses-friendly terminal settings. Then call the :func:" "`~curses.endwin` function to restore the terminal to its original operating " "mode. ::" msgstr "" #: ../Doc/howto/curses.rst:131 msgid "" "A common problem when debugging a curses application is to get your terminal " "messed up when the application dies without restoring the terminal to its " "previous state. In Python this commonly happens when your code is buggy and " "raises an uncaught exception. Keys are no longer echoed to the screen when " "you type them, for example, which makes using the shell difficult." msgstr "" #: ../Doc/howto/curses.rst:137 msgid "" "In Python you can avoid these complications and make debugging much easier " "by importing the :func:`curses.wrapper` function and using it like this::" msgstr "" #: ../Doc/howto/curses.rst:156 msgid "" "The :func:`~curses.wrapper` function takes a callable object and does the " "initializations described above, also initializing colors if color support " "is present. :func:`wrapper` then runs your provided callable. Once the " "callable returns, :func:`wrapper` will restore the original state of the " "terminal. The callable is called inside a :keyword:`try`...\\ :keyword:" "`except` that catches exceptions, restores the state of the terminal, and " "then re-raises the exception. Therefore your terminal won't be left in a " "funny state on exception and you'll be able to read the exception's message " "and traceback." msgstr "" #: ../Doc/howto/curses.rst:168 msgid "Windows and Pads" msgstr "" #: ../Doc/howto/curses.rst:170 msgid "" "Windows are the basic abstraction in curses. A window object represents a " "rectangular area of the screen, and supports methods to display text, erase " "it, allow the user to input strings, and so forth." msgstr "" #: ../Doc/howto/curses.rst:174 msgid "" "The ``stdscr`` object returned by the :func:`~curses.initscr` function is a " "window object that covers the entire screen. Many programs may need only " "this single window, but you might wish to divide the screen into smaller " "windows, in order to redraw or clear them separately. The :func:`~curses." "newwin` function creates a new window of a given size, returning the new " "window object. ::" msgstr "" #: ../Doc/howto/curses.rst:185 msgid "" "Note that the coordinate system used in curses is unusual. Coordinates are " "always passed in the order *y,x*, and the top-left corner of a window is " "coordinate (0,0). This breaks the normal convention for handling " "coordinates where the *x* coordinate comes first. This is an unfortunate " "difference from most other computer applications, but it's been part of " "curses since it was first written, and it's too late to change things now." msgstr "" #: ../Doc/howto/curses.rst:193 msgid "" "Your application can determine the size of the screen by using the :data:" "`curses.LINES` and :data:`curses.COLS` variables to obtain the *y* and *x* " "sizes. Legal coordinates will then extend from ``(0,0)`` to ``(curses.LINES " "- 1, curses.COLS - 1)``." msgstr "" #: ../Doc/howto/curses.rst:198 msgid "" "When you call a method to display or erase text, the effect doesn't " "immediately show up on the display. Instead you must call the :meth:" "`~curses.window.refresh` method of window objects to update the screen." msgstr "" #: ../Doc/howto/curses.rst:203 msgid "" "This is because curses was originally written with slow 300-baud terminal " "connections in mind; with these terminals, minimizing the time required to " "redraw the screen was very important. Instead curses accumulates changes to " "the screen and displays them in the most efficient manner when you call :" "meth:`refresh`. For example, if your program displays some text in a window " "and then clears the window, there's no need to send the original text " "because they're never visible." msgstr "" #: ../Doc/howto/curses.rst:212 msgid "" "In practice, explicitly telling curses to redraw a window doesn't really " "complicate programming with curses much. Most programs go into a flurry of " "activity, and then pause waiting for a keypress or some other action on the " "part of the user. All you have to do is to be sure that the screen has been " "redrawn before pausing to wait for user input, by first calling ``stdscr." "refresh()`` or the :meth:`refresh` method of some other relevant window." msgstr "" #: ../Doc/howto/curses.rst:220 msgid "" "A pad is a special case of a window; it can be larger than the actual " "display screen, and only a portion of the pad displayed at a time. Creating " "a pad requires the pad's height and width, while refreshing a pad requires " "giving the coordinates of the on-screen area where a subsection of the pad " "will be displayed. ::" msgstr "" #: ../Doc/howto/curses.rst:241 msgid "" "The :meth:`refresh` call displays a section of the pad in the rectangle " "extending from coordinate (5,5) to coordinate (20,75) on the screen; the " "upper left corner of the displayed section is coordinate (0,0) on the pad. " "Beyond that difference, pads are exactly like ordinary windows and support " "the same methods." msgstr "" #: ../Doc/howto/curses.rst:247 msgid "" "If you have multiple windows and pads on screen there is a more efficient " "way to update the screen and prevent annoying screen flicker as each part of " "the screen gets updated. :meth:`refresh` actually does two things:" msgstr "" #: ../Doc/howto/curses.rst:252 msgid "" "Calls the :meth:`~curses.window.noutrefresh` method of each window to update " "an underlying data structure representing the desired state of the screen." msgstr "" #: ../Doc/howto/curses.rst:255 msgid "" "Calls the function :func:`~curses.doupdate` function to change the physical " "screen to match the desired state recorded in the data structure." msgstr "" #: ../Doc/howto/curses.rst:258 msgid "" "Instead you can call :meth:`noutrefresh` on a number of windows to update " "the data structure, and then call :func:`doupdate` to update the screen." msgstr "" #: ../Doc/howto/curses.rst:264 msgid "Displaying Text" msgstr "" #: ../Doc/howto/curses.rst:266 msgid "" "From a C programmer's point of view, curses may sometimes look like a twisty " "maze of functions, all subtly different. For example, :c:func:`addstr` " "displays a string at the current cursor location in the ``stdscr`` window, " "while :c:func:`mvaddstr` moves to a given y,x coordinate first before " "displaying the string. :c:func:`waddstr` is just like :c:func:`addstr`, but " "allows specifying a window to use instead of using ``stdscr`` by default. :c:" "func:`mvwaddstr` allows specifying both a window and a coordinate." msgstr "" #: ../Doc/howto/curses.rst:275 msgid "" "Fortunately the Python interface hides all these details. ``stdscr`` is a " "window object like any other, and methods such as :meth:`~curses.window." "addstr` accept multiple argument forms. Usually there are four different " "forms." msgstr "" #: ../Doc/howto/curses.rst:281 msgid "Form" msgstr "" #: ../Doc/howto/curses.rst:281 ../Doc/howto/curses.rst:350 msgid "Description" msgstr "Description" #: ../Doc/howto/curses.rst:283 msgid "*str* or *ch*" msgstr "" #: ../Doc/howto/curses.rst:283 msgid "Display the string *str* or character *ch* at the current position" msgstr "" #: ../Doc/howto/curses.rst:286 msgid "*str* or *ch*, *attr*" msgstr "" #: ../Doc/howto/curses.rst:286 msgid "" "Display the string *str* or character *ch*, using attribute *attr* at the " "current position" msgstr "" #: ../Doc/howto/curses.rst:290 msgid "*y*, *x*, *str* or *ch*" msgstr "" #: ../Doc/howto/curses.rst:290 msgid "Move to position *y,x* within the window, and display *str* or *ch*" msgstr "" #: ../Doc/howto/curses.rst:293 msgid "*y*, *x*, *str* or *ch*, *attr*" msgstr "" #: ../Doc/howto/curses.rst:293 msgid "" "Move to position *y,x* within the window, and display *str* or *ch*, using " "attribute *attr*" msgstr "" #: ../Doc/howto/curses.rst:297 msgid "" "Attributes allow displaying text in highlighted forms such as boldface, " "underline, reverse code, or in color. They'll be explained in more detail " "in the next subsection." msgstr "" #: ../Doc/howto/curses.rst:302 msgid "" "The :meth:`~curses.window.addstr` method takes a Python string or bytestring " "as the value to be displayed. The contents of bytestrings are sent to the " "terminal as-is. Strings are encoded to bytes using the value of the " "window's :attr:`encoding` attribute; this defaults to the default system " "encoding as returned by :func:`locale.getpreferredencoding`." msgstr "" #: ../Doc/howto/curses.rst:309 msgid "" "The :meth:`~curses.window.addch` methods take a character, which can be " "either a string of length 1, a bytestring of length 1, or an integer." msgstr "" #: ../Doc/howto/curses.rst:312 msgid "" "Constants are provided for extension characters; these constants are " "integers greater than 255. For example, :const:`ACS_PLMINUS` is a +/- " "symbol, and :const:`ACS_ULCORNER` is the upper left corner of a box (handy " "for drawing borders). You can also use the appropriate Unicode character." msgstr "" #: ../Doc/howto/curses.rst:318 msgid "" "Windows remember where the cursor was left after the last operation, so if " "you leave out the *y,x* coordinates, the string or character will be " "displayed wherever the last operation left off. You can also move the " "cursor with the ``move(y,x)`` method. Because some terminals always display " "a flashing cursor, you may want to ensure that the cursor is positioned in " "some location where it won't be distracting; it can be confusing to have the " "cursor blinking at some apparently random location." msgstr "" #: ../Doc/howto/curses.rst:326 msgid "" "If your application doesn't need a blinking cursor at all, you can call " "``curs_set(False)`` to make it invisible. For compatibility with older " "curses versions, there's a ``leaveok(bool)`` function that's a synonym for :" "func:`~curses.curs_set`. When *bool* is true, the curses library will " "attempt to suppress the flashing cursor, and you won't need to worry about " "leaving it in odd locations." msgstr "" #: ../Doc/howto/curses.rst:335 msgid "Attributes and Color" msgstr "" #: ../Doc/howto/curses.rst:337 msgid "" "Characters can be displayed in different ways. Status lines in a text-based " "application are commonly shown in reverse video, or a text viewer may need " "to highlight certain words. curses supports this by allowing you to specify " "an attribute for each cell on the screen." msgstr "" #: ../Doc/howto/curses.rst:342 msgid "" "An attribute is an integer, each bit representing a different attribute. " "You can try to display text with multiple attribute bits set, but curses " "doesn't guarantee that all the possible combinations are available, or that " "they're all visually distinct. That depends on the ability of the terminal " "being used, so it's safest to stick to the most commonly available " "attributes, listed here." msgstr "" #: ../Doc/howto/curses.rst:350 msgid "Attribute" msgstr "" #: ../Doc/howto/curses.rst:352 msgid ":const:`A_BLINK`" msgstr "" #: ../Doc/howto/curses.rst:352 msgid "Blinking text" msgstr "" #: ../Doc/howto/curses.rst:354 msgid ":const:`A_BOLD`" msgstr "" #: ../Doc/howto/curses.rst:354 msgid "Extra bright or bold text" msgstr "" #: ../Doc/howto/curses.rst:356 msgid ":const:`A_DIM`" msgstr "" #: ../Doc/howto/curses.rst:356 msgid "Half bright text" msgstr "" #: ../Doc/howto/curses.rst:358 msgid ":const:`A_REVERSE`" msgstr "" #: ../Doc/howto/curses.rst:358 msgid "Reverse-video text" msgstr "" #: ../Doc/howto/curses.rst:360 msgid ":const:`A_STANDOUT`" msgstr "" #: ../Doc/howto/curses.rst:360 msgid "The best highlighting mode available" msgstr "" #: ../Doc/howto/curses.rst:362 msgid ":const:`A_UNDERLINE`" msgstr "" #: ../Doc/howto/curses.rst:362 msgid "Underlined text" msgstr "" #: ../Doc/howto/curses.rst:365 msgid "" "So, to display a reverse-video status line on the top line of the screen, " "you could code::" msgstr "" #: ../Doc/howto/curses.rst:372 msgid "" "The curses library also supports color on those terminals that provide it. " "The most common such terminal is probably the Linux console, followed by " "color xterms." msgstr "" #: ../Doc/howto/curses.rst:376 msgid "" "To use color, you must call the :func:`~curses.start_color` function soon " "after calling :func:`~curses.initscr`, to initialize the default color set " "(the :func:`curses.wrapper` function does this automatically). Once that's " "done, the :func:`~curses.has_colors` function returns TRUE if the terminal " "in use can actually display color. (Note: curses uses the American spelling " "'color', instead of the Canadian/British spelling 'colour'. If you're used " "to the British spelling, you'll have to resign yourself to misspelling it " "for the sake of these functions.)" msgstr "" #: ../Doc/howto/curses.rst:386 msgid "" "The curses library maintains a finite number of color pairs, containing a " "foreground (or text) color and a background color. You can get the " "attribute value corresponding to a color pair with the :func:`~curses." "color_pair` function; this can be bitwise-OR'ed with other attributes such " "as :const:`A_REVERSE`, but again, such combinations are not guaranteed to " "work on all terminals." msgstr "" #: ../Doc/howto/curses.rst:393 msgid "An example, which displays a line of text using color pair 1::" msgstr "" #: ../Doc/howto/curses.rst:398 msgid "" "As I said before, a color pair consists of a foreground and background " "color. The ``init_pair(n, f, b)`` function changes the definition of color " "pair *n*, to foreground color f and background color b. Color pair 0 is " "hard-wired to white on black, and cannot be changed." msgstr "" #: ../Doc/howto/curses.rst:403 msgid "" "Colors are numbered, and :func:`start_color` initializes 8 basic colors when " "it activates color mode. They are: 0:black, 1:red, 2:green, 3:yellow, 4:" "blue, 5:magenta, 6:cyan, and 7:white. The :mod:`curses` module defines " "named constants for each of these colors: :const:`curses.COLOR_BLACK`, :" "const:`curses.COLOR_RED`, and so forth." msgstr "" #: ../Doc/howto/curses.rst:409 msgid "" "Let's put all this together. To change color 1 to red text on a white " "background, you would call::" msgstr "" #: ../Doc/howto/curses.rst:414 msgid "" "When you change a color pair, any text already displayed using that color " "pair will change to the new colors. You can also display new text in this " "color with::" msgstr "" #: ../Doc/howto/curses.rst:420 msgid "" "Very fancy terminals can change the definitions of the actual colors to a " "given RGB value. This lets you change color 1, which is usually red, to " "purple or blue or any other color you like. Unfortunately, the Linux " "console doesn't support this, so I'm unable to try it out, and can't provide " "any examples. You can check if your terminal can do this by calling :func:" "`~curses.can_change_color`, which returns ``True`` if the capability is " "there. If you're lucky enough to have such a talented terminal, consult " "your system's man pages for more information." msgstr "" #: ../Doc/howto/curses.rst:431 msgid "User Input" msgstr "" #: ../Doc/howto/curses.rst:433 msgid "" "The C curses library offers only very simple input mechanisms. Python's :mod:" "`curses` module adds a basic text-input widget. (Other libraries such as " "`Urwid `_ have more extensive " "collections of widgets.)" msgstr "" #: ../Doc/howto/curses.rst:438 msgid "There are two methods for getting input from a window:" msgstr "" #: ../Doc/howto/curses.rst:440 msgid "" ":meth:`~curses.window.getch` refreshes the screen and then waits for the " "user to hit a key, displaying the key if :func:`~curses.echo` has been " "called earlier. You can optionally specify a coordinate to which the cursor " "should be moved before pausing." msgstr "" #: ../Doc/howto/curses.rst:445 msgid "" ":meth:`~curses.window.getkey` does the same thing but converts the integer " "to a string. Individual characters are returned as 1-character strings, and " "special keys such as function keys return longer strings containing a key " "name such as ``KEY_UP`` or ``^G``." msgstr "" #: ../Doc/howto/curses.rst:450 msgid "" "It's possible to not wait for the user using the :meth:`~curses.window." "nodelay` window method. After ``nodelay(True)``, :meth:`getch` and :meth:" "`getkey` for the window become non-blocking. To signal that no input is " "ready, :meth:`getch` returns ``curses.ERR`` (a value of -1) and :meth:" "`getkey` raises an exception. There's also a :func:`~curses.halfdelay` " "function, which can be used to (in effect) set a timer on each :meth:" "`getch`; if no input becomes available within a specified delay (measured in " "tenths of a second), curses raises an exception." msgstr "" #: ../Doc/howto/curses.rst:460 msgid "" "The :meth:`getch` method returns an integer; if it's between 0 and 255, it " "represents the ASCII code of the key pressed. Values greater than 255 are " "special keys such as Page Up, Home, or the cursor keys. You can compare the " "value returned to constants such as :const:`curses.KEY_PPAGE`, :const:" "`curses.KEY_HOME`, or :const:`curses.KEY_LEFT`. The main loop of your " "program may look something like this::" msgstr "" #: ../Doc/howto/curses.rst:476 msgid "" "The :mod:`curses.ascii` module supplies ASCII class membership functions " "that take either integer or 1-character string arguments; these may be " "useful in writing more readable tests for such loops. It also supplies " "conversion functions that take either integer or 1-character-string " "arguments and return the same type. For example, :func:`curses.ascii.ctrl` " "returns the control character corresponding to its argument." msgstr "" #: ../Doc/howto/curses.rst:483 msgid "" "There's also a method to retrieve an entire string, :meth:`~curses.window." "getstr`. It isn't used very often, because its functionality is quite " "limited; the only editing keys available are the backspace key and the Enter " "key, which terminates the string. It can optionally be limited to a fixed " "number of characters. ::" msgstr "" #: ../Doc/howto/curses.rst:494 msgid "" "The :mod:`curses.textpad` module supplies a text box that supports an Emacs-" "like set of keybindings. Various methods of the :class:`~curses.textpad." "Textbox` class support editing with input validation and gathering the edit " "results either with or without trailing spaces. Here's an example::" msgstr "" #: ../Doc/howto/curses.rst:518 msgid "" "See the library documentation on :mod:`curses.textpad` for more details." msgstr "" #: ../Doc/howto/curses.rst:522 msgid "For More Information" msgstr "" #: ../Doc/howto/curses.rst:524 msgid "" "This HOWTO doesn't cover some advanced topics, such as reading the contents " "of the screen or capturing mouse events from an xterm instance, but the " "Python library page for the :mod:`curses` module is now reasonably " "complete. You should browse it next." msgstr "" #: ../Doc/howto/curses.rst:529 msgid "" "If you're in doubt about the detailed behavior of the curses functions, " "consult the manual pages for your curses implementation, whether it's " "ncurses or a proprietary Unix vendor's. The manual pages will document any " "quirks, and provide complete lists of all the functions, attributes, and :" "const:`ACS_\\*` characters available to you." msgstr "" #: ../Doc/howto/curses.rst:536 msgid "" "Because the curses API is so large, some functions aren't supported in the " "Python interface. Often this isn't because they're difficult to implement, " "but because no one has needed them yet. Also, Python doesn't yet support " "the menu library associated with ncurses. Patches adding support for these " "would be welcome; see `the Python Developer's Guide `_ to learn more about submitting patches to Python." msgstr "" #: ../Doc/howto/curses.rst:544 msgid "" "`Writing Programs with NCURSES `_: a lengthy tutorial for C programmers." msgstr "" #: ../Doc/howto/curses.rst:546 msgid "`The ncurses man page `_" msgstr "" #: ../Doc/howto/curses.rst:547 msgid "" "`The ncurses FAQ `_" msgstr "" #: ../Doc/howto/curses.rst:548 msgid "" "`\"Use curses... don't swear\" `_: video of a PyCon 2013 talk on controlling terminals using " "curses or Urwid." msgstr "" #: ../Doc/howto/curses.rst:550 msgid "" "`\"Console Applications with Urwid\" `_: video of a PyCon CA 2012 talk " "demonstrating some applications written using Urwid." msgstr "" #: ../Doc/howto/descriptor.rst:3 msgid "Descriptor HowTo Guide" msgstr "" #: ../Doc/howto/descriptor.rst:5 msgid "Raymond Hettinger" msgstr "" #: ../Doc/howto/descriptor.rst:6 msgid "" msgstr "" #: ../Doc/howto/descriptor.rst:0 msgid "Contents" msgstr "" #: ../Doc/howto/descriptor.rst:13 msgid "" "Defines descriptors, summarizes the protocol, and shows how descriptors are " "called. Examines a custom descriptor and several built-in python " "descriptors including functions, properties, static methods, and class " "methods. Shows how each works by giving a pure Python equivalent and a " "sample application." msgstr "" #: ../Doc/howto/descriptor.rst:18 msgid "" "Learning about descriptors not only provides access to a larger toolset, it " "creates a deeper understanding of how Python works and an appreciation for " "the elegance of its design." msgstr "" #: ../Doc/howto/descriptor.rst:24 msgid "Definition and Introduction" msgstr "" #: ../Doc/howto/descriptor.rst:26 msgid "" "In general, a descriptor is an object attribute with \"binding behavior\", " "one whose attribute access has been overridden by methods in the descriptor " "protocol. Those methods are :meth:`__get__`, :meth:`__set__`, and :meth:" "`__delete__`. If any of those methods are defined for an object, it is said " "to be a descriptor." msgstr "" #: ../Doc/howto/descriptor.rst:32 msgid "" "The default behavior for attribute access is to get, set, or delete the " "attribute from an object's dictionary. For instance, ``a.x`` has a lookup " "chain starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and " "continuing through the base classes of ``type(a)`` excluding metaclasses. If " "the looked-up value is an object defining one of the descriptor methods, " "then Python may override the default behavior and invoke the descriptor " "method instead. Where this occurs in the precedence chain depends on which " "descriptor methods were defined." msgstr "" #: ../Doc/howto/descriptor.rst:41 msgid "" "Descriptors are a powerful, general purpose protocol. They are the " "mechanism behind properties, methods, static methods, class methods, and :" "func:`super()`. They are used throughout Python itself to implement the new " "style classes introduced in version 2.2. Descriptors simplify the " "underlying C-code and offer a flexible set of new tools for everyday Python " "programs." msgstr "" #: ../Doc/howto/descriptor.rst:49 msgid "Descriptor Protocol" msgstr "" #: ../Doc/howto/descriptor.rst:51 msgid "``descr.__get__(self, obj, type=None) --> value``" msgstr "" #: ../Doc/howto/descriptor.rst:53 msgid "``descr.__set__(self, obj, value) --> None``" msgstr "" #: ../Doc/howto/descriptor.rst:55 msgid "``descr.__delete__(self, obj) --> None``" msgstr "" #: ../Doc/howto/descriptor.rst:57 msgid "" "That is all there is to it. Define any of these methods and an object is " "considered a descriptor and can override default behavior upon being looked " "up as an attribute." msgstr "" #: ../Doc/howto/descriptor.rst:61 msgid "" "If an object defines both :meth:`__get__` and :meth:`__set__`, it is " "considered a data descriptor. Descriptors that only define :meth:`__get__` " "are called non-data descriptors (they are typically used for methods but " "other uses are possible)." msgstr "" #: ../Doc/howto/descriptor.rst:66 msgid "" "Data and non-data descriptors differ in how overrides are calculated with " "respect to entries in an instance's dictionary. If an instance's dictionary " "has an entry with the same name as a data descriptor, the data descriptor " "takes precedence. If an instance's dictionary has an entry with the same " "name as a non-data descriptor, the dictionary entry takes precedence." msgstr "" #: ../Doc/howto/descriptor.rst:72 msgid "" "To make a read-only data descriptor, define both :meth:`__get__` and :meth:" "`__set__` with the :meth:`__set__` raising an :exc:`AttributeError` when " "called. Defining the :meth:`__set__` method with an exception raising " "placeholder is enough to make it a data descriptor." msgstr "" #: ../Doc/howto/descriptor.rst:79 msgid "Invoking Descriptors" msgstr "" #: ../Doc/howto/descriptor.rst:81 msgid "" "A descriptor can be called directly by its method name. For example, ``d." "__get__(obj)``." msgstr "" #: ../Doc/howto/descriptor.rst:84 msgid "" "Alternatively, it is more common for a descriptor to be invoked " "automatically upon attribute access. For example, ``obj.d`` looks up ``d`` " "in the dictionary of ``obj``. If ``d`` defines the method :meth:`__get__`, " "then ``d.__get__(obj)`` is invoked according to the precedence rules listed " "below." msgstr "" #: ../Doc/howto/descriptor.rst:89 msgid "" "The details of invocation depend on whether ``obj`` is an object or a class." msgstr "" #: ../Doc/howto/descriptor.rst:91 msgid "" "For objects, the machinery is in :meth:`object.__getattribute__` which " "transforms ``b.x`` into ``type(b).__dict__['x'].__get__(b, type(b))``. The " "implementation works through a precedence chain that gives data descriptors " "priority over instance variables, instance variables priority over non-data " "descriptors, and assigns lowest priority to :meth:`__getattr__` if provided. " "The full C implementation can be found in :c:func:" "`PyObject_GenericGetAttr()` in :source:`Objects/object.c`." msgstr "" #: ../Doc/howto/descriptor.rst:99 msgid "" "For classes, the machinery is in :meth:`type.__getattribute__` which " "transforms ``B.x`` into ``B.__dict__['x'].__get__(None, B)``. In pure " "Python, it looks like::" msgstr "" #: ../Doc/howto/descriptor.rst:110 msgid "The important points to remember are:" msgstr "" #: ../Doc/howto/descriptor.rst:112 msgid "descriptors are invoked by the :meth:`__getattribute__` method" msgstr "" #: ../Doc/howto/descriptor.rst:113 msgid "overriding :meth:`__getattribute__` prevents automatic descriptor calls" msgstr "" #: ../Doc/howto/descriptor.rst:114 msgid "" ":meth:`object.__getattribute__` and :meth:`type.__getattribute__` make " "different calls to :meth:`__get__`." msgstr "" #: ../Doc/howto/descriptor.rst:116 msgid "data descriptors always override instance dictionaries." msgstr "" #: ../Doc/howto/descriptor.rst:117 msgid "non-data descriptors may be overridden by instance dictionaries." msgstr "" #: ../Doc/howto/descriptor.rst:119 msgid "" "The object returned by ``super()`` also has a custom :meth:" "`__getattribute__` method for invoking descriptors. The call ``super(B, " "obj).m()`` searches ``obj.__class__.__mro__`` for the base class ``A`` " "immediately following ``B`` and then returns ``A.__dict__['m'].__get__(obj, " "B)``. If not a descriptor, ``m`` is returned unchanged. If not in the " "dictionary, ``m`` reverts to a search using :meth:`object.__getattribute__`." msgstr "" #: ../Doc/howto/descriptor.rst:126 msgid "" "The implementation details are in :c:func:`super_getattro()` in :source:" "`Objects/typeobject.c`. and a pure Python equivalent can be found in " "`Guido's Tutorial`_." msgstr "" #: ../Doc/howto/descriptor.rst:132 msgid "" "The details above show that the mechanism for descriptors is embedded in " "the :meth:`__getattribute__()` methods for :class:`object`, :class:`type`, " "and :func:`super`. Classes inherit this machinery when they derive from :" "class:`object` or if they have a meta-class providing similar functionality. " "Likewise, classes can turn-off descriptor invocation by overriding :meth:" "`__getattribute__()`." msgstr "" #: ../Doc/howto/descriptor.rst:141 msgid "Descriptor Example" msgstr "" #: ../Doc/howto/descriptor.rst:143 msgid "" "The following code creates a class whose objects are data descriptors which " "print a message for each get or set. Overriding :meth:`__getattribute__` is " "alternate approach that could do this for every attribute. However, this " "descriptor is useful for monitoring just a few chosen attributes::" msgstr "" #: ../Doc/howto/descriptor.rst:181 msgid "" "The protocol is simple and offers exciting possibilities. Several use cases " "are so common that they have been packaged into individual function calls. " "Properties, bound and unbound methods, static methods, and class methods are " "all based on the descriptor protocol." msgstr "" #: ../Doc/howto/descriptor.rst:188 msgid "Properties" msgstr "" #: ../Doc/howto/descriptor.rst:190 msgid "" "Calling :func:`property` is a succinct way of building a data descriptor " "that triggers function calls upon access to an attribute. Its signature is::" msgstr "" #: ../Doc/howto/descriptor.rst:195 msgid "" "The documentation shows a typical use to define a managed attribute ``x``::" msgstr "" #: ../Doc/howto/descriptor.rst:203 msgid "" "To see how :func:`property` is implemented in terms of the descriptor " "protocol, here is a pure Python equivalent::" msgstr "" #: ../Doc/howto/descriptor.rst:243 msgid "" "The :func:`property` builtin helps whenever a user interface has granted " "attribute access and then subsequent changes require the intervention of a " "method." msgstr "" #: ../Doc/howto/descriptor.rst:247 msgid "" "For instance, a spreadsheet class may grant access to a cell value through " "``Cell('b10').value``. Subsequent improvements to the program require the " "cell to be recalculated on every access; however, the programmer does not " "want to affect existing client code accessing the attribute directly. The " "solution is to wrap access to the value attribute in a property data " "descriptor::" msgstr "" #: ../Doc/howto/descriptor.rst:263 msgid "Functions and Methods" msgstr "" #: ../Doc/howto/descriptor.rst:265 msgid "" "Python's object oriented features are built upon a function based " "environment. Using non-data descriptors, the two are merged seamlessly." msgstr "" #: ../Doc/howto/descriptor.rst:268 msgid "" "Class dictionaries store methods as functions. In a class definition, " "methods are written using :keyword:`def` and :keyword:`lambda`, the usual " "tools for creating functions. The only difference from regular functions is " "that the first argument is reserved for the object instance. By Python " "convention, the instance reference is called *self* but may be called *this* " "or any other variable name." msgstr "" #: ../Doc/howto/descriptor.rst:275 msgid "" "To support method calls, functions include the :meth:`__get__` method for " "binding methods during attribute access. This means that all functions are " "non-data descriptors which return bound or unbound methods depending whether " "they are invoked from an object or a class. In pure python, it works like " "this::" msgstr "" #: ../Doc/howto/descriptor.rst:287 msgid "" "Running the interpreter shows how the function descriptor works in practice::" msgstr "" #: ../Doc/howto/descriptor.rst:301 msgid "" "The output suggests that bound and unbound methods are two different types. " "While they could have been implemented that way, the actual C implementation " "of :c:type:`PyMethod_Type` in :source:`Objects/classobject.c` is a single " "object with two different representations depending on whether the :attr:" "`im_self` field is set or is *NULL* (the C equivalent of *None*)." msgstr "" #: ../Doc/howto/descriptor.rst:307 msgid "" "Likewise, the effects of calling a method object depend on the :attr:" "`im_self` field. If set (meaning bound), the original function (stored in " "the :attr:`im_func` field) is called as expected with the first argument set " "to the instance. If unbound, all of the arguments are passed unchanged to " "the original function. The actual C implementation of :func:" "`instancemethod_call()` is only slightly more complex in that it includes " "some type checking." msgstr "" #: ../Doc/howto/descriptor.rst:316 msgid "Static Methods and Class Methods" msgstr "" #: ../Doc/howto/descriptor.rst:318 msgid "" "Non-data descriptors provide a simple mechanism for variations on the usual " "patterns of binding functions into methods." msgstr "" #: ../Doc/howto/descriptor.rst:321 msgid "" "To recap, functions have a :meth:`__get__` method so that they can be " "converted to a method when accessed as attributes. The non-data descriptor " "transforms an ``obj.f(*args)`` call into ``f(obj, *args)``. Calling ``klass." "f(*args)`` becomes ``f(*args)``." msgstr "" #: ../Doc/howto/descriptor.rst:326 msgid "This chart summarizes the binding and its two most useful variants:" msgstr "" #: ../Doc/howto/descriptor.rst:329 msgid "Transformation" msgstr "" #: ../Doc/howto/descriptor.rst:329 msgid "Called from an Object" msgstr "" #: ../Doc/howto/descriptor.rst:329 msgid "Called from a Class" msgstr "" #: ../Doc/howto/descriptor.rst:332 msgid "function" msgstr "fonction" #: ../Doc/howto/descriptor.rst:332 msgid "f(obj, \\*args)" msgstr "" #: ../Doc/howto/descriptor.rst:332 ../Doc/howto/descriptor.rst:334 msgid "f(\\*args)" msgstr "" #: ../Doc/howto/descriptor.rst:334 msgid "staticmethod" msgstr "" #: ../Doc/howto/descriptor.rst:336 msgid "classmethod" msgstr "" #: ../Doc/howto/descriptor.rst:336 msgid "f(type(obj), \\*args)" msgstr "" #: ../Doc/howto/descriptor.rst:336 msgid "f(klass, \\*args)" msgstr "" #: ../Doc/howto/descriptor.rst:339 msgid "" "Static methods return the underlying function without changes. Calling " "either ``c.f`` or ``C.f`` is the equivalent of a direct lookup into ``object." "__getattribute__(c, \"f\")`` or ``object.__getattribute__(C, \"f\")``. As a " "result, the function becomes identically accessible from either an object or " "a class." msgstr "" #: ../Doc/howto/descriptor.rst:345 msgid "" "Good candidates for static methods are methods that do not reference the " "``self`` variable." msgstr "" #: ../Doc/howto/descriptor.rst:348 msgid "" "For instance, a statistics package may include a container class for " "experimental data. The class provides normal methods for computing the " "average, mean, median, and other descriptive statistics that depend on the " "data. However, there may be useful functions which are conceptually related " "but do not depend on the data. For instance, ``erf(x)`` is handy conversion " "routine that comes up in statistical work but does not directly depend on a " "particular dataset. It can be called either from an object or the class: " "``s.erf(1.5) --> .9332`` or ``Sample.erf(1.5) --> .9332``." msgstr "" #: ../Doc/howto/descriptor.rst:357 msgid "" "Since staticmethods return the underlying function with no changes, the " "example calls are unexciting::" msgstr "" #: ../Doc/howto/descriptor.rst:370 msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`staticmethod` would look like this::" msgstr "" #: ../Doc/howto/descriptor.rst:382 msgid "" "Unlike static methods, class methods prepend the class reference to the " "argument list before calling the function. This format is the same for " "whether the caller is an object or a class::" msgstr "" #: ../Doc/howto/descriptor.rst:397 msgid "" "This behavior is useful whenever the function only needs to have a class " "reference and does not care about any underlying data. One use for " "classmethods is to create alternate class constructors. In Python 2.3, the " "classmethod :func:`dict.fromkeys` creates a new dictionary from a list of " "keys. The pure Python equivalent is::" msgstr "" #: ../Doc/howto/descriptor.rst:413 msgid "Now a new dictionary of unique keys can be constructed like this::" msgstr "" #: ../Doc/howto/descriptor.rst:418 msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`classmethod` would look like this::" msgstr "" #: ../Doc/howto/functional.rst:3 msgid "Functional Programming HOWTO" msgstr "" #: ../Doc/howto/functional.rst:5 msgid "A. M. Kuchling" msgstr "" #: ../Doc/howto/functional.rst:6 msgid "0.32" msgstr "" #: ../Doc/howto/functional.rst:8 msgid "" "In this document, we'll take a tour of Python's features suitable for " "implementing programs in a functional style. After an introduction to the " "concepts of functional programming, we'll look at language features such as :" "term:`iterator`\\s and :term:`generator`\\s and relevant library modules " "such as :mod:`itertools` and :mod:`functools`." msgstr "" #: ../Doc/howto/functional.rst:16 ../Doc/howto/regex.rst:24 #: ../Doc/howto/urllib2.rst:18 msgid "Introduction" msgstr "Introduction" #: ../Doc/howto/functional.rst:18 msgid "" "This section explains the basic concept of functional programming; if you're " "just interested in learning about Python language features, skip to the next " "section on :ref:`functional-howto-iterators`." msgstr "" #: ../Doc/howto/functional.rst:22 msgid "" "Programming languages support decomposing problems in several different ways:" msgstr "" #: ../Doc/howto/functional.rst:24 msgid "" "Most programming languages are **procedural**: programs are lists of " "instructions that tell the computer what to do with the program's input. C, " "Pascal, and even Unix shells are procedural languages." msgstr "" #: ../Doc/howto/functional.rst:28 msgid "" "In **declarative** languages, you write a specification that describes the " "problem to be solved, and the language implementation figures out how to " "perform the computation efficiently. SQL is the declarative language you're " "most likely to be familiar with; a SQL query describes the data set you want " "to retrieve, and the SQL engine decides whether to scan tables or use " "indexes, which subclauses should be performed first, etc." msgstr "" #: ../Doc/howto/functional.rst:35 msgid "" "**Object-oriented** programs manipulate collections of objects. Objects " "have internal state and support methods that query or modify this internal " "state in some way. Smalltalk and Java are object-oriented languages. C++ " "and Python are languages that support object-oriented programming, but don't " "force the use of object-oriented features." msgstr "" #: ../Doc/howto/functional.rst:41 msgid "" "**Functional** programming decomposes a problem into a set of functions. " "Ideally, functions only take inputs and produce outputs, and don't have any " "internal state that affects the output produced for a given input. Well-" "known functional languages include the ML family (Standard ML, OCaml, and " "other variants) and Haskell." msgstr "" #: ../Doc/howto/functional.rst:47 msgid "" "The designers of some computer languages choose to emphasize one particular " "approach to programming. This often makes it difficult to write programs " "that use a different approach. Other languages are multi-paradigm languages " "that support several different approaches. Lisp, C++, and Python are multi-" "paradigm; you can write programs or libraries that are largely procedural, " "object-oriented, or functional in all of these languages. In a large " "program, different sections might be written using different approaches; the " "GUI might be object-oriented while the processing logic is procedural or " "functional, for example." msgstr "" #: ../Doc/howto/functional.rst:58 msgid "" "In a functional program, input flows through a set of functions. Each " "function operates on its input and produces some output. Functional style " "discourages functions with side effects that modify internal state or make " "other changes that aren't visible in the function's return value. Functions " "that have no side effects at all are called **purely functional**. Avoiding " "side effects means not using data structures that get updated as a program " "runs; every function's output must only depend on its input." msgstr "" #: ../Doc/howto/functional.rst:66 msgid "" "Some languages are very strict about purity and don't even have assignment " "statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all " "side effects. Printing to the screen or writing to a disk file are side " "effects, for example. For example, in Python a call to the :func:`print` " "or :func:`time.sleep` function both return no useful value; they're only " "called for their side effects of sending some text to the screen or pausing " "execution for a second." msgstr "" #: ../Doc/howto/functional.rst:74 msgid "" "Python programs written in functional style usually won't go to the extreme " "of avoiding all I/O or all assignments; instead, they'll provide a " "functional-appearing interface but will use non-functional features " "internally. For example, the implementation of a function will still use " "assignments to local variables, but won't modify global variables or have " "other side effects." msgstr "" #: ../Doc/howto/functional.rst:80 msgid "" "Functional programming can be considered the opposite of object-oriented " "programming. Objects are little capsules containing some internal state " "along with a collection of method calls that let you modify this state, and " "programs consist of making the right set of state changes. Functional " "programming wants to avoid state changes as much as possible and works with " "data flowing between functions. In Python you might combine the two " "approaches by writing functions that take and return instances representing " "objects in your application (e-mail messages, transactions, etc.)." msgstr "" #: ../Doc/howto/functional.rst:89 msgid "" "Functional design may seem like an odd constraint to work under. Why should " "you avoid objects and side effects? There are theoretical and practical " "advantages to the functional style:" msgstr "" #: ../Doc/howto/functional.rst:93 msgid "Formal provability." msgstr "" #: ../Doc/howto/functional.rst:94 msgid "Modularity." msgstr "" #: ../Doc/howto/functional.rst:95 msgid "Composability." msgstr "" #: ../Doc/howto/functional.rst:96 msgid "Ease of debugging and testing." msgstr "" #: ../Doc/howto/functional.rst:100 msgid "Formal provability" msgstr "" #: ../Doc/howto/functional.rst:102 msgid "" "A theoretical benefit is that it's easier to construct a mathematical proof " "that a functional program is correct." msgstr "" #: ../Doc/howto/functional.rst:105 msgid "" "For a long time researchers have been interested in finding ways to " "mathematically prove programs correct. This is different from testing a " "program on numerous inputs and concluding that its output is usually " "correct, or reading a program's source code and concluding that the code " "looks right; the goal is instead a rigorous proof that a program produces " "the right result for all possible inputs." msgstr "" #: ../Doc/howto/functional.rst:112 msgid "" "The technique used to prove programs correct is to write down " "**invariants**, properties of the input data and of the program's variables " "that are always true. For each line of code, you then show that if " "invariants X and Y are true **before** the line is executed, the slightly " "different invariants X' and Y' are true **after** the line is executed. " "This continues until you reach the end of the program, at which point the " "invariants should match the desired conditions on the program's output." msgstr "" #: ../Doc/howto/functional.rst:120 msgid "" "Functional programming's avoidance of assignments arose because assignments " "are difficult to handle with this technique; assignments can break " "invariants that were true before the assignment without producing any new " "invariants that can be propagated onward." msgstr "" #: ../Doc/howto/functional.rst:125 msgid "" "Unfortunately, proving programs correct is largely impractical and not " "relevant to Python software. Even trivial programs require proofs that are " "several pages long; the proof of correctness for a moderately complicated " "program would be enormous, and few or none of the programs you use daily " "(the Python interpreter, your XML parser, your web browser) could be proven " "correct. Even if you wrote down or generated a proof, there would then be " "the question of verifying the proof; maybe there's an error in it, and you " "wrongly believe you've proved the program correct." msgstr "" #: ../Doc/howto/functional.rst:136 msgid "Modularity" msgstr "" #: ../Doc/howto/functional.rst:138 msgid "" "A more practical benefit of functional programming is that it forces you to " "break apart your problem into small pieces. Programs are more modular as a " "result. It's easier to specify and write a small function that does one " "thing than a large function that performs a complicated transformation. " "Small functions are also easier to read and to check for errors." msgstr "" #: ../Doc/howto/functional.rst:146 msgid "Ease of debugging and testing" msgstr "" #: ../Doc/howto/functional.rst:148 msgid "Testing and debugging a functional-style program is easier." msgstr "" #: ../Doc/howto/functional.rst:150 msgid "" "Debugging is simplified because functions are generally small and clearly " "specified. When a program doesn't work, each function is an interface point " "where you can check that the data are correct. You can look at the " "intermediate inputs and outputs to quickly isolate the function that's " "responsible for a bug." msgstr "" #: ../Doc/howto/functional.rst:155 msgid "" "Testing is easier because each function is a potential subject for a unit " "test. Functions don't depend on system state that needs to be replicated " "before running a test; instead you only have to synthesize the right input " "and then check that the output matches expectations." msgstr "" #: ../Doc/howto/functional.rst:162 msgid "Composability" msgstr "" #: ../Doc/howto/functional.rst:164 msgid "" "As you work on a functional-style program, you'll write a number of " "functions with varying inputs and outputs. Some of these functions will be " "unavoidably specialized to a particular application, but others will be " "useful in a wide variety of programs. For example, a function that takes a " "directory path and returns all the XML files in the directory, or a function " "that takes a filename and returns its contents, can be applied to many " "different situations." msgstr "" #: ../Doc/howto/functional.rst:171 msgid "" "Over time you'll form a personal library of utilities. Often you'll " "assemble new programs by arranging existing functions in a new configuration " "and writing a few functions specialized for the current task." msgstr "" #: ../Doc/howto/functional.rst:179 msgid "Iterators" msgstr "Itérateurs" #: ../Doc/howto/functional.rst:181 msgid "" "I'll start by looking at a Python language feature that's an important " "foundation for writing functional-style programs: iterators." msgstr "" #: ../Doc/howto/functional.rst:184 msgid "" "An iterator is an object representing a stream of data; this object returns " "the data one element at a time. A Python iterator must support a method " "called :meth:`~iterator.__next__` that takes no arguments and always returns " "the next element of the stream. If there are no more elements in the " "stream, :meth:`~iterator.__next__` must raise the :exc:`StopIteration` " "exception. Iterators don't have to be finite, though; it's perfectly " "reasonable to write an iterator that produces an infinite stream of data." msgstr "" #: ../Doc/howto/functional.rst:192 msgid "" "The built-in :func:`iter` function takes an arbitrary object and tries to " "return an iterator that will return the object's contents or elements, " "raising :exc:`TypeError` if the object doesn't support iteration. Several " "of Python's built-in data types support iteration, the most common being " "lists and dictionaries. An object is called :term:`iterable` if you can get " "an iterator for it." msgstr "" #: ../Doc/howto/functional.rst:199 msgid "You can experiment with the iteration interface manually:" msgstr "" #: ../Doc/howto/functional.rst:217 msgid "" "Python expects iterable objects in several different contexts, the most " "important being the :keyword:`for` statement. In the statement ``for X in " "Y``, Y must be an iterator or some object for which :func:`iter` can create " "an iterator. These two statements are equivalent::" msgstr "" #: ../Doc/howto/functional.rst:229 msgid "" "Iterators can be materialized as lists or tuples by using the :func:`list` " "or :func:`tuple` constructor functions:" msgstr "" #: ../Doc/howto/functional.rst:238 msgid "" "Sequence unpacking also supports iterators: if you know an iterator will " "return N elements, you can unpack them into an N-tuple:" msgstr "" #: ../Doc/howto/functional.rst:247 msgid "" "Built-in functions such as :func:`max` and :func:`min` can take a single " "iterator argument and will return the largest or smallest element. The ``" "\"in\"`` and ``\"not in\"`` operators also support iterators: ``X in " "iterator`` is true if X is found in the stream returned by the iterator. " "You'll run into obvious problems if the iterator is infinite; :func:`max`, :" "func:`min` will never return, and if the element X never appears in the " "stream, the ``\"in\"`` and ``\"not in\"`` operators won't return either." msgstr "" #: ../Doc/howto/functional.rst:255 msgid "" "Note that you can only go forward in an iterator; there's no way to get the " "previous element, reset the iterator, or make a copy of it. Iterator " "objects can optionally provide these additional capabilities, but the " "iterator protocol only specifies the :meth:`~iterator.__next__` method. " "Functions may therefore consume all of the iterator's output, and if you " "need to do something different with the same stream, you'll have to create a " "new iterator." msgstr "" #: ../Doc/howto/functional.rst:265 msgid "Data Types That Support Iterators" msgstr "" #: ../Doc/howto/functional.rst:267 msgid "" "We've already seen how lists and tuples support iterators. In fact, any " "Python sequence type, such as strings, will automatically support creation " "of an iterator." msgstr "" #: ../Doc/howto/functional.rst:271 msgid "" "Calling :func:`iter` on a dictionary returns an iterator that will loop over " "the dictionary's keys::" msgstr "" #: ../Doc/howto/functional.rst:291 msgid "" "Note that the order is essentially random, because it's based on the hash " "ordering of the objects in the dictionary." msgstr "" #: ../Doc/howto/functional.rst:294 msgid "" "Applying :func:`iter` to a dictionary always loops over the keys, but " "dictionaries have methods that return other iterators. If you want to " "iterate over values or key/value pairs, you can explicitly call the :meth:" "`~dict.values` or :meth:`~dict.items` methods to get an appropriate iterator." msgstr "" #: ../Doc/howto/functional.rst:300 msgid "" "The :func:`dict` constructor can accept an iterator that returns a finite " "stream of ``(key, value)`` tuples:" msgstr "" #: ../Doc/howto/functional.rst:307 msgid "" "Files also support iteration by calling the :meth:`~io.TextIOBase.readline` " "method until there are no more lines in the file. This means you can read " "each line of a file like this::" msgstr "" #: ../Doc/howto/functional.rst:315 msgid "" "Sets can take their contents from an iterable and let you iterate over the " "set's elements::" msgstr "" #: ../Doc/howto/functional.rst:325 msgid "Generator expressions and list comprehensions" msgstr "" #: ../Doc/howto/functional.rst:327 msgid "" "Two common operations on an iterator's output are 1) performing some " "operation for every element, 2) selecting a subset of elements that meet " "some condition. For example, given a list of strings, you might want to " "strip off trailing whitespace from each line or extract all the strings " "containing a given substring." msgstr "" #: ../Doc/howto/functional.rst:333 msgid "" "List comprehensions and generator expressions (short form: \"listcomps\" and " "\"genexps\") are a concise notation for such operations, borrowed from the " "functional programming language Haskell (https://www.haskell.org/). You can " "strip all the whitespace from a stream of strings with the following code::" msgstr "" #: ../Doc/howto/functional.rst:346 msgid "" "You can select only certain elements by adding an ``\"if\"`` condition::" msgstr "" #: ../Doc/howto/functional.rst:351 msgid "" "With a list comprehension, you get back a Python list; ``stripped_list`` is " "a list containing the resulting lines, not an iterator. Generator " "expressions return an iterator that computes the values as necessary, not " "needing to materialize all the values at once. This means that list " "comprehensions aren't useful if you're working with iterators that return an " "infinite stream or a very large amount of data. Generator expressions are " "preferable in these situations." msgstr "" #: ../Doc/howto/functional.rst:358 msgid "" "Generator expressions are surrounded by parentheses (\"()\") and list " "comprehensions are surrounded by square brackets (\"[]\"). Generator " "expressions have the form::" msgstr "" #: ../Doc/howto/functional.rst:371 msgid "" "Again, for a list comprehension only the outside brackets are different " "(square brackets instead of parentheses)." msgstr "" #: ../Doc/howto/functional.rst:374 msgid "" "The elements of the generated output will be the successive values of " "``expression``. The ``if`` clauses are all optional; if present, " "``expression`` is only evaluated and added to the result when ``condition`` " "is true." msgstr "" #: ../Doc/howto/functional.rst:378 msgid "" "Generator expressions always have to be written inside parentheses, but the " "parentheses signalling a function call also count. If you want to create an " "iterator that will be immediately passed to a function you can write::" msgstr "" #: ../Doc/howto/functional.rst:384 msgid "" "The ``for...in`` clauses contain the sequences to be iterated over. The " "sequences do not have to be the same length, because they are iterated over " "from left to right, **not** in parallel. For each element in ``sequence1``, " "``sequence2`` is looped over from the beginning. ``sequence3`` is then " "looped over for each resulting pair of elements from ``sequence1`` and " "``sequence2``." msgstr "" #: ../Doc/howto/functional.rst:390 msgid "" "To put it another way, a list comprehension or generator expression is " "equivalent to the following Python code::" msgstr "" #: ../Doc/howto/functional.rst:407 msgid "" "This means that when there are multiple ``for...in`` clauses but no ``if`` " "clauses, the length of the resulting output will be equal to the product of " "the lengths of all the sequences. If you have two lists of length 3, the " "output list is 9 elements long:" msgstr "" #: ../Doc/howto/functional.rst:419 msgid "" "To avoid introducing an ambiguity into Python's grammar, if ``expression`` " "is creating a tuple, it must be surrounded with parentheses. The first list " "comprehension below is a syntax error, while the second one is correct::" msgstr "" #: ../Doc/howto/functional.rst:430 msgid "Generators" msgstr "Générateurs" #: ../Doc/howto/functional.rst:432 msgid "" "Generators are a special class of functions that simplify the task of " "writing iterators. Regular functions compute a value and return it, but " "generators return an iterator that returns a stream of values." msgstr "" #: ../Doc/howto/functional.rst:436 msgid "" "You're doubtless familiar with how regular function calls work in Python or " "C. When you call a function, it gets a private namespace where its local " "variables are created. When the function reaches a ``return`` statement, " "the local variables are destroyed and the value is returned to the caller. " "A later call to the same function creates a new private namespace and a " "fresh set of local variables. But, what if the local variables weren't " "thrown away on exiting a function? What if you could later resume the " "function where it left off? This is what generators provide; they can be " "thought of as resumable functions." msgstr "" #: ../Doc/howto/functional.rst:445 msgid "Here's the simplest example of a generator function:" msgstr "" #: ../Doc/howto/functional.rst:451 msgid "" "Any function containing a :keyword:`yield` keyword is a generator function; " "this is detected by Python's :term:`bytecode` compiler which compiles the " "function specially as a result." msgstr "" #: ../Doc/howto/functional.rst:455 msgid "" "When you call a generator function, it doesn't return a single value; " "instead it returns a generator object that supports the iterator protocol. " "On executing the ``yield`` expression, the generator outputs the value of " "``i``, similar to a ``return`` statement. The big difference between " "``yield`` and a ``return`` statement is that on reaching a ``yield`` the " "generator's state of execution is suspended and local variables are " "preserved. On the next call to the generator's :meth:`~generator.__next__` " "method, the function will resume executing." msgstr "" #: ../Doc/howto/functional.rst:464 msgid "Here's a sample usage of the ``generate_ints()`` generator:" msgstr "" #: ../Doc/howto/functional.rst:481 msgid "" "You could equally write ``for i in generate_ints(5)``, or ``a,b,c = " "generate_ints(3)``." msgstr "" #: ../Doc/howto/functional.rst:484 msgid "" "Inside a generator function, ``return value`` causes " "``StopIteration(value)`` to be raised from the :meth:`~generator.__next__` " "method. Once this happens, or the bottom of the function is reached, the " "procession of values ends and the generator cannot yield any further values." msgstr "" #: ../Doc/howto/functional.rst:489 msgid "" "You could achieve the effect of generators manually by writing your own " "class and storing all the local variables of the generator as instance " "variables. For example, returning a list of integers could be done by " "setting ``self.count`` to 0, and having the :meth:`~iterator.__next__` " "method increment ``self.count`` and return it. However, for a moderately " "complicated generator, writing a corresponding class can be much messier." msgstr "" #: ../Doc/howto/functional.rst:497 msgid "" "The test suite included with Python's library, :source:`Lib/test/" "test_generators.py`, contains a number of more interesting examples. Here's " "one generator that implements an in-order traversal of a tree using " "generators recursively. ::" msgstr "" #: ../Doc/howto/functional.rst:513 msgid "" "Two other examples in ``test_generators.py`` produce solutions for the N-" "Queens problem (placing N queens on an NxN chess board so that no queen " "threatens another) and the Knight's Tour (finding a route that takes a " "knight to every square of an NxN chessboard without visiting any square " "twice)." msgstr "" #: ../Doc/howto/functional.rst:521 msgid "Passing values into a generator" msgstr "" #: ../Doc/howto/functional.rst:523 msgid "" "In Python 2.4 and earlier, generators only produced output. Once a " "generator's code was invoked to create an iterator, there was no way to pass " "any new information into the function when its execution is resumed. You " "could hack together this ability by making the generator look at a global " "variable or by passing in some mutable object that callers then modify, but " "these approaches are messy." msgstr "" #: ../Doc/howto/functional.rst:530 msgid "" "In Python 2.5 there's a simple way to pass values into a generator. :keyword:" "`yield` became an expression, returning a value that can be assigned to a " "variable or otherwise operated on::" msgstr "" #: ../Doc/howto/functional.rst:536 msgid "" "I recommend that you **always** put parentheses around a ``yield`` " "expression when you're doing something with the returned value, as in the " "above example. The parentheses aren't always necessary, but it's easier to " "always add them instead of having to remember when they're needed." msgstr "" #: ../Doc/howto/functional.rst:541 msgid "" "(:pep:`342` explains the exact rules, which are that a ``yield``-expression " "must always be parenthesized except when it occurs at the top-level " "expression on the right-hand side of an assignment. This means you can " "write ``val = yield i`` but have to use parentheses when there's an " "operation, as in ``val = (yield i) + 12``.)" msgstr "" #: ../Doc/howto/functional.rst:547 msgid "" "Values are sent into a generator by calling its :meth:`send(value) " "` method. This method resumes the generator's code and the " "``yield`` expression returns the specified value. If the regular :meth:" "`~generator.__next__` method is called, the ``yield`` returns ``None``." msgstr "" #: ../Doc/howto/functional.rst:552 msgid "" "Here's a simple counter that increments by 1 and allows changing the value " "of the internal counter." msgstr "" #: ../Doc/howto/functional.rst:567 msgid "And here's an example of changing the counter:" msgstr "" #: ../Doc/howto/functional.rst:584 msgid "" "Because ``yield`` will often be returning ``None``, you should always check " "for this case. Don't just use its value in expressions unless you're sure " "that the :meth:`~generator.send` method will be the only method used to " "resume your generator function." msgstr "" #: ../Doc/howto/functional.rst:589 msgid "" "In addition to :meth:`~generator.send`, there are two other methods on " "generators:" msgstr "" #: ../Doc/howto/functional.rst:592 msgid "" ":meth:`throw(type, value=None, traceback=None) ` is used to " "raise an exception inside the generator; the exception is raised by the " "``yield`` expression where the generator's execution is paused." msgstr "" #: ../Doc/howto/functional.rst:596 msgid "" ":meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the " "generator to terminate the iteration. On receiving this exception, the " "generator's code must either raise :exc:`GeneratorExit` or :exc:" "`StopIteration`; catching the exception and doing anything else is illegal " "and will trigger a :exc:`RuntimeError`. :meth:`~generator.close` will also " "be called by Python's garbage collector when the generator is garbage-" "collected." msgstr "" #: ../Doc/howto/functional.rst:604 msgid "" "If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I " "suggest using a ``try: ... finally:`` suite instead of catching :exc:" "`GeneratorExit`." msgstr "" #: ../Doc/howto/functional.rst:607 msgid "" "The cumulative effect of these changes is to turn generators from one-way " "producers of information into both producers and consumers." msgstr "" #: ../Doc/howto/functional.rst:610 msgid "" "Generators also become **coroutines**, a more generalized form of " "subroutines. Subroutines are entered at one point and exited at another " "point (the top of the function, and a ``return`` statement), but coroutines " "can be entered, exited, and resumed at many different points (the ``yield`` " "statements)." msgstr "" #: ../Doc/howto/functional.rst:617 msgid "Built-in functions" msgstr "Fonctions Natives" #: ../Doc/howto/functional.rst:619 msgid "" "Let's look in more detail at built-in functions often used with iterators." msgstr "" #: ../Doc/howto/functional.rst:621 msgid "" "Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate " "the features of generator expressions:" msgstr "" #: ../Doc/howto/functional.rst:633 msgid "" ":func:`map(f, iterA, iterB, ...) ` returns an iterator over the sequence" msgstr "" #: ../Doc/howto/functional.rst:625 msgid "" "``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``." msgstr "" #: ../Doc/howto/functional.rst:635 msgid "You can of course achieve the same effect with a list comprehension." msgstr "" #: ../Doc/howto/functional.rst:637 msgid "" ":func:`filter(predicate, iter) ` returns an iterator over all the " "sequence elements that meet a certain condition, and is similarly duplicated " "by list comprehensions. A **predicate** is a function that returns the " "truth value of some condition; for use with :func:`filter`, the predicate " "must take a single value." msgstr "" #: ../Doc/howto/functional.rst:650 msgid "This can also be written as a list comprehension:" msgstr "" #: ../Doc/howto/functional.rst:656 msgid "" ":func:`enumerate(iter) ` counts off the elements in the iterable, " "returning 2-tuples containing the count and each element. ::" msgstr "" #: ../Doc/howto/functional.rst:665 msgid "" ":func:`enumerate` is often used when looping through a list and recording " "the indexes at which certain conditions are met::" msgstr "" #: ../Doc/howto/functional.rst:673 msgid "" ":func:`sorted(iterable, key=None, reverse=False) ` collects all the " "elements of the iterable into a list, sorts the list, and returns the sorted " "result. The *key* and *reverse* arguments are passed through to the " "constructed list's :meth:`~list.sort` method. ::" msgstr "" #: ../Doc/howto/functional.rst:688 msgid "" "(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)" msgstr "" #: ../Doc/howto/functional.rst:691 msgid "" "The :func:`any(iter) ` and :func:`all(iter) ` built-ins look at " "the truth values of an iterable's contents. :func:`any` returns ``True`` if " "any element in the iterable is a true value, and :func:`all` returns " "``True`` if all of the elements are true values:" msgstr "" #: ../Doc/howto/functional.rst:710 msgid "" ":func:`zip(iterA, iterB, ...) ` takes one element from each iterable " "and returns them in a tuple::" msgstr "" #: ../Doc/howto/functional.rst:716 msgid "" "It doesn't construct an in-memory list and exhaust all the input iterators " "before returning; instead tuples are constructed and returned only if " "they're requested. (The technical term for this behaviour is `lazy " "evaluation `__.)" msgstr "" #: ../Doc/howto/functional.rst:721 msgid "" "This iterator is intended to be used with iterables that are all of the same " "length. If the iterables are of different lengths, the resulting stream " "will be the same length as the shortest iterable. ::" msgstr "" #: ../Doc/howto/functional.rst:728 msgid "" "You should avoid doing this, though, because an element may be taken from " "the longer iterators and discarded. This means you can't go on to use the " "iterators further because you risk skipping a discarded element." msgstr "" #: ../Doc/howto/functional.rst:734 msgid "The itertools module" msgstr "" #: ../Doc/howto/functional.rst:736 msgid "" "The :mod:`itertools` module contains a number of commonly-used iterators as " "well as functions for combining several iterators. This section will " "introduce the module's contents by showing small examples." msgstr "" #: ../Doc/howto/functional.rst:740 msgid "The module's functions fall into a few broad classes:" msgstr "" #: ../Doc/howto/functional.rst:742 msgid "Functions that create a new iterator based on an existing iterator." msgstr "" #: ../Doc/howto/functional.rst:743 msgid "Functions for treating an iterator's elements as function arguments." msgstr "" #: ../Doc/howto/functional.rst:744 msgid "Functions for selecting portions of an iterator's output." msgstr "" #: ../Doc/howto/functional.rst:745 msgid "A function for grouping an iterator's output." msgstr "" #: ../Doc/howto/functional.rst:748 msgid "Creating new iterators" msgstr "" #: ../Doc/howto/functional.rst:750 msgid "" ":func:`itertools.count(n) ` returns an infinite stream of " "integers, increasing by 1 each time. You can optionally supply the starting " "number, which defaults to 0::" msgstr "" #: ../Doc/howto/functional.rst:759 msgid "" ":func:`itertools.cycle(iter) ` saves a copy of the contents " "of a provided iterable and returns a new iterator that returns its elements " "from first to last. The new iterator will repeat these elements " "infinitely. ::" msgstr "" #: ../Doc/howto/functional.rst:766 msgid "" ":func:`itertools.repeat(elem, [n]) ` returns the provided " "element *n* times, or returns the element endlessly if *n* is not " "provided. ::" msgstr "" #: ../Doc/howto/functional.rst:774 msgid "" ":func:`itertools.chain(iterA, iterB, ...) ` takes an " "arbitrary number of iterables as input, and returns all the elements of the " "first iterator, then all the elements of the second, and so on, until all of " "the iterables have been exhausted. ::" msgstr "" #: ../Doc/howto/functional.rst:782 msgid "" ":func:`itertools.islice(iter, [start], stop, [step]) ` " "returns a stream that's a slice of the iterator. With a single *stop* " "argument, it will return the first *stop* elements. If you supply a " "starting index, you'll get *stop-start* elements, and if you supply a value " "for *step*, elements will be skipped accordingly. Unlike Python's string " "and list slicing, you can't use negative values for *start*, *stop*, or " "*step*. ::" msgstr "" #: ../Doc/howto/functional.rst:796 msgid "" ":func:`itertools.tee(iter, [n]) ` replicates an iterator; it " "returns *n* independent iterators that will all return the contents of the " "source iterator. If you don't supply a value for *n*, the default is 2. " "Replicating iterators requires saving some of the contents of the source " "iterator, so this can consume significant memory if the iterator is large " "and one of the new iterators is consumed more than the others. ::" msgstr "" #: ../Doc/howto/functional.rst:815 msgid "Calling functions on elements" msgstr "" #: ../Doc/howto/functional.rst:817 msgid "" "The :mod:`operator` module contains a set of functions corresponding to " "Python's operators. Some examples are :func:`operator.add(a, b) ` (adds two values), :func:`operator.ne(a, b) ` (same as " "``a != b``), and :func:`operator.attrgetter('id') ` " "(returns a callable that fetches the ``.id`` attribute)." msgstr "" #: ../Doc/howto/functional.rst:823 msgid "" ":func:`itertools.starmap(func, iter) ` assumes that the " "iterable will return a stream of tuples, and calls *func* using these tuples " "as the arguments::" msgstr "" #: ../Doc/howto/functional.rst:835 msgid "Selecting elements" msgstr "" #: ../Doc/howto/functional.rst:837 msgid "" "Another group of functions chooses a subset of an iterator's elements based " "on a predicate." msgstr "" #: ../Doc/howto/functional.rst:840 msgid "" ":func:`itertools.filterfalse(predicate, iter) ` is " "the opposite of :func:`filter`, returning all elements for which the " "predicate returns false::" msgstr "" #: ../Doc/howto/functional.rst:847 msgid "" ":func:`itertools.takewhile(predicate, iter) ` returns " "elements for as long as the predicate returns true. Once the predicate " "returns false, the iterator will signal the end of its results. ::" msgstr "" #: ../Doc/howto/functional.rst:860 msgid "" ":func:`itertools.dropwhile(predicate, iter) ` discards " "elements while the predicate returns true, and then returns the rest of the " "iterable's results. ::" msgstr "" #: ../Doc/howto/functional.rst:870 msgid "" ":func:`itertools.compress(data, selectors) ` takes two " "iterators and returns only those elements of *data* for which the " "corresponding element of *selectors* is true, stopping whenever either one " "is exhausted::" msgstr "" #: ../Doc/howto/functional.rst:879 msgid "Combinatoric functions" msgstr "" #: ../Doc/howto/functional.rst:881 msgid "" "The :func:`itertools.combinations(iterable, r) ` " "returns an iterator giving all possible *r*-tuple combinations of the " "elements contained in *iterable*. ::" msgstr "" #: ../Doc/howto/functional.rst:896 msgid "" "The elements within each tuple remain in the same order as *iterable* " "returned them. For example, the number 1 is always before 2, 3, 4, or 5 in " "the examples above. A similar function, :func:`itertools." "permutations(iterable, r=None) `, removes this " "constraint on the order, returning all possible arrangements of length *r*::" msgstr "" #: ../Doc/howto/functional.rst:915 msgid "" "If you don't supply a value for *r* the length of the iterable is used, " "meaning that all the elements are permuted." msgstr "" #: ../Doc/howto/functional.rst:918 msgid "" "Note that these functions produce all of the possible combinations by " "position and don't require that the contents of *iterable* are unique::" msgstr "" #: ../Doc/howto/functional.rst:925 msgid "" "The identical tuple ``('a', 'a', 'b')`` occurs twice, but the two 'a' " "strings came from different positions." msgstr "" #: ../Doc/howto/functional.rst:928 msgid "" "The :func:`itertools.combinations_with_replacement(iterable, r) ` function relaxes a different constraint: " "elements can be repeated within a single tuple. Conceptually an element is " "selected for the first position of each tuple and then is replaced before " "the second element is selected. ::" msgstr "" #: ../Doc/howto/functional.rst:943 msgid "Grouping elements" msgstr "" #: ../Doc/howto/functional.rst:945 msgid "" "The last function I'll discuss, :func:`itertools.groupby(iter, " "key_func=None) `, is the most complicated. " "``key_func(elem)`` is a function that can compute a key value for each " "element returned by the iterable. If you don't supply a key function, the " "key is simply each element itself." msgstr "" #: ../Doc/howto/functional.rst:950 msgid "" ":func:`~itertools.groupby` collects all the consecutive elements from the " "underlying iterable that have the same key value, and returns a stream of 2-" "tuples containing a key value and an iterator for the elements with that key." msgstr "" #: ../Doc/howto/functional.rst:978 msgid "" ":func:`~itertools.groupby` assumes that the underlying iterable's contents " "will already be sorted based on the key. Note that the returned iterators " "also use the underlying iterable, so you have to consume the results of " "iterator-1 before requesting iterator-2 and its corresponding key." msgstr "" #: ../Doc/howto/functional.rst:985 msgid "The functools module" msgstr "" #: ../Doc/howto/functional.rst:987 msgid "" "The :mod:`functools` module in Python 2.5 contains some higher-order " "functions. A **higher-order function** takes one or more functions as input " "and returns a new function. The most useful tool in this module is the :" "func:`functools.partial` function." msgstr "" #: ../Doc/howto/functional.rst:992 msgid "" "For programs written in a functional style, you'll sometimes want to " "construct variants of existing functions that have some of the parameters " "filled in. Consider a Python function ``f(a, b, c)``; you may wish to create " "a new function ``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're " "filling in a value for one of ``f()``'s parameters. This is called " "\"partial function application\"." msgstr "" #: ../Doc/howto/functional.rst:998 msgid "" "The constructor for :func:`~functools.partial` takes the arguments " "``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``. The " "resulting object is callable, so you can just call it to invoke ``function`` " "with the filled-in arguments." msgstr "" #: ../Doc/howto/functional.rst:1003 msgid "Here's a small but realistic example::" msgstr "Voici un exemple court mais réaliste ::" #: ../Doc/howto/functional.rst:1015 msgid "" ":func:`functools.reduce(func, iter, [initial_value]) ` " "cumulatively performs an operation on all the iterable's elements and, " "therefore, can't be applied to infinite iterables. *func* must be a function " "that takes two elements and returns a single value. :func:`functools." "reduce` takes the first two elements A and B returned by the iterator and " "calculates ``func(A, B)``. It then requests the third element, C, " "calculates ``func(func(A, B), C)``, combines this result with the fourth " "element returned, and continues until the iterable is exhausted. If the " "iterable returns no values at all, a :exc:`TypeError` exception is raised. " "If the initial value is supplied, it's used as a starting point and " "``func(initial_value, A)`` is the first calculation. ::" msgstr "" #: ../Doc/howto/functional.rst:1039 msgid "" "If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up " "all the elements of the iterable. This case is so common that there's a " "special built-in called :func:`sum` to compute it:" msgstr "" #: ../Doc/howto/functional.rst:1051 msgid "" "For many uses of :func:`functools.reduce`, though, it can be clearer to just " "write the obvious :keyword:`for` loop::" msgstr "" #: ../Doc/howto/functional.rst:1063 msgid "" "A related function is `itertools.accumulate(iterable, func=operator.add) " "`__, `part 2 `__, and `part 3 `__," msgstr "" #: ../Doc/howto/functional.rst:1234 msgid "Python documentation" msgstr "" #: ../Doc/howto/functional.rst:1236 msgid "Documentation for the :mod:`itertools` module." msgstr "" #: ../Doc/howto/functional.rst:1238 msgid "Documentation for the :mod:`operator` module." msgstr "" #: ../Doc/howto/functional.rst:1240 msgid ":pep:`289`: \"Generator Expressions\"" msgstr "" #: ../Doc/howto/functional.rst:1242 msgid "" ":pep:`342`: \"Coroutines via Enhanced Generators\" describes the new " "generator features in Python 2.5." msgstr "" #: ../Doc/howto/index.rst:3 msgid "Python HOWTOs" msgstr "Les HOWTOs de Python [en]" #: ../Doc/howto/index.rst:5 msgid "" "Python HOWTOs are documents that cover a single, specific topic, and attempt " "to cover it fairly completely. Modelled on the Linux Documentation Project's " "HOWTO collection, this collection is an effort to foster documentation " "that's more detailed than the Python Library Reference." msgstr "" #: ../Doc/howto/index.rst:11 msgid "Currently, the HOWTOs are:" msgstr "" #: ../Doc/howto/instrumentation.rst:5 msgid "Instrumenting CPython with DTrace and SystemTap" msgstr "" #: ../Doc/howto/instrumentation.rst:7 msgid "David Malcolm" msgstr "" #: ../Doc/howto/instrumentation.rst:8 msgid "Łukasz Langa" msgstr "" #: ../Doc/howto/instrumentation.rst:10 msgid "" "DTrace and SystemTap are monitoring tools, each providing a way to inspect " "what the processes on a computer system are doing. They both use domain-" "specific languages allowing a user to write scripts which:" msgstr "" #: ../Doc/howto/instrumentation.rst:14 msgid "filter which processes are to be observed" msgstr "" #: ../Doc/howto/instrumentation.rst:15 msgid "gather data from the processes of interest" msgstr "" #: ../Doc/howto/instrumentation.rst:16 msgid "generate reports on the data" msgstr "" #: ../Doc/howto/instrumentation.rst:18 msgid "" "As of Python 3.6, CPython can be built with embedded \"markers\", also known " "as \"probes\", that can be observed by a DTrace or SystemTap script, making " "it easier to monitor what the CPython processes on a system are doing." msgstr "" #: ../Doc/howto/instrumentation.rst:28 msgid "" "DTrace markers are implementation details of the CPython interpreter. No " "guarantees are made about probe compatibility between versions of CPython. " "DTrace scripts can stop working or work incorrectly without warning when " "changing CPython versions." msgstr "" #: ../Doc/howto/instrumentation.rst:35 msgid "Enabling the static markers" msgstr "" #: ../Doc/howto/instrumentation.rst:37 msgid "" "macOS comes with built-in support for DTrace. On Linux, in order to build " "CPython with the embedded markers for SystemTap, the SystemTap development " "tools must be installed." msgstr "" #: ../Doc/howto/instrumentation.rst:41 msgid "On a Linux machine, this can be done via::" msgstr "" #: ../Doc/howto/instrumentation.rst:45 msgid "or::" msgstr "ou : ::" #: ../Doc/howto/instrumentation.rst:50 msgid "CPython must then be configured `--with-dtrace`::" msgstr "" #: ../Doc/howto/instrumentation.rst:54 msgid "" "On macOS, you can list available DTrace probes by running a Python process " "in the background and listing all probes made available by the Python " "provider::" msgstr "" #: ../Doc/howto/instrumentation.rst:71 msgid "" "On Linux, you can verify if the SystemTap static markers are present in the " "built binary by seeing if it contains a \".note.stapsdt\" section." msgstr "" #: ../Doc/howto/instrumentation.rst:79 msgid "" "If you've built Python as a shared library (with --enable-shared), you need " "to look instead within the shared library. For example:" msgstr "" #: ../Doc/howto/instrumentation.rst:87 msgid "Sufficiently modern readelf can print the metadata:" msgstr "" #: ../Doc/howto/instrumentation.rst:126 msgid "" "The above metadata contains information for SystemTap describing how it can " "patch strategically-placed machine code instructions to enable the tracing " "hooks used by a SystemTap script." msgstr "" #: ../Doc/howto/instrumentation.rst:132 msgid "Static DTrace probes" msgstr "" #: ../Doc/howto/instrumentation.rst:134 msgid "" "The following example DTrace script can be used to show the call/return " "hierarchy of a Python script, only tracing within the invocation of a " "function called \"start\". In other words, import-time function invocations " "are not going to be listed:" msgstr "" #: ../Doc/howto/instrumentation.rst:173 ../Doc/howto/instrumentation.rst:231 msgid "It can be invoked like this:" msgstr "" #: ../Doc/howto/instrumentation.rst:179 ../Doc/howto/instrumentation.rst:239 #: ../Doc/howto/logging-cookbook.rst:75 msgid "The output looks like this::" msgstr "" #: ../Doc/howto/instrumentation.rst:202 msgid "Static SystemTap markers" msgstr "" #: ../Doc/howto/instrumentation.rst:204 msgid "" "The low-level way to use the SystemTap integration is to use the static " "markers directly. This requires you to explicitly state the binary file " "containing them." msgstr "" #: ../Doc/howto/instrumentation.rst:208 msgid "" "For example, this SystemTap script can be used to show the call/return " "hierarchy of a Python script:" msgstr "" #: ../Doc/howto/instrumentation.rst:248 msgid "where the columns are:" msgstr "" #: ../Doc/howto/instrumentation.rst:250 msgid "time in microseconds since start of script" msgstr "" #: ../Doc/howto/instrumentation.rst:252 msgid "name of executable" msgstr "" #: ../Doc/howto/instrumentation.rst:254 msgid "PID of process" msgstr "" #: ../Doc/howto/instrumentation.rst:256 msgid "" "and the remainder indicates the call/return hierarchy as the script executes." msgstr "" #: ../Doc/howto/instrumentation.rst:258 msgid "" "For a `--enable-shared` build of CPython, the markers are contained within " "the libpython shared library, and the probe's dotted path needs to reflect " "this. For example, this line from the above example::" msgstr "" #: ../Doc/howto/instrumentation.rst:264 msgid "should instead read::" msgstr "" #: ../Doc/howto/instrumentation.rst:268 msgid "(assuming a debug build of CPython 3.6)" msgstr "" #: ../Doc/howto/instrumentation.rst:272 msgid "Available static markers" msgstr "" #: ../Doc/howto/instrumentation.rst:278 msgid "" "This marker indicates that execution of a Python function has begun. It is " "only triggered for pure-Python (bytecode) functions." msgstr "" #: ../Doc/howto/instrumentation.rst:281 msgid "" "The filename, function name, and line number are provided back to the " "tracing script as positional arguments, which must be accessed using ``" "$arg1``, ``$arg2``, ``$arg3``:" msgstr "" #: ../Doc/howto/instrumentation.rst:285 msgid "" "``$arg1`` : ``(const char *)`` filename, accessible using " "``user_string($arg1)``" msgstr "" #: ../Doc/howto/instrumentation.rst:287 msgid "" "``$arg2`` : ``(const char *)`` function name, accessible using " "``user_string($arg2)``" msgstr "" #: ../Doc/howto/instrumentation.rst:290 msgid "``$arg3`` : ``int`` line number" msgstr "" #: ../Doc/howto/instrumentation.rst:294 msgid "" "This marker is the converse of :c:func:`function__entry`, and indicates that " "execution of a Python function has ended (either via ``return``, or via an " "exception). It is only triggered for pure-Python (bytecode) functions." msgstr "" #: ../Doc/howto/instrumentation.rst:298 msgid "The arguments are the same as for :c:func:`function__entry`" msgstr "" #: ../Doc/howto/instrumentation.rst:302 msgid "" "This marker indicates a Python line is about to be executed. It is the " "equivalent of line-by-line tracing with a Python profiler. It is not " "triggered within C functions." msgstr "" #: ../Doc/howto/instrumentation.rst:306 msgid "The arguments are the same as for :c:func:`function__entry`." msgstr "" #: ../Doc/howto/instrumentation.rst:310 msgid "" "Fires when the Python interpreter starts a garbage collection cycle. " "``arg0`` is the generation to scan, like :func:`gc.collect()`." msgstr "" #: ../Doc/howto/instrumentation.rst:315 msgid "" "Fires when the Python interpreter finishes a garbage collection cycle. " "``arg0`` is the number of collected objects." msgstr "" #: ../Doc/howto/instrumentation.rst:320 msgid "SystemTap Tapsets" msgstr "" #: ../Doc/howto/instrumentation.rst:322 msgid "" "The higher-level way to use the SystemTap integration is to use a \"tapset" "\": SystemTap's equivalent of a library, which hides some of the lower-level " "details of the static markers." msgstr "" #: ../Doc/howto/instrumentation.rst:326 msgid "Here is a tapset file, based on a non-shared build of CPython:" msgstr "" #: ../Doc/howto/instrumentation.rst:349 msgid "" "If this file is installed in SystemTap's tapset directory (e.g. ``/usr/share/" "systemtap/tapset``), then these additional probepoints become available:" msgstr "" #: ../Doc/howto/instrumentation.rst:355 msgid "" "This probe point indicates that execution of a Python function has begun. It " "is only triggered for pure-python (bytecode) functions." msgstr "" #: ../Doc/howto/instrumentation.rst:360 msgid "" "This probe point is the converse of :c:func:`python.function.return`, and " "indicates that execution of a Python function has ended (either via " "``return``, or via an exception). It is only triggered for pure-python " "(bytecode) functions." msgstr "" #: ../Doc/howto/instrumentation.rst:367 msgid "Examples" msgstr "Exemples" #: ../Doc/howto/instrumentation.rst:368 msgid "" "This SystemTap script uses the tapset above to more cleanly implement the " "example given above of tracing the Python function-call hierarchy, without " "needing to directly name the static markers:" msgstr "" #: ../Doc/howto/instrumentation.rst:387 msgid "" "The following script uses the tapset above to provide a top-like view of all " "running CPython code, showing the top 20 most frequently-entered bytecode " "frames, each second, across the whole system:" msgstr "" #: ../Doc/howto/ipaddress.rst:9 msgid "An introduction to the ipaddress module" msgstr "" #: ../Doc/howto/ipaddress.rst:11 msgid "Peter Moody" msgstr "" #: ../Doc/howto/ipaddress.rst:12 msgid "Nick Coghlan" msgstr "" #: ../Doc/howto/ipaddress.rst:0 msgid "Overview" msgstr "" #: ../Doc/howto/ipaddress.rst:16 msgid "" "This document aims to provide a gentle introduction to the :mod:`ipaddress` " "module. It is aimed primarily at users that aren't already familiar with IP " "networking terminology, but may also be useful to network engineers wanting " "an overview of how :mod:`ipaddress` represents IP network addressing " "concepts." msgstr "" #: ../Doc/howto/ipaddress.rst:24 msgid "Creating Address/Network/Interface objects" msgstr "" #: ../Doc/howto/ipaddress.rst:26 msgid "" "Since :mod:`ipaddress` is a module for inspecting and manipulating IP " "addresses, the first thing you'll want to do is create some objects. You " "can use :mod:`ipaddress` to create objects from strings and integers." msgstr "" #: ../Doc/howto/ipaddress.rst:32 msgid "A Note on IP Versions" msgstr "" #: ../Doc/howto/ipaddress.rst:34 msgid "" "For readers that aren't particularly familiar with IP addressing, it's " "important to know that the Internet Protocol is currently in the process of " "moving from version 4 of the protocol to version 6. This transition is " "occurring largely because version 4 of the protocol doesn't provide enough " "addresses to handle the needs of the whole world, especially given the " "increasing number of devices with direct connections to the internet." msgstr "" #: ../Doc/howto/ipaddress.rst:41 msgid "" "Explaining the details of the differences between the two versions of the " "protocol is beyond the scope of this introduction, but readers need to at " "least be aware that these two versions exist, and it will sometimes be " "necessary to force the use of one version or the other." msgstr "" #: ../Doc/howto/ipaddress.rst:48 msgid "IP Host Addresses" msgstr "" #: ../Doc/howto/ipaddress.rst:50 msgid "" "Addresses, often referred to as \"host addresses\" are the most basic unit " "when working with IP addressing. The simplest way to create addresses is to " "use the :func:`ipaddress.ip_address` factory function, which automatically " "determines whether to create an IPv4 or IPv6 address based on the passed in " "value:" msgstr "" #: ../Doc/howto/ipaddress.rst:61 msgid "" "Addresses can also be created directly from integers. Values that will fit " "within 32 bits are assumed to be IPv4 addresses::" msgstr "" #: ../Doc/howto/ipaddress.rst:69 msgid "" "To force the use of IPv4 or IPv6 addresses, the relevant classes can be " "invoked directly. This is particularly useful to force creation of IPv6 " "addresses for small integers::" msgstr "" #: ../Doc/howto/ipaddress.rst:82 msgid "Defining Networks" msgstr "" #: ../Doc/howto/ipaddress.rst:84 msgid "" "Host addresses are usually grouped together into IP networks, so :mod:" "`ipaddress` provides a way to create, inspect and manipulate network " "definitions. IP network objects are constructed from strings that define the " "range of host addresses that are part of that network. The simplest form for " "that information is a \"network address/network prefix\" pair, where the " "prefix defines the number of leading bits that are compared to determine " "whether or not an address is part of the network and the network address " "defines the expected value of those bits." msgstr "" #: ../Doc/howto/ipaddress.rst:93 msgid "" "As for addresses, a factory function is provided that determines the correct " "IP version automatically::" msgstr "" #: ../Doc/howto/ipaddress.rst:101 msgid "" "Network objects cannot have any host bits set. The practical effect of this " "is that ``192.0.2.1/24`` does not describe a network. Such definitions are " "referred to as interface objects since the ip-on-a-network notation is " "commonly used to describe network interfaces of a computer on a given " "network and are described further in the next section." msgstr "" #: ../Doc/howto/ipaddress.rst:107 msgid "" "By default, attempting to create a network object with host bits set will " "result in :exc:`ValueError` being raised. To request that the additional " "bits instead be coerced to zero, the flag ``strict=False`` can be passed to " "the constructor::" msgstr "" #: ../Doc/howto/ipaddress.rst:119 msgid "" "While the string form offers significantly more flexibility, networks can " "also be defined with integers, just like host addresses. In this case, the " "network is considered to contain only the single address identified by the " "integer, so the network prefix includes the entire network address::" msgstr "" #: ../Doc/howto/ipaddress.rst:129 msgid "" "As with addresses, creation of a particular kind of network can be forced by " "calling the class constructor directly instead of using the factory function." msgstr "" #: ../Doc/howto/ipaddress.rst:135 msgid "Host Interfaces" msgstr "" #: ../Doc/howto/ipaddress.rst:137 msgid "" "As mentioned just above, if you need to describe an address on a particular " "network, neither the address nor the network classes are sufficient. " "Notation like ``192.0.2.1/24`` is commonly used by network engineers and the " "people who write tools for firewalls and routers as shorthand for \"the host " "``192.0.2.1`` on the network ``192.0.2.0/24``\", Accordingly, :mod:" "`ipaddress` provides a set of hybrid classes that associate an address with " "a particular network. The interface for creation is identical to that for " "defining network objects, except that the address portion isn't constrained " "to being a network address." msgstr "" #: ../Doc/howto/ipaddress.rst:152 msgid "" "Integer inputs are accepted (as with networks), and use of a particular IP " "version can be forced by calling the relevant constructor directly." msgstr "" #: ../Doc/howto/ipaddress.rst:157 msgid "Inspecting Address/Network/Interface Objects" msgstr "" #: ../Doc/howto/ipaddress.rst:159 msgid "" "You've gone to the trouble of creating an IPv(4|6)(Address|Network|" "Interface) object, so you probably want to get information about it. :mod:" "`ipaddress` tries to make doing this easy and intuitive." msgstr "" #: ../Doc/howto/ipaddress.rst:163 msgid "Extracting the IP version::" msgstr "" #: ../Doc/howto/ipaddress.rst:172 msgid "Obtaining the network from an interface::" msgstr "" #: ../Doc/howto/ipaddress.rst:181 msgid "Finding out how many individual addresses are in a network::" msgstr "" #: ../Doc/howto/ipaddress.rst:190 msgid "Iterating through the \"usable\" addresses on a network::" msgstr "" #: ../Doc/howto/ipaddress.rst:205 msgid "" "Obtaining the netmask (i.e. set bits corresponding to the network prefix) or " "the hostmask (any bits that are not part of the netmask):" msgstr "" #: ../Doc/howto/ipaddress.rst:220 msgid "Exploding or compressing the address::" msgstr "" #: ../Doc/howto/ipaddress.rst:231 msgid "" "While IPv4 doesn't support explosion or compression, the associated objects " "still provide the relevant properties so that version neutral code can " "easily ensure the most concise or most verbose form is used for IPv6 " "addresses while still correctly handling IPv4 addresses." msgstr "" #: ../Doc/howto/ipaddress.rst:238 msgid "Networks as lists of Addresses" msgstr "" #: ../Doc/howto/ipaddress.rst:240 msgid "" "It's sometimes useful to treat networks as lists. This means it is possible " "to index them like this::" msgstr "" #: ../Doc/howto/ipaddress.rst:253 msgid "" "It also means that network objects lend themselves to using the list " "membership test syntax like this::" msgstr "" #: ../Doc/howto/ipaddress.rst:259 msgid "Containment testing is done efficiently based on the network prefix::" msgstr "" #: ../Doc/howto/ipaddress.rst:269 msgid "Comparisons" msgstr "Comparaisons" #: ../Doc/howto/ipaddress.rst:271 msgid "" ":mod:`ipaddress` provides some simple, hopefully intuitive ways to compare " "objects, where it makes sense::" msgstr "" #: ../Doc/howto/ipaddress.rst:277 msgid "" "A :exc:`TypeError` exception is raised if you try to compare objects of " "different versions or different types." msgstr "" #: ../Doc/howto/ipaddress.rst:282 msgid "Using IP Addresses with other modules" msgstr "" #: ../Doc/howto/ipaddress.rst:284 msgid "" "Other modules that use IP addresses (such as :mod:`socket`) usually won't " "accept objects from this module directly. Instead, they must be coerced to " "an integer or string that the other module will accept::" msgstr "" #: ../Doc/howto/ipaddress.rst:296 msgid "Getting more detail when instance creation fails" msgstr "" #: ../Doc/howto/ipaddress.rst:298 msgid "" "When creating address/network/interface objects using the version-agnostic " "factory functions, any errors will be reported as :exc:`ValueError` with a " "generic error message that simply says the passed in value was not " "recognized as an object of that type. The lack of a specific error is " "because it's necessary to know whether the value is *supposed* to be IPv4 or " "IPv6 in order to provide more detail on why it has been rejected." msgstr "" #: ../Doc/howto/ipaddress.rst:305 msgid "" "To support use cases where it is useful to have access to this additional " "detail, the individual class constructors actually raise the :exc:" "`ValueError` subclasses :exc:`ipaddress.AddressValueError` and :exc:" "`ipaddress.NetmaskValueError` to indicate exactly which part of the " "definition failed to parse correctly." msgstr "" #: ../Doc/howto/ipaddress.rst:311 msgid "" "The error messages are significantly more detailed when using the class " "constructors directly. For example::" msgstr "" #: ../Doc/howto/ipaddress.rst:332 msgid "" "However, both of the module specific exceptions have :exc:`ValueError` as " "their parent class, so if you're not concerned with the particular type of " "error, you can still write code like the following::" msgstr "" #: ../Doc/howto/logging.rst:3 msgid "Logging HOWTO" msgstr "" #: ../Doc/howto/logging.rst:5 ../Doc/howto/logging-cookbook.rst:7 msgid "Vinay Sajip " msgstr "" #: ../Doc/howto/logging.rst:12 msgid "Basic Logging Tutorial" msgstr "" #: ../Doc/howto/logging.rst:14 msgid "" "Logging is a means of tracking events that happen when some software runs. " "The software's developer adds logging calls to their code to indicate that " "certain events have occurred. An event is described by a descriptive message " "which can optionally contain variable data (i.e. data that is potentially " "different for each occurrence of the event). Events also have an importance " "which the developer ascribes to the event; the importance can also be called " "the *level* or *severity*." msgstr "" #: ../Doc/howto/logging.rst:23 msgid "When to use logging" msgstr "" #: ../Doc/howto/logging.rst:25 msgid "" "Logging provides a set of convenience functions for simple logging usage. " "These are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and :" "func:`critical`. To determine when to use logging, see the table below, " "which states, for each of a set of common tasks, the best tool to use for it." msgstr "" #: ../Doc/howto/logging.rst:31 msgid "Task you want to perform" msgstr "" #: ../Doc/howto/logging.rst:31 msgid "The best tool for the task" msgstr "" #: ../Doc/howto/logging.rst:33 msgid "" "Display console output for ordinary usage of a command line script or program" msgstr "" #: ../Doc/howto/logging.rst:33 msgid ":func:`print`" msgstr ":func:`print`" #: ../Doc/howto/logging.rst:37 msgid "" "Report events that occur during normal operation of a program (e.g. for " "status monitoring or fault investigation)" msgstr "" #: ../Doc/howto/logging.rst:37 msgid "" ":func:`logging.info` (or :func:`logging.debug` for very detailed output for " "diagnostic purposes)" msgstr "" #: ../Doc/howto/logging.rst:42 msgid "Issue a warning regarding a particular runtime event" msgstr "" #: ../Doc/howto/logging.rst:42 msgid "" ":func:`warnings.warn` in library code if the issue is avoidable and the " "client application should be modified to eliminate the warning" msgstr "" #: ../Doc/howto/logging.rst:47 msgid "" ":func:`logging.warning` if there is nothing the client application can do " "about the situation, but the event should still be noted" msgstr "" #: ../Doc/howto/logging.rst:52 msgid "Report an error regarding a particular runtime event" msgstr "" #: ../Doc/howto/logging.rst:52 msgid "Raise an exception" msgstr "" #: ../Doc/howto/logging.rst:55 msgid "" "Report suppression of an error without raising an exception (e.g. error " "handler in a long-running server process)" msgstr "" #: ../Doc/howto/logging.rst:55 msgid "" ":func:`logging.error`, :func:`logging.exception` or :func:`logging.critical` " "as appropriate for the specific error and application domain" msgstr "" #: ../Doc/howto/logging.rst:62 msgid "" "The logging functions are named after the level or severity of the events " "they are used to track. The standard levels and their applicability are " "described below (in increasing order of severity):" msgstr "" #: ../Doc/howto/logging.rst:69 ../Doc/howto/logging.rst:826 msgid "Level" msgstr "" #: ../Doc/howto/logging.rst:69 msgid "When it's used" msgstr "" #: ../Doc/howto/logging.rst:71 ../Doc/howto/logging.rst:836 msgid "``DEBUG``" msgstr "``DEBUG``" #: ../Doc/howto/logging.rst:71 msgid "" "Detailed information, typically of interest only when diagnosing problems." msgstr "" #: ../Doc/howto/logging.rst:74 ../Doc/howto/logging.rst:834 msgid "``INFO``" msgstr "``INFO``" #: ../Doc/howto/logging.rst:74 msgid "Confirmation that things are working as expected." msgstr "" #: ../Doc/howto/logging.rst:77 ../Doc/howto/logging.rst:832 msgid "``WARNING``" msgstr "``WARNING``" #: ../Doc/howto/logging.rst:77 msgid "" "An indication that something unexpected happened, or indicative of some " "problem in the near future (e.g. 'disk space low'). The software is still " "working as expected." msgstr "" #: ../Doc/howto/logging.rst:82 ../Doc/howto/logging.rst:830 msgid "``ERROR``" msgstr "``ERROR``" #: ../Doc/howto/logging.rst:82 msgid "" "Due to a more serious problem, the software has not been able to perform " "some function." msgstr "" #: ../Doc/howto/logging.rst:85 ../Doc/howto/logging.rst:828 msgid "``CRITICAL``" msgstr "``CRITICAL``" #: ../Doc/howto/logging.rst:85 msgid "" "A serious error, indicating that the program itself may be unable to " "continue running." msgstr "" #: ../Doc/howto/logging.rst:89 msgid "" "The default level is ``WARNING``, which means that only events of this level " "and above will be tracked, unless the logging package is configured to do " "otherwise." msgstr "" #: ../Doc/howto/logging.rst:93 msgid "" "Events that are tracked can be handled in different ways. The simplest way " "of handling tracked events is to print them to the console. Another common " "way is to write them to a disk file." msgstr "" #: ../Doc/howto/logging.rst:101 msgid "A simple example" msgstr "" #: ../Doc/howto/logging.rst:103 msgid "A very simple example is::" msgstr "" #: ../Doc/howto/logging.rst:109 msgid "If you type these lines into a script and run it, you'll see:" msgstr "" #: ../Doc/howto/logging.rst:115 msgid "" "printed out on the console. The ``INFO`` message doesn't appear because the " "default level is ``WARNING``. The printed message includes the indication of " "the level and the description of the event provided in the logging call, i." "e. 'Watch out!'. Don't worry about the 'root' part for now: it will be " "explained later. The actual output can be formatted quite flexibly if you " "need that; formatting options will also be explained later." msgstr "" #: ../Doc/howto/logging.rst:124 msgid "Logging to a file" msgstr "" #: ../Doc/howto/logging.rst:126 msgid "" "A very common situation is that of recording logging events in a file, so " "let's look at that next. Be sure to try the following in a newly-started " "Python interpreter, and don't just continue from the session described " "above::" msgstr "" #: ../Doc/howto/logging.rst:136 msgid "" "And now if we open the file and look at what we have, we should find the log " "messages::" msgstr "" #: ../Doc/howto/logging.rst:143 msgid "" "This example also shows how you can set the logging level which acts as the " "threshold for tracking. In this case, because we set the threshold to " "``DEBUG``, all of the messages were printed." msgstr "" #: ../Doc/howto/logging.rst:147 msgid "" "If you want to set the logging level from a command-line option such as::" msgstr "" #: ../Doc/howto/logging.rst:151 msgid "" "and you have the value of the parameter passed for ``--log`` in some " "variable *loglevel*, you can use::" msgstr "" #: ../Doc/howto/logging.rst:156 msgid "" "to get the value which you'll pass to :func:`basicConfig` via the *level* " "argument. You may want to error check any user input value, perhaps as in " "the following example::" msgstr "" #: ../Doc/howto/logging.rst:168 msgid "" "The call to :func:`basicConfig` should come *before* any calls to :func:" "`debug`, :func:`info` etc. As it's intended as a one-off simple " "configuration facility, only the first call will actually do anything: " "subsequent calls are effectively no-ops." msgstr "" #: ../Doc/howto/logging.rst:173 msgid "" "If you run the above script several times, the messages from successive runs " "are appended to the file *example.log*. If you want each run to start " "afresh, not remembering the messages from earlier runs, you can specify the " "*filemode* argument, by changing the call in the above example to::" msgstr "" #: ../Doc/howto/logging.rst:180 msgid "" "The output will be the same as before, but the log file is no longer " "appended to, so the messages from earlier runs are lost." msgstr "" #: ../Doc/howto/logging.rst:185 msgid "Logging from multiple modules" msgstr "" #: ../Doc/howto/logging.rst:187 msgid "" "If your program consists of multiple modules, here's an example of how you " "could organize logging in it::" msgstr "" #: ../Doc/howto/logging.rst:211 msgid "If you run *myapp.py*, you should see this in *myapp.log*::" msgstr "" #: ../Doc/howto/logging.rst:217 msgid "" "which is hopefully what you were expecting to see. You can generalize this " "to multiple modules, using the pattern in *mylib.py*. Note that for this " "simple usage pattern, you won't know, by looking in the log file, *where* in " "your application your messages came from, apart from looking at the event " "description. If you want to track the location of your messages, you'll need " "to refer to the documentation beyond the tutorial level -- see :ref:`logging-" "advanced-tutorial`." msgstr "" #: ../Doc/howto/logging.rst:227 msgid "Logging variable data" msgstr "" #: ../Doc/howto/logging.rst:229 msgid "" "To log variable data, use a format string for the event description message " "and append the variable data as arguments. For example::" msgstr "" #: ../Doc/howto/logging.rst:235 msgid "will display:" msgstr "" #: ../Doc/howto/logging.rst:241 msgid "" "As you can see, merging of variable data into the event description message " "uses the old, %-style of string formatting. This is for backwards " "compatibility: the logging package pre-dates newer formatting options such " "as :meth:`str.format` and :class:`string.Template`. These newer formatting " "options *are* supported, but exploring them is outside the scope of this " "tutorial: see :ref:`formatting-styles` for more information." msgstr "" #: ../Doc/howto/logging.rst:250 msgid "Changing the format of displayed messages" msgstr "" #: ../Doc/howto/logging.rst:252 msgid "" "To change the format which is used to display messages, you need to specify " "the format you want to use::" msgstr "" #: ../Doc/howto/logging.rst:261 msgid "which would print::" msgstr "" #: ../Doc/howto/logging.rst:267 msgid "" "Notice that the 'root' which appeared in earlier examples has disappeared. " "For a full set of things that can appear in format strings, you can refer to " "the documentation for :ref:`logrecord-attributes`, but for simple usage, you " "just need the *levelname* (severity), *message* (event description, " "including variable data) and perhaps to display when the event occurred. " "This is described in the next section." msgstr "" #: ../Doc/howto/logging.rst:276 msgid "Displaying the date/time in messages" msgstr "" #: ../Doc/howto/logging.rst:278 msgid "" "To display the date and time of an event, you would place '%(asctime)s' in " "your format string::" msgstr "" #: ../Doc/howto/logging.rst:285 msgid "which should print something like this::" msgstr "" #: ../Doc/howto/logging.rst:289 msgid "" "The default format for date/time display (shown above) is ISO8601. If you " "need more control over the formatting of the date/time, provide a *datefmt* " "argument to ``basicConfig``, as in this example::" msgstr "" #: ../Doc/howto/logging.rst:297 msgid "which would display something like this::" msgstr "" #: ../Doc/howto/logging.rst:301 msgid "" "The format of the *datefmt* argument is the same as supported by :func:`time." "strftime`." msgstr "" #: ../Doc/howto/logging.rst:306 msgid "Next Steps" msgstr "" #: ../Doc/howto/logging.rst:308 msgid "" "That concludes the basic tutorial. It should be enough to get you up and " "running with logging. There's a lot more that the logging package offers, " "but to get the best out of it, you'll need to invest a little more of your " "time in reading the following sections. If you're ready for that, grab some " "of your favourite beverage and carry on." msgstr "" #: ../Doc/howto/logging.rst:314 msgid "" "If your logging needs are simple, then use the above examples to incorporate " "logging into your own scripts, and if you run into problems or don't " "understand something, please post a question on the comp.lang.python Usenet " "group (available at https://groups.google.com/group/comp.lang.python) and " "you should receive help before too long." msgstr "" #: ../Doc/howto/logging.rst:320 msgid "" "Still here? You can carry on reading the next few sections, which provide a " "slightly more advanced/in-depth tutorial than the basic one above. After " "that, you can take a look at the :ref:`logging-cookbook`." msgstr "" #: ../Doc/howto/logging.rst:328 msgid "Advanced Logging Tutorial" msgstr "" #: ../Doc/howto/logging.rst:330 msgid "" "The logging library takes a modular approach and offers several categories " "of components: loggers, handlers, filters, and formatters." msgstr "" #: ../Doc/howto/logging.rst:333 msgid "Loggers expose the interface that application code directly uses." msgstr "" #: ../Doc/howto/logging.rst:334 msgid "" "Handlers send the log records (created by loggers) to the appropriate " "destination." msgstr "" #: ../Doc/howto/logging.rst:336 msgid "" "Filters provide a finer grained facility for determining which log records " "to output." msgstr "" #: ../Doc/howto/logging.rst:338 msgid "Formatters specify the layout of log records in the final output." msgstr "" #: ../Doc/howto/logging.rst:340 msgid "" "Log event information is passed between loggers, handlers, filters and " "formatters in a :class:`LogRecord` instance." msgstr "" #: ../Doc/howto/logging.rst:343 msgid "" "Logging is performed by calling methods on instances of the :class:`Logger` " "class (hereafter called :dfn:`loggers`). Each instance has a name, and they " "are conceptually arranged in a namespace hierarchy using dots (periods) as " "separators. For example, a logger named 'scan' is the parent of loggers " "'scan.text', 'scan.html' and 'scan.pdf'. Logger names can be anything you " "want, and indicate the area of an application in which a logged message " "originates." msgstr "" #: ../Doc/howto/logging.rst:350 msgid "" "A good convention to use when naming loggers is to use a module-level " "logger, in each module which uses logging, named as follows::" msgstr "" #: ../Doc/howto/logging.rst:355 msgid "" "This means that logger names track the package/module hierarchy, and it's " "intuitively obvious where events are logged just from the logger name." msgstr "" #: ../Doc/howto/logging.rst:358 msgid "" "The root of the hierarchy of loggers is called the root logger. That's the " "logger used by the functions :func:`debug`, :func:`info`, :func:`warning`, :" "func:`error` and :func:`critical`, which just call the same-named method of " "the root logger. The functions and the methods have the same signatures. The " "root logger's name is printed as 'root' in the logged output." msgstr "" #: ../Doc/howto/logging.rst:364 msgid "" "It is, of course, possible to log messages to different destinations. " "Support is included in the package for writing log messages to files, HTTP " "GET/POST locations, email via SMTP, generic sockets, queues, or OS-specific " "logging mechanisms such as syslog or the Windows NT event log. Destinations " "are served by :dfn:`handler` classes. You can create your own log " "destination class if you have special requirements not met by any of the " "built-in handler classes." msgstr "" #: ../Doc/howto/logging.rst:371 msgid "" "By default, no destination is set for any logging messages. You can specify " "a destination (such as console or file) by using :func:`basicConfig` as in " "the tutorial examples. If you call the functions :func:`debug`, :func:" "`info`, :func:`warning`, :func:`error` and :func:`critical`, they will check " "to see if no destination is set; and if one is not set, they will set a " "destination of the console (``sys.stderr``) and a default format for the " "displayed message before delegating to the root logger to do the actual " "message output." msgstr "" #: ../Doc/howto/logging.rst:379 msgid "The default format set by :func:`basicConfig` for messages is::" msgstr "" #: ../Doc/howto/logging.rst:383 msgid "" "You can change this by passing a format string to :func:`basicConfig` with " "the *format* keyword argument. For all options regarding how a format string " "is constructed, see :ref:`formatter-objects`." msgstr "" #: ../Doc/howto/logging.rst:388 msgid "Logging Flow" msgstr "" #: ../Doc/howto/logging.rst:390 msgid "" "The flow of log event information in loggers and handlers is illustrated in " "the following diagram." msgstr "" #: ../Doc/howto/logging.rst:396 msgid "Loggers" msgstr "" #: ../Doc/howto/logging.rst:398 msgid "" ":class:`Logger` objects have a threefold job. First, they expose several " "methods to application code so that applications can log messages at " "runtime. Second, logger objects determine which log messages to act upon " "based upon severity (the default filtering facility) or filter objects. " "Third, logger objects pass along relevant log messages to all interested log " "handlers." msgstr "" #: ../Doc/howto/logging.rst:404 msgid "" "The most widely used methods on logger objects fall into two categories: " "configuration and message sending." msgstr "" #: ../Doc/howto/logging.rst:407 msgid "These are the most common configuration methods:" msgstr "" #: ../Doc/howto/logging.rst:409 msgid "" ":meth:`Logger.setLevel` specifies the lowest-severity log message a logger " "will handle, where debug is the lowest built-in severity level and critical " "is the highest built-in severity. For example, if the severity level is " "INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL " "messages and will ignore DEBUG messages." msgstr "" #: ../Doc/howto/logging.rst:415 msgid "" ":meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove " "handler objects from the logger object. Handlers are covered in more detail " "in :ref:`handler-basic`." msgstr "" #: ../Doc/howto/logging.rst:419 msgid "" ":meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove " "filter objects from the logger object. Filters are covered in more detail " "in :ref:`filter`." msgstr "" #: ../Doc/howto/logging.rst:423 msgid "" "You don't need to always call these methods on every logger you create. See " "the last two paragraphs in this section." msgstr "" #: ../Doc/howto/logging.rst:426 msgid "" "With the logger object configured, the following methods create log messages:" msgstr "" #: ../Doc/howto/logging.rst:428 msgid "" ":meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`, :meth:" "`Logger.error`, and :meth:`Logger.critical` all create log records with a " "message and a level that corresponds to their respective method names. The " "message is actually a format string, which may contain the standard string " "substitution syntax of ``%s``, ``%d``, ``%f``, and so on. The rest of their " "arguments is a list of objects that correspond with the substitution fields " "in the message. With regard to ``**kwargs``, the logging methods care only " "about a keyword of ``exc_info`` and use it to determine whether to log " "exception information." msgstr "" #: ../Doc/howto/logging.rst:438 msgid "" ":meth:`Logger.exception` creates a log message similar to :meth:`Logger." "error`. The difference is that :meth:`Logger.exception` dumps a stack trace " "along with it. Call this method only from an exception handler." msgstr "" #: ../Doc/howto/logging.rst:442 msgid "" ":meth:`Logger.log` takes a log level as an explicit argument. This is a " "little more verbose for logging messages than using the log level " "convenience methods listed above, but this is how to log at custom log " "levels." msgstr "" #: ../Doc/howto/logging.rst:446 msgid "" ":func:`getLogger` returns a reference to a logger instance with the " "specified name if it is provided, or ``root`` if not. The names are period-" "separated hierarchical structures. Multiple calls to :func:`getLogger` with " "the same name will return a reference to the same logger object. Loggers " "that are further down in the hierarchical list are children of loggers " "higher up in the list. For example, given a logger with a name of ``foo``, " "loggers with names of ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all " "descendants of ``foo``." msgstr "" #: ../Doc/howto/logging.rst:454 msgid "" "Loggers have a concept of *effective level*. If a level is not explicitly " "set on a logger, the level of its parent is used instead as its effective " "level. If the parent has no explicit level set, *its* parent is examined, " "and so on - all ancestors are searched until an explicitly set level is " "found. The root logger always has an explicit level set (``WARNING`` by " "default). When deciding whether to process an event, the effective level of " "the logger is used to determine whether the event is passed to the logger's " "handlers." msgstr "" #: ../Doc/howto/logging.rst:462 msgid "" "Child loggers propagate messages up to the handlers associated with their " "ancestor loggers. Because of this, it is unnecessary to define and configure " "handlers for all the loggers an application uses. It is sufficient to " "configure handlers for a top-level logger and create child loggers as " "needed. (You can, however, turn off propagation by setting the *propagate* " "attribute of a logger to *False*.)" msgstr "" #: ../Doc/howto/logging.rst:473 msgid "Handlers" msgstr "" #: ../Doc/howto/logging.rst:475 msgid "" ":class:`~logging.Handler` objects are responsible for dispatching the " "appropriate log messages (based on the log messages' severity) to the " "handler's specified destination. :class:`Logger` objects can add zero or " "more handler objects to themselves with an :meth:`~Logger.addHandler` " "method. As an example scenario, an application may want to send all log " "messages to a log file, all log messages of error or higher to stdout, and " "all messages of critical to an email address. This scenario requires three " "individual handlers where each handler is responsible for sending messages " "of a specific severity to a specific location." msgstr "" #: ../Doc/howto/logging.rst:485 msgid "" "The standard library includes quite a few handler types (see :ref:`useful-" "handlers`); the tutorials use mainly :class:`StreamHandler` and :class:" "`FileHandler` in its examples." msgstr "" #: ../Doc/howto/logging.rst:489 msgid "" "There are very few methods in a handler for application developers to " "concern themselves with. The only handler methods that seem relevant for " "application developers who are using the built-in handler objects (that is, " "not creating custom handlers) are the following configuration methods:" msgstr "" #: ../Doc/howto/logging.rst:494 msgid "" "The :meth:`~Handler.setLevel` method, just as in logger objects, specifies " "the lowest severity that will be dispatched to the appropriate destination. " "Why are there two :func:`setLevel` methods? The level set in the logger " "determines which severity of messages it will pass to its handlers. The " "level set in each handler determines which messages that handler will send " "on." msgstr "" #: ../Doc/howto/logging.rst:500 msgid "" ":meth:`~Handler.setFormatter` selects a Formatter object for this handler to " "use." msgstr "" #: ../Doc/howto/logging.rst:503 msgid "" ":meth:`~Handler.addFilter` and :meth:`~Handler.removeFilter` respectively " "configure and deconfigure filter objects on handlers." msgstr "" #: ../Doc/howto/logging.rst:506 msgid "" "Application code should not directly instantiate and use instances of :class:" "`Handler`. Instead, the :class:`Handler` class is a base class that defines " "the interface that all handlers should have and establishes some default " "behavior that child classes can use (or override)." msgstr "" #: ../Doc/howto/logging.rst:513 msgid "Formatters" msgstr "" #: ../Doc/howto/logging.rst:515 msgid "" "Formatter objects configure the final order, structure, and contents of the " "log message. Unlike the base :class:`logging.Handler` class, application " "code may instantiate formatter classes, although you could likely subclass " "the formatter if your application needs special behavior. The constructor " "takes three optional arguments -- a message format string, a date format " "string and a style indicator." msgstr "" #: ../Doc/howto/logging.rst:524 msgid "" "If there is no message format string, the default is to use the raw " "message. If there is no date format string, the default date format is::" msgstr "" #: ../Doc/howto/logging.rst:529 msgid "" "with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{' " "or '$'. If one of these is not specified, then '%' will be used." msgstr "" #: ../Doc/howto/logging.rst:532 msgid "" "If the ``style`` is '%', the message format string uses ``%()s`` styled string substitution; the possible keys are documented in :" "ref:`logrecord-attributes`. If the style is '{', the message format string " "is assumed to be compatible with :meth:`str.format` (using keyword " "arguments), while if the style is '$' then the message format string should " "conform to what is expected by :meth:`string.Template.substitute`." msgstr "" #: ../Doc/howto/logging.rst:539 msgid "Added the ``style`` parameter." msgstr "" #: ../Doc/howto/logging.rst:542 msgid "" "The following message format string will log the time in a human-readable " "format, the severity of the message, and the contents of the message, in " "that order::" msgstr "" #: ../Doc/howto/logging.rst:548 msgid "" "Formatters use a user-configurable function to convert the creation time of " "a record to a tuple. By default, :func:`time.localtime` is used; to change " "this for a particular formatter instance, set the ``converter`` attribute of " "the instance to a function with the same signature as :func:`time.localtime` " "or :func:`time.gmtime`. To change it for all formatters, for example if you " "want all logging times to be shown in GMT, set the ``converter`` attribute " "in the Formatter class (to ``time.gmtime`` for GMT display)." msgstr "" #: ../Doc/howto/logging.rst:558 msgid "Configuring Logging" msgstr "" #: ../Doc/howto/logging.rst:562 msgid "Programmers can configure logging in three ways:" msgstr "" #: ../Doc/howto/logging.rst:564 msgid "" "Creating loggers, handlers, and formatters explicitly using Python code that " "calls the configuration methods listed above." msgstr "" #: ../Doc/howto/logging.rst:566 msgid "" "Creating a logging config file and reading it using the :func:`fileConfig` " "function." msgstr "" #: ../Doc/howto/logging.rst:568 msgid "" "Creating a dictionary of configuration information and passing it to the :" "func:`dictConfig` function." msgstr "" #: ../Doc/howto/logging.rst:571 msgid "" "For the reference documentation on the last two options, see :ref:`logging-" "config-api`. The following example configures a very simple logger, a " "console handler, and a simple formatter using Python code::" msgstr "" #: ../Doc/howto/logging.rst:601 msgid "" "Running this module from the command line produces the following output:" msgstr "" #: ../Doc/howto/logging.rst:612 msgid "" "The following Python module creates a logger, handler, and formatter nearly " "identical to those in the example listed above, with the only difference " "being the names of the objects::" msgstr "" #: ../Doc/howto/logging.rst:631 msgid "Here is the logging.conf file::" msgstr "" #: ../Doc/howto/logging.rst:662 msgid "" "The output is nearly identical to that of the non-config-file-based example:" msgstr "" #: ../Doc/howto/logging.rst:673 msgid "" "You can see that the config file approach has a few advantages over the " "Python code approach, mainly separation of configuration and code and the " "ability of noncoders to easily modify the logging properties." msgstr "" #: ../Doc/howto/logging.rst:677 msgid "" "The :func:`fileConfig` function takes a default parameter, " "``disable_existing_loggers``, which defaults to ``True`` for reasons of " "backward compatibility. This may or may not be what you want, since it will " "cause any loggers existing before the :func:`fileConfig` call to be disabled " "unless they (or an ancestor) are explicitly named in the configuration. " "Please refer to the reference documentation for more information, and " "specify ``False`` for this parameter if you wish." msgstr "" #: ../Doc/howto/logging.rst:685 msgid "" "The dictionary passed to :func:`dictConfig` can also specify a Boolean value " "with key ``disable_existing_loggers``, which if not specified explicitly in " "the dictionary also defaults to being interpreted as ``True``. This leads " "to the logger-disabling behaviour described above, which may not be what you " "want - in which case, provide the key explicitly with a value of ``False``." msgstr "" #: ../Doc/howto/logging.rst:695 msgid "" "Note that the class names referenced in config files need to be either " "relative to the logging module, or absolute values which can be resolved " "using normal import mechanisms. Thus, you could use either :class:`~logging." "handlers.WatchedFileHandler` (relative to the logging module) or ``mypackage." "mymodule.MyHandler`` (for a class defined in package ``mypackage`` and " "module ``mymodule``, where ``mypackage`` is available on the Python import " "path)." msgstr "" #: ../Doc/howto/logging.rst:703 msgid "" "In Python 3.2, a new means of configuring logging has been introduced, using " "dictionaries to hold configuration information. This provides a superset of " "the functionality of the config-file-based approach outlined above, and is " "the recommended configuration method for new applications and deployments. " "Because a Python dictionary is used to hold configuration information, and " "since you can populate that dictionary using different means, you have more " "options for configuration. For example, you can use a configuration file in " "JSON format, or, if you have access to YAML processing functionality, a file " "in YAML format, to populate the configuration dictionary. Or, of course, you " "can construct the dictionary in Python code, receive it in pickled form over " "a socket, or use whatever approach makes sense for your application." msgstr "" #: ../Doc/howto/logging.rst:715 msgid "" "Here's an example of the same configuration as above, in YAML format for the " "new dictionary-based approach::" msgstr "" #: ../Doc/howto/logging.rst:737 msgid "" "For more information about logging using a dictionary, see :ref:`logging-" "config-api`." msgstr "" #: ../Doc/howto/logging.rst:741 msgid "What happens if no configuration is provided" msgstr "" #: ../Doc/howto/logging.rst:743 msgid "" "If no logging configuration is provided, it is possible to have a situation " "where a logging event needs to be output, but no handlers can be found to " "output the event. The behaviour of the logging package in these " "circumstances is dependent on the Python version." msgstr "" #: ../Doc/howto/logging.rst:748 msgid "For versions of Python prior to 3.2, the behaviour is as follows:" msgstr "" #: ../Doc/howto/logging.rst:750 msgid "" "If *logging.raiseExceptions* is *False* (production mode), the event is " "silently dropped." msgstr "" #: ../Doc/howto/logging.rst:753 msgid "" "If *logging.raiseExceptions* is *True* (development mode), a message 'No " "handlers could be found for logger X.Y.Z' is printed once." msgstr "" #: ../Doc/howto/logging.rst:756 msgid "In Python 3.2 and later, the behaviour is as follows:" msgstr "" #: ../Doc/howto/logging.rst:758 msgid "" "The event is output using a 'handler of last resort', stored in ``logging." "lastResort``. This internal handler is not associated with any logger, and " "acts like a :class:`~logging.StreamHandler` which writes the event " "description message to the current value of ``sys.stderr`` (therefore " "respecting any redirections which may be in effect). No formatting is done " "on the message - just the bare event description message is printed. The " "handler's level is set to ``WARNING``, so all events at this and greater " "severities will be output." msgstr "" #: ../Doc/howto/logging.rst:767 msgid "" "To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to *None*." msgstr "" #: ../Doc/howto/logging.rst:772 msgid "Configuring Logging for a Library" msgstr "" #: ../Doc/howto/logging.rst:774 msgid "" "When developing a library which uses logging, you should take care to " "document how the library uses logging - for example, the names of loggers " "used. Some consideration also needs to be given to its logging " "configuration. If the using application does not use logging, and library " "code makes logging calls, then (as described in the previous section) events " "of severity ``WARNING`` and greater will be printed to ``sys.stderr``. This " "is regarded as the best default behaviour." msgstr "" #: ../Doc/howto/logging.rst:782 msgid "" "If for some reason you *don't* want these messages printed in the absence of " "any logging configuration, you can attach a do-nothing handler to the top-" "level logger for your library. This avoids the message being printed, since " "a handler will be always be found for the library's events: it just doesn't " "produce any output. If the library user configures logging for application " "use, presumably that configuration will add some handlers, and if levels are " "suitably configured then logging calls made in library code will send output " "to those handlers, as normal." msgstr "" #: ../Doc/howto/logging.rst:791 msgid "" "A do-nothing handler is included in the logging package: :class:`~logging." "NullHandler` (since Python 3.1). An instance of this handler could be added " "to the top-level logger of the logging namespace used by the library (*if* " "you want to prevent your library's logged events being output to ``sys." "stderr`` in the absence of logging configuration). If all logging by a " "library *foo* is done using loggers with names matching 'foo.x', 'foo.x.y', " "etc. then the code::" msgstr "" #: ../Doc/howto/logging.rst:802 msgid "" "should have the desired effect. If an organisation produces a number of " "libraries, then the logger name specified can be 'orgname.foo' rather than " "just 'foo'." msgstr "" #: ../Doc/howto/logging.rst:806 msgid "" "It is strongly advised that you *do not add any handlers other than* :class:" "`~logging.NullHandler` *to your library's loggers*. This is because the " "configuration of handlers is the prerogative of the application developer " "who uses your library. The application developer knows their target audience " "and what handlers are most appropriate for their application: if you add " "handlers 'under the hood', you might well interfere with their ability to " "carry out unit tests and deliver logs which suit their requirements." msgstr "" #: ../Doc/howto/logging.rst:817 msgid "Logging Levels" msgstr "" #: ../Doc/howto/logging.rst:819 msgid "" "The numeric values of logging levels are given in the following table. These " "are primarily of interest if you want to define your own levels, and need " "them to have specific values relative to the predefined levels. If you " "define a level with the same numeric value, it overwrites the predefined " "value; the predefined name is lost." msgstr "" #: ../Doc/howto/logging.rst:826 msgid "Numeric value" msgstr "" #: ../Doc/howto/logging.rst:828 msgid "50" msgstr "50" #: ../Doc/howto/logging.rst:830 msgid "40" msgstr "40" #: ../Doc/howto/logging.rst:832 msgid "30" msgstr "30" #: ../Doc/howto/logging.rst:834 msgid "20" msgstr "20" #: ../Doc/howto/logging.rst:836 msgid "10" msgstr "10" #: ../Doc/howto/logging.rst:838 msgid "``NOTSET``" msgstr "``NOTSET``" #: ../Doc/howto/logging.rst:838 msgid "0" msgstr "0" #: ../Doc/howto/logging.rst:841 msgid "" "Levels can also be associated with loggers, being set either by the " "developer or through loading a saved logging configuration. When a logging " "method is called on a logger, the logger compares its own level with the " "level associated with the method call. If the logger's level is higher than " "the method call's, no logging message is actually generated. This is the " "basic mechanism controlling the verbosity of logging output." msgstr "" #: ../Doc/howto/logging.rst:848 msgid "" "Logging messages are encoded as instances of the :class:`~logging.LogRecord` " "class. When a logger decides to actually log an event, a :class:`~logging." "LogRecord` instance is created from the logging message." msgstr "" #: ../Doc/howto/logging.rst:852 msgid "" "Logging messages are subjected to a dispatch mechanism through the use of :" "dfn:`handlers`, which are instances of subclasses of the :class:`Handler` " "class. Handlers are responsible for ensuring that a logged message (in the " "form of a :class:`LogRecord`) ends up in a particular location (or set of " "locations) which is useful for the target audience for that message (such as " "end users, support desk staff, system administrators, developers). Handlers " "are passed :class:`LogRecord` instances intended for particular " "destinations. Each logger can have zero, one or more handlers associated " "with it (via the :meth:`~Logger.addHandler` method of :class:`Logger`). In " "addition to any handlers directly associated with a logger, *all handlers " "associated with all ancestors of the logger* are called to dispatch the " "message (unless the *propagate* flag for a logger is set to a false value, " "at which point the passing to ancestor handlers stops)." msgstr "" #: ../Doc/howto/logging.rst:866 msgid "" "Just as for loggers, handlers can have levels associated with them. A " "handler's level acts as a filter in the same way as a logger's level does. " "If a handler decides to actually dispatch an event, the :meth:`~Handler." "emit` method is used to send the message to its destination. Most user-" "defined subclasses of :class:`Handler` will need to override this :meth:" "`~Handler.emit`." msgstr "" #: ../Doc/howto/logging.rst:875 msgid "Custom Levels" msgstr "" #: ../Doc/howto/logging.rst:877 msgid "" "Defining your own levels is possible, but should not be necessary, as the " "existing levels have been chosen on the basis of practical experience. " "However, if you are convinced that you need custom levels, great care should " "be exercised when doing this, and it is possibly *a very bad idea to define " "custom levels if you are developing a library*. That's because if multiple " "library authors all define their own custom levels, there is a chance that " "the logging output from such multiple libraries used together will be " "difficult for the using developer to control and/or interpret, because a " "given numeric value might mean different things for different libraries." msgstr "" #: ../Doc/howto/logging.rst:890 msgid "Useful Handlers" msgstr "" #: ../Doc/howto/logging.rst:892 msgid "" "In addition to the base :class:`Handler` class, many useful subclasses are " "provided:" msgstr "" #: ../Doc/howto/logging.rst:895 msgid "" ":class:`StreamHandler` instances send messages to streams (file-like " "objects)." msgstr "" #: ../Doc/howto/logging.rst:898 msgid ":class:`FileHandler` instances send messages to disk files." msgstr "" #: ../Doc/howto/logging.rst:900 msgid "" ":class:`~handlers.BaseRotatingHandler` is the base class for handlers that " "rotate log files at a certain point. It is not meant to be instantiated " "directly. Instead, use :class:`~handlers.RotatingFileHandler` or :class:" "`~handlers.TimedRotatingFileHandler`." msgstr "" #: ../Doc/howto/logging.rst:905 msgid "" ":class:`~handlers.RotatingFileHandler` instances send messages to disk " "files, with support for maximum log file sizes and log file rotation." msgstr "" #: ../Doc/howto/logging.rst:908 msgid "" ":class:`~handlers.TimedRotatingFileHandler` instances send messages to disk " "files, rotating the log file at certain timed intervals." msgstr "" #: ../Doc/howto/logging.rst:911 msgid "" ":class:`~handlers.SocketHandler` instances send messages to TCP/IP sockets. " "Since 3.4, Unix domain sockets are also supported." msgstr "" #: ../Doc/howto/logging.rst:914 msgid "" ":class:`~handlers.DatagramHandler` instances send messages to UDP sockets. " "Since 3.4, Unix domain sockets are also supported." msgstr "" #: ../Doc/howto/logging.rst:917 msgid "" ":class:`~handlers.SMTPHandler` instances send messages to a designated email " "address." msgstr "" #: ../Doc/howto/logging.rst:920 msgid "" ":class:`~handlers.SysLogHandler` instances send messages to a Unix syslog " "daemon, possibly on a remote machine." msgstr "" #: ../Doc/howto/logging.rst:923 msgid "" ":class:`~handlers.NTEventLogHandler` instances send messages to a Windows " "NT/2000/XP event log." msgstr "" #: ../Doc/howto/logging.rst:926 msgid "" ":class:`~handlers.MemoryHandler` instances send messages to a buffer in " "memory, which is flushed whenever specific criteria are met." msgstr "" #: ../Doc/howto/logging.rst:929 msgid "" ":class:`~handlers.HTTPHandler` instances send messages to an HTTP server " "using either ``GET`` or ``POST`` semantics." msgstr "" #: ../Doc/howto/logging.rst:932 msgid "" ":class:`~handlers.WatchedFileHandler` instances watch the file they are " "logging to. If the file changes, it is closed and reopened using the file " "name. This handler is only useful on Unix-like systems; Windows does not " "support the underlying mechanism used." msgstr "" #: ../Doc/howto/logging.rst:937 msgid "" ":class:`~handlers.QueueHandler` instances send messages to a queue, such as " "those implemented in the :mod:`queue` or :mod:`multiprocessing` modules." msgstr "" #: ../Doc/howto/logging.rst:940 msgid "" ":class:`NullHandler` instances do nothing with error messages. They are used " "by library developers who want to use logging, but want to avoid the 'No " "handlers could be found for logger XXX' message which can be displayed if " "the library user has not configured logging. See :ref:`library-config` for " "more information." msgstr "" #: ../Doc/howto/logging.rst:946 msgid "The :class:`NullHandler` class." msgstr "" #: ../Doc/howto/logging.rst:949 msgid "The :class:`~handlers.QueueHandler` class." msgstr "" #: ../Doc/howto/logging.rst:952 msgid "" "The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler` " "classes are defined in the core logging package. The other handlers are " "defined in a sub- module, :mod:`logging.handlers`. (There is also another " "sub-module, :mod:`logging.config`, for configuration functionality.)" msgstr "" #: ../Doc/howto/logging.rst:957 msgid "" "Logged messages are formatted for presentation through instances of the :" "class:`Formatter` class. They are initialized with a format string suitable " "for use with the % operator and a dictionary." msgstr "" #: ../Doc/howto/logging.rst:961 msgid "" "For formatting multiple messages in a batch, instances of :class:`~handlers." "BufferingFormatter` can be used. In addition to the format string (which is " "applied to each message in the batch), there is provision for header and " "trailer format strings." msgstr "" #: ../Doc/howto/logging.rst:966 msgid "" "When filtering based on logger level and/or handler level is not enough, " "instances of :class:`Filter` can be added to both :class:`Logger` and :class:" "`Handler` instances (through their :meth:`~Handler.addFilter` method). " "Before deciding to process a message further, both loggers and handlers " "consult all their filters for permission. If any filter returns a false " "value, the message is not processed further." msgstr "" #: ../Doc/howto/logging.rst:973 msgid "" "The basic :class:`Filter` functionality allows filtering by specific logger " "name. If this feature is used, messages sent to the named logger and its " "children are allowed through the filter, and all others dropped." msgstr "" #: ../Doc/howto/logging.rst:981 msgid "Exceptions raised during logging" msgstr "" #: ../Doc/howto/logging.rst:983 msgid "" "The logging package is designed to swallow exceptions which occur while " "logging in production. This is so that errors which occur while handling " "logging events - such as logging misconfiguration, network or other similar " "errors - do not cause the application using logging to terminate prematurely." msgstr "" #: ../Doc/howto/logging.rst:988 msgid "" ":class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never " "swallowed. Other exceptions which occur during the :meth:`~Handler.emit` " "method of a :class:`Handler` subclass are passed to its :meth:`~Handler." "handleError` method." msgstr "" #: ../Doc/howto/logging.rst:993 msgid "" "The default implementation of :meth:`~Handler.handleError` in :class:" "`Handler` checks to see if a module-level variable, :data:`raiseExceptions`, " "is set. If set, a traceback is printed to :data:`sys.stderr`. If not set, " "the exception is swallowed." msgstr "" #: ../Doc/howto/logging.rst:998 msgid "" "The default value of :data:`raiseExceptions` is ``True``. This is because " "during development, you typically want to be notified of any exceptions that " "occur. It's advised that you set :data:`raiseExceptions` to ``False`` for " "production usage." msgstr "" #: ../Doc/howto/logging.rst:1008 msgid "Using arbitrary objects as messages" msgstr "" #: ../Doc/howto/logging.rst:1010 msgid "" "In the preceding sections and examples, it has been assumed that the message " "passed when logging the event is a string. However, this is not the only " "possibility. You can pass an arbitrary object as a message, and its :meth:" "`~object.__str__` method will be called when the logging system needs to " "convert it to a string representation. In fact, if you want to, you can " "avoid computing a string representation altogether - for example, the :class:" "`~handlers.SocketHandler` emits an event by pickling it and sending it over " "the wire." msgstr "" #: ../Doc/howto/logging.rst:1021 msgid "Optimization" msgstr "" #: ../Doc/howto/logging.rst:1023 msgid "" "Formatting of message arguments is deferred until it cannot be avoided. " "However, computing the arguments passed to the logging method can also be " "expensive, and you may want to avoid doing it if the logger will just throw " "away your event. To decide what to do, you can call the :meth:`~Logger." "isEnabledFor` method which takes a level argument and returns true if the " "event would be created by the Logger for that level of call. You can write " "code like this::" msgstr "" #: ../Doc/howto/logging.rst:1035 msgid "" "so that if the logger's threshold is set above ``DEBUG``, the calls to :func:" "`expensive_func1` and :func:`expensive_func2` are never made." msgstr "" #: ../Doc/howto/logging.rst:1038 msgid "" "In some cases, :meth:`~Logger.isEnabledFor` can itself be more expensive " "than you'd like (e.g. for deeply nested loggers where an explicit level is " "only set high up in the logger hierarchy). In such cases (or if you want to " "avoid calling a method in tight loops), you can cache the result of a call " "to :meth:`~Logger.isEnabledFor` in a local or instance variable, and use " "that instead of calling the method each time. Such a cached value would only " "need to be recomputed when the logging configuration changes dynamically " "while the application is running (which is not all that common)." msgstr "" #: ../Doc/howto/logging.rst:1047 msgid "" "There are other optimizations which can be made for specific applications " "which need more precise control over what logging information is collected. " "Here's a list of things you can do to avoid processing during logging which " "you don't need:" msgstr "" #: ../Doc/howto/logging.rst:1053 msgid "What you don't want to collect" msgstr "" #: ../Doc/howto/logging.rst:1053 msgid "How to avoid collecting it" msgstr "" #: ../Doc/howto/logging.rst:1055 msgid "Information about where calls were made from." msgstr "" #: ../Doc/howto/logging.rst:1055 msgid "" "Set ``logging._srcfile`` to ``None``. This avoids calling :func:`sys." "_getframe`, which may help to speed up your code in environments like PyPy " "(which can't speed up code that uses :func:`sys._getframe`), if and when " "PyPy supports Python 3.x." msgstr "" #: ../Doc/howto/logging.rst:1063 msgid "Threading information." msgstr "" #: ../Doc/howto/logging.rst:1063 msgid "Set ``logging.logThreads`` to ``0``." msgstr "" #: ../Doc/howto/logging.rst:1065 msgid "Process information." msgstr "" #: ../Doc/howto/logging.rst:1065 msgid "Set ``logging.logProcesses`` to ``0``." msgstr "" #: ../Doc/howto/logging.rst:1068 msgid "" "Also note that the core logging module only includes the basic handlers. If " "you don't import :mod:`logging.handlers` and :mod:`logging.config`, they " "won't take up any memory." msgstr "" #: ../Doc/howto/logging.rst:1075 ../Doc/howto/logging-cookbook.rst:1306 msgid "Module :mod:`logging`" msgstr "" #: ../Doc/howto/logging.rst:1075 ../Doc/howto/logging-cookbook.rst:1306 msgid "API reference for the logging module." msgstr "" #: ../Doc/howto/logging.rst:1078 ../Doc/howto/logging-cookbook.rst:1309 msgid "Module :mod:`logging.config`" msgstr "" #: ../Doc/howto/logging.rst:1078 ../Doc/howto/logging-cookbook.rst:1309 msgid "Configuration API for the logging module." msgstr "" #: ../Doc/howto/logging.rst:1081 ../Doc/howto/logging-cookbook.rst:1312 msgid "Module :mod:`logging.handlers`" msgstr "" #: ../Doc/howto/logging.rst:1081 ../Doc/howto/logging-cookbook.rst:1312 msgid "Useful handlers included with the logging module." msgstr "" #: ../Doc/howto/logging.rst:1083 msgid ":ref:`A logging cookbook `" msgstr "" #: ../Doc/howto/logging-cookbook.rst:5 msgid "Logging Cookbook" msgstr "" #: ../Doc/howto/logging-cookbook.rst:9 msgid "" "This page contains a number of recipes related to logging, which have been " "found useful in the past." msgstr "" #: ../Doc/howto/logging-cookbook.rst:15 msgid "Using logging in multiple modules" msgstr "" #: ../Doc/howto/logging-cookbook.rst:17 msgid "" "Multiple calls to ``logging.getLogger('someLogger')`` return a reference to " "the same logger object. This is true not only within the same module, but " "also across modules as long as it is in the same Python interpreter " "process. It is true for references to the same object; additionally, " "application code can define and configure a parent logger in one module and " "create (but not configure) a child logger in a separate module, and all " "logger calls to the child will pass up to the parent. Here is a main " "module::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:55 msgid "Here is the auxiliary module::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:99 msgid "Logging from multiple threads" msgstr "" #: ../Doc/howto/logging-cookbook.rst:101 msgid "" "Logging from multiple threads requires no special effort. The following " "example shows logging from the main (initial) thread and another thread::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:130 msgid "When run, the script should print something like the following::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:150 msgid "" "This shows the logging output interspersed as one might expect. This " "approach works for more threads than shown here, of course." msgstr "" #: ../Doc/howto/logging-cookbook.rst:154 msgid "Multiple handlers and formatters" msgstr "" #: ../Doc/howto/logging-cookbook.rst:156 msgid "" "Loggers are plain Python objects. The :meth:`~Logger.addHandler` method has " "no minimum or maximum quota for the number of handlers you may add. " "Sometimes it will be beneficial for an application to log all messages of " "all severities to a text file while simultaneously logging errors or above " "to the console. To set this up, simply configure the appropriate handlers. " "The logging calls in the application code will remain unchanged. Here is a " "slight modification to the previous simple module-based configuration " "example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:189 msgid "" "Notice that the 'application' code does not care about multiple handlers. " "All that changed was the addition and configuration of a new handler named " "*fh*." msgstr "" #: ../Doc/howto/logging-cookbook.rst:192 msgid "" "The ability to create new handlers with higher- or lower-severity filters " "can be very helpful when writing and testing an application. Instead of " "using many ``print`` statements for debugging, use ``logger.debug``: Unlike " "the print statements, which you will have to delete or comment out later, " "the logger.debug statements can remain intact in the source code and remain " "dormant until you need them again. At that time, the only change that needs " "to happen is to modify the severity level of the logger and/or handler to " "debug." msgstr "" #: ../Doc/howto/logging-cookbook.rst:203 msgid "Logging to multiple destinations" msgstr "" #: ../Doc/howto/logging-cookbook.rst:205 msgid "" "Let's say you want to log to console and file with different message formats " "and in differing circumstances. Say you want to log messages with levels of " "DEBUG and higher to file, and those messages at level INFO and higher to the " "console. Let's also assume that the file should contain timestamps, but the " "console messages should not. Here's how you can achieve this::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:243 msgid "When you run this, on the console you will see ::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:250 msgid "and in the file you will see something like ::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:258 msgid "" "As you can see, the DEBUG message only shows up in the file. The other " "messages are sent to both destinations." msgstr "" #: ../Doc/howto/logging-cookbook.rst:261 msgid "" "This example uses console and file handlers, but you can use any number and " "combination of handlers you choose." msgstr "" #: ../Doc/howto/logging-cookbook.rst:266 msgid "Configuration server example" msgstr "" #: ../Doc/howto/logging-cookbook.rst:268 msgid "Here is an example of a module using the logging configuration server::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:299 msgid "" "And here is a script that takes a filename and sends that file to the " "server, properly preceded with the binary-encoded length, as the new logging " "configuration::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:322 msgid "Dealing with handlers that block" msgstr "" #: ../Doc/howto/logging-cookbook.rst:326 msgid "" "Sometimes you have to get your logging handlers to do their work without " "blocking the thread you're logging from. This is common in Web applications, " "though of course it also occurs in other scenarios." msgstr "" #: ../Doc/howto/logging-cookbook.rst:330 msgid "" "A common culprit which demonstrates sluggish behaviour is the :class:" "`SMTPHandler`: sending emails can take a long time, for a number of reasons " "outside the developer's control (for example, a poorly performing mail or " "network infrastructure). But almost any network-based handler can block: " "Even a :class:`SocketHandler` operation may do a DNS query under the hood " "which is too slow (and this query can be deep in the socket library code, " "below the Python layer, and outside your control)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:338 msgid "" "One solution is to use a two-part approach. For the first part, attach only " "a :class:`QueueHandler` to those loggers which are accessed from performance-" "critical threads. They simply write to their queue, which can be sized to a " "large enough capacity or initialized with no upper bound to their size. The " "write to the queue will typically be accepted quickly, though you will " "probably need to catch the :exc:`queue.Full` exception as a precaution in " "your code. If you are a library developer who has performance-critical " "threads in their code, be sure to document this (together with a suggestion " "to attach only ``QueueHandlers`` to your loggers) for the benefit of other " "developers who will use your code." msgstr "" #: ../Doc/howto/logging-cookbook.rst:349 msgid "" "The second part of the solution is :class:`QueueListener`, which has been " "designed as the counterpart to :class:`QueueHandler`. A :class:" "`QueueListener` is very simple: it's passed a queue and some handlers, and " "it fires up an internal thread which listens to its queue for LogRecords " "sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that " "matter). The ``LogRecords`` are removed from the queue and passed to the " "handlers for processing." msgstr "" #: ../Doc/howto/logging-cookbook.rst:357 msgid "" "The advantage of having a separate :class:`QueueListener` class is that you " "can use the same instance to service multiple ``QueueHandlers``. This is " "more resource-friendly than, say, having threaded versions of the existing " "handler classes, which would eat up one thread per handler for no particular " "benefit." msgstr "" #: ../Doc/howto/logging-cookbook.rst:362 msgid "An example of using these two classes follows (imports omitted)::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:380 msgid "which, when run, will produce:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:386 msgid "" "Prior to Python 3.5, the :class:`QueueListener` always passed every message " "received from the queue to every handler it was initialized with. (This was " "because it was assumed that level filtering was all done on the other side, " "where the queue is filled.) From 3.5 onwards, this behaviour can be changed " "by passing a keyword argument ``respect_handler_level=True`` to the " "listener's constructor. When this is done, the listener compares the level " "of each message with the handler's level, and only passes a message to a " "handler if it's appropriate to do so." msgstr "" #: ../Doc/howto/logging-cookbook.rst:399 msgid "Sending and receiving logging events across a network" msgstr "" #: ../Doc/howto/logging-cookbook.rst:401 msgid "" "Let's say you want to send logging events across a network, and handle them " "at the receiving end. A simple way of doing this is attaching a :class:" "`SocketHandler` instance to the root logger at the sending end::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:429 msgid "" "At the receiving end, you can set up a receiver using the :mod:" "`socketserver` module. Here is a basic working example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:517 msgid "" "First run the server, and then the client. On the client side, nothing is " "printed on the console; on the server side, you should see something like::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:527 msgid "" "Note that there are some security issues with pickle in some scenarios. If " "these affect you, you can use an alternative serialization scheme by " "overriding the :meth:`~handlers.SocketHandler.makePickle` method and " "implementing your alternative there, as well as adapting the above script to " "use your alternative serialization." msgstr "" #: ../Doc/howto/logging-cookbook.rst:537 msgid "Adding contextual information to your logging output" msgstr "" #: ../Doc/howto/logging-cookbook.rst:539 msgid "" "Sometimes you want logging output to contain contextual information in " "addition to the parameters passed to the logging call. For example, in a " "networked application, it may be desirable to log client-specific " "information in the log (e.g. remote client's username, or IP address). " "Although you could use the *extra* parameter to achieve this, it's not " "always convenient to pass the information in this way. While it might be " "tempting to create :class:`Logger` instances on a per-connection basis, this " "is not a good idea because these instances are not garbage collected. While " "this is not a problem in practice, when the number of :class:`Logger` " "instances is dependent on the level of granularity you want to use in " "logging an application, it could be hard to manage if the number of :class:" "`Logger` instances becomes effectively unbounded." msgstr "" #: ../Doc/howto/logging-cookbook.rst:554 msgid "Using LoggerAdapters to impart contextual information" msgstr "" #: ../Doc/howto/logging-cookbook.rst:556 msgid "" "An easy way in which you can pass contextual information to be output along " "with logging event information is to use the :class:`LoggerAdapter` class. " "This class is designed to look like a :class:`Logger`, so that you can call :" "meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`, :meth:" "`exception`, :meth:`critical` and :meth:`log`. These methods have the same " "signatures as their counterparts in :class:`Logger`, so you can use the two " "types of instances interchangeably." msgstr "" #: ../Doc/howto/logging-cookbook.rst:564 msgid "" "When you create an instance of :class:`LoggerAdapter`, you pass it a :class:" "`Logger` instance and a dict-like object which contains your contextual " "information. When you call one of the logging methods on an instance of :" "class:`LoggerAdapter`, it delegates the call to the underlying instance of :" "class:`Logger` passed to its constructor, and arranges to pass the " "contextual information in the delegated call. Here's a snippet from the code " "of :class:`LoggerAdapter`::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:580 msgid "" "The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where " "the contextual information is added to the logging output. It's passed the " "message and keyword arguments of the logging call, and it passes back " "(potentially) modified versions of these to use in the call to the " "underlying logger. The default implementation of this method leaves the " "message alone, but inserts an 'extra' key in the keyword argument whose " "value is the dict-like object passed to the constructor. Of course, if you " "had passed an 'extra' keyword argument in the call to the adapter, it will " "be silently overwritten." msgstr "" #: ../Doc/howto/logging-cookbook.rst:589 msgid "" "The advantage of using 'extra' is that the values in the dict-like object " "are merged into the :class:`LogRecord` instance's __dict__, allowing you to " "use customized strings with your :class:`Formatter` instances which know " "about the keys of the dict-like object. If you need a different method, e.g. " "if you want to prepend or append the contextual information to the message " "string, you just need to subclass :class:`LoggerAdapter` and override :meth:" "`~LoggerAdapter.process` to do what you need. Here is a simple example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:605 msgid "which you can use like this::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:610 msgid "" "Then any events that you log to the adapter will have the value of " "``some_conn_id`` prepended to the log messages." msgstr "" #: ../Doc/howto/logging-cookbook.rst:614 msgid "Using objects other than dicts to pass contextual information" msgstr "" #: ../Doc/howto/logging-cookbook.rst:616 msgid "" "You don't need to pass an actual dict to a :class:`LoggerAdapter` - you " "could pass an instance of a class which implements ``__getitem__`` and " "``__iter__`` so that it looks like a dict to logging. This would be useful " "if you want to generate values dynamically (whereas the values in a dict " "would be constant)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:625 msgid "Using Filters to impart contextual information" msgstr "" #: ../Doc/howto/logging-cookbook.rst:627 msgid "" "You can also add contextual information to log output using a user-defined :" "class:`Filter`. ``Filter`` instances are allowed to modify the " "``LogRecords`` passed to them, including adding additional attributes which " "can then be output using a suitable format string, or if needed a custom :" "class:`Formatter`." msgstr "" #: ../Doc/howto/logging-cookbook.rst:632 msgid "" "For example in a web application, the request being processed (or at least, " "the interesting parts of it) can be stored in a threadlocal (:class:" "`threading.local`) variable, and then accessed from a ``Filter`` to add, " "say, information from the request - say, the remote IP address and remote " "user's username - to the ``LogRecord``, using the attribute names 'ip' and " "'user' as in the ``LoggerAdapter`` example above. In that case, the same " "format string can be used to get similar output to that shown above. Here's " "an example script::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:678 msgid "which, when run, produces something like::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:697 msgid "Logging to a single file from multiple processes" msgstr "" #: ../Doc/howto/logging-cookbook.rst:699 msgid "" "Although logging is thread-safe, and logging to a single file from multiple " "threads in a single process *is* supported, logging to a single file from " "*multiple processes* is *not* supported, because there is no standard way to " "serialize access to a single file across multiple processes in Python. If " "you need to log to a single file from multiple processes, one way of doing " "this is to have all the processes log to a :class:`~handlers.SocketHandler`, " "and have a separate process which implements a socket server which reads " "from the socket and logs to file. (If you prefer, you can dedicate one " "thread in one of the existing processes to perform this function.) :ref:" "`This section ` documents this approach in more detail and " "includes a working socket receiver which can be used as a starting point for " "you to adapt in your own applications." msgstr "" #: ../Doc/howto/logging-cookbook.rst:712 msgid "" "If you are using a recent version of Python which includes the :mod:" "`multiprocessing` module, you could write your own handler which uses the :" "class:`~multiprocessing.Lock` class from this module to serialize access to " "the file from your processes. The existing :class:`FileHandler` and " "subclasses do not make use of :mod:`multiprocessing` at present, though they " "may do so in the future. Note that at present, the :mod:`multiprocessing` " "module does not provide working lock functionality on all platforms (see " "https://bugs.python.org/issue3770)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:723 msgid "" "Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send " "all logging events to one of the processes in your multi-process " "application. The following example script demonstrates how you can do this; " "in the example a separate listener process listens for events sent by other " "processes and logs them according to its own logging configuration. Although " "the example only demonstrates one way of doing it (for example, you may want " "to use a listener thread rather than a separate listener process -- the " "implementation would be analogous) it does allow for completely different " "logging configurations for the listener and the other processes in your " "application, and can be used as the basis for code meeting your own specific " "requirements::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:839 msgid "" "A variant of the above script keeps the logging in the main process, in a " "separate thread::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:934 msgid "" "This variant shows how you can e.g. apply configuration for particular " "loggers - e.g. the ``foo`` logger has a special handler which stores all " "events in the ``foo`` subsystem in a file ``mplog-foo.log``. This will be " "used by the logging machinery in the main process (even though the logging " "events are generated in the worker processes) to direct the messages to the " "appropriate destinations." msgstr "" #: ../Doc/howto/logging-cookbook.rst:941 msgid "Using file rotation" msgstr "" #: ../Doc/howto/logging-cookbook.rst:946 msgid "" "Sometimes you want to let a log file grow to a certain size, then open a new " "file and log to that. You may want to keep a certain number of these files, " "and when that many files have been created, rotate the files so that the " "number of files and the size of the files both remain bounded. For this " "usage pattern, the logging package provides a :class:`~handlers." "RotatingFileHandler`::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:978 msgid "" "The result should be 6 separate files, each with part of the log history for " "the application::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:988 msgid "" "The most current file is always :file:`logging_rotatingfile_example.out`, " "and each time it reaches the size limit it is renamed with the suffix " "``.1``. Each of the existing backup files is renamed to increment the suffix " "(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased." msgstr "" #: ../Doc/howto/logging-cookbook.rst:993 msgid "" "Obviously this example sets the log length much too small as an extreme " "example. You would want to set *maxBytes* to an appropriate value." msgstr "" #: ../Doc/howto/logging-cookbook.rst:999 msgid "Use of alternative formatting styles" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1001 msgid "" "When logging was added to the Python standard library, the only way of " "formatting messages with variable content was to use the %-formatting " "method. Since then, Python has gained two new formatting approaches: :class:" "`string.Template` (added in Python 2.4) and :meth:`str.format` (added in " "Python 2.6)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1007 msgid "" "Logging (as of 3.2) provides improved support for these two additional " "formatting styles. The :class:`Formatter` class been enhanced to take an " "additional, optional keyword parameter named ``style``. This defaults to " "``'%'``, but other possible values are ``'{'`` and ``'$'``, which correspond " "to the other two formatting styles. Backwards compatibility is maintained by " "default (as you would expect), but by explicitly specifying a style " "parameter, you get the ability to specify format strings which work with :" "meth:`str.format` or :class:`string.Template`. Here's an example console " "session to show the possibilities:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1041 msgid "" "Note that the formatting of logging messages for final output to logs is " "completely independent of how an individual logging message is constructed. " "That can still use %-formatting, as shown here::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1049 msgid "" "Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take " "positional parameters for the actual logging message itself, with keyword " "parameters used only for determining options for how to handle the actual " "logging call (e.g. the ``exc_info`` keyword parameter to indicate that " "traceback information should be logged, or the ``extra`` keyword parameter " "to indicate additional contextual information to be added to the log). So " "you cannot directly make logging calls using :meth:`str.format` or :class:" "`string.Template` syntax, because internally the logging package uses %-" "formatting to merge the format string and the variable arguments. There " "would no changing this while preserving backward compatibility, since all " "logging calls which are out there in existing code will be using %-format " "strings." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1062 msgid "" "There is, however, a way that you can use {}- and $- formatting to construct " "your individual log messages. Recall that for a message you can use an " "arbitrary object as a message format string, and that the logging package " "will call ``str()`` on that object to get the actual format string. Consider " "the following two classes::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1086 msgid "" "Either of these can be used in place of a format string, to allow {}- or $-" "formatting to be used to build the actual \"message\" part which appears in " "the formatted log output in place of \"%(message)s\" or \"{message}\" or " "\"$message\". It's a little unwieldy to use the class names whenever you " "want to log something, but it's quite palatable if you use an alias such as " "__ (double underscore – not to be confused with _, the single underscore " "used as a synonym/alias for :func:`gettext.gettext` or its brethren)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1094 msgid "" "The above classes are not included in Python, though they're easy enough to " "copy and paste into your own code. They can be used as follows (assuming " "that they're declared in a module called ``wherever``):" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1116 msgid "" "While the above examples use ``print()`` to show how the formatting works, " "you would of course use ``logger.debug()`` or similar to actually log using " "this approach." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1120 msgid "" "One thing to note is that you pay no significant performance penalty with " "this approach: the actual formatting happens not when you make the logging " "call, but when (and if) the logged message is actually about to be output to " "a log by a handler. So the only slightly unusual thing which might trip you " "up is that the parentheses go around the format string and the arguments, " "not just the format string. That's because the __ notation is just syntax " "sugar for a constructor call to one of the XXXMessage classes." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1128 msgid "" "If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar " "effect to the above, as in the following example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1159 msgid "" "The above script should log the message ``Hello, world!`` when run with " "Python 3.2 or later." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1168 msgid "Customizing ``LogRecord``" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1170 msgid "" "Every logging event is represented by a :class:`LogRecord` instance. When an " "event is logged and not filtered out by a logger's level, a :class:" "`LogRecord` is created, populated with information about the event and then " "passed to the handlers for that logger (and its ancestors, up to and " "including the logger where further propagation up the hierarchy is " "disabled). Before Python 3.2, there were only two places where this creation " "was done:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1177 msgid "" ":meth:`Logger.makeRecord`, which is called in the normal process of logging " "an event. This invoked :class:`LogRecord` directly to create an instance." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1180 msgid "" ":func:`makeLogRecord`, which is called with a dictionary containing " "attributes to be added to the LogRecord. This is typically invoked when a " "suitable dictionary has been received over the network (e.g. in pickle form " "via a :class:`~handlers.SocketHandler`, or in JSON form via an :class:" "`~handlers.HTTPHandler`)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1186 msgid "" "This has usually meant that if you need to do anything special with a :class:" "`LogRecord`, you've had to do one of the following." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1189 msgid "" "Create your own :class:`Logger` subclass, which overrides :meth:`Logger." "makeRecord`, and set it using :func:`~logging.setLoggerClass` before any " "loggers that you care about are instantiated." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1192 msgid "" "Add a :class:`Filter` to a logger or handler, which does the necessary " "special manipulation you need when its :meth:`~Filter.filter` method is " "called." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1196 msgid "" "The first approach would be a little unwieldy in the scenario where (say) " "several different libraries wanted to do different things. Each would " "attempt to set its own :class:`Logger` subclass, and the one which did this " "last would win." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1201 msgid "" "The second approach works reasonably well for many cases, but does not allow " "you to e.g. use a specialized subclass of :class:`LogRecord`. Library " "developers can set a suitable filter on their loggers, but they would have " "to remember to do this every time they introduced a new logger (which they " "would do simply by adding new packages or modules and doing ::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1209 msgid "" "at module level). It's probably one too many things to think about. " "Developers could also add the filter to a :class:`~logging.NullHandler` " "attached to their top-level logger, but this would not be invoked if an " "application developer attached a handler to a lower-level library logger – " "so output from that handler would not reflect the intentions of the library " "developer." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1215 msgid "" "In Python 3.2 and later, :class:`~logging.LogRecord` creation is done " "through a factory, which you can specify. The factory is just a callable you " "can set with :func:`~logging.setLogRecordFactory`, and interrogate with :" "func:`~logging.getLogRecordFactory`. The factory is invoked with the same " "signature as the :class:`~logging.LogRecord` constructor, as :class:" "`LogRecord` is the default setting for the factory." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1222 msgid "" "This approach allows a custom factory to control all aspects of LogRecord " "creation. For example, you could return a subclass, or just add some " "additional attributes to the record once created, using a pattern similar to " "this::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1235 msgid "" "This pattern allows different libraries to chain factories together, and as " "long as they don't overwrite each other's attributes or unintentionally " "overwrite the attributes provided as standard, there should be no surprises. " "However, it should be borne in mind that each link in the chain adds run-" "time overhead to all logging operations, and the technique should only be " "used when the use of a :class:`Filter` does not provide the desired result." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1246 msgid "Subclassing QueueHandler - a ZeroMQ example" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1248 msgid "" "You can use a :class:`QueueHandler` subclass to send messages to other kinds " "of queues, for example a ZeroMQ 'publish' socket. In the example below,the " "socket is created separately and passed to the handler (as its 'queue')::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1267 msgid "" "Of course there are other ways of organizing this, for example passing in " "the data needed by the handler to create the socket::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1286 msgid "Subclassing QueueListener - a ZeroMQ example" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1288 msgid "" "You can also subclass :class:`QueueListener` to get messages from other " "kinds of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1314 msgid ":ref:`A basic logging tutorial `" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1316 msgid ":ref:`A more advanced logging tutorial `" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1320 msgid "An example dictionary-based configuration" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1322 msgid "" "Below is an example of a logging configuration dictionary - it's taken from " "the `documentation on the Django project `_. This dictionary is passed to :" "func:`~config.dictConfig` to put the configuration into effect::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1378 msgid "" "For more information about this configuration, you can see the `relevant " "section `_ of the Django documentation." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1385 msgid "Using a rotator and namer to customize log rotation processing" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1387 msgid "" "An example of how you can define a namer and rotator is given in the " "following snippet, which shows zlib-based compression of the log file::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1405 msgid "" "These are not \"true\" .gz files, as they are bare compressed data, with no " "\"container\" such as you’d find in an actual gzip file. This snippet is " "just for illustration purposes." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1410 msgid "A more elaborate multiprocessing example" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1412 msgid "" "The following working example shows how logging can be used with " "multiprocessing using configuration files. The configurations are fairly " "simple, but serve to illustrate how more complex ones could be implemented " "in a real multiprocessing scenario." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1417 msgid "" "In the example, the main process spawns a listener process and some worker " "processes. Each of the main process, the listener and the workers have three " "separate configurations (the workers all share the same configuration). We " "can see logging in the main process, how the workers log to a QueueHandler " "and how the listener implements a QueueListener and a more complex logging " "configuration, and arranges to dispatch events received via the queue to the " "handlers specified in the configuration. Note that these configurations are " "purely illustrative, but you should be able to adapt this example to your " "own scenario." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1427 msgid "" "Here's the script - the docstrings and the comments hopefully explain how it " "works::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1639 msgid "Inserting a BOM into messages sent to a SysLogHandler" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1641 msgid "" "`RFC 5424 `_ requires that a Unicode " "message be sent to a syslog daemon as a set of bytes which have the " "following structure: an optional pure-ASCII component, followed by a UTF-8 " "Byte Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the " "`relevant section of the specification `_.)" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1647 msgid "" "In Python 3.1, code was added to :class:`~logging.handlers.SysLogHandler` to " "insert a BOM into the message, but unfortunately, it was implemented " "incorrectly, with the BOM appearing at the beginning of the message and " "hence not allowing any pure-ASCII component to appear before it." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1653 msgid "" "As this behaviour is broken, the incorrect BOM insertion code is being " "removed from Python 3.2.4 and later. However, it is not being replaced, and " "if you want to produce RFC 5424-compliant messages which include a BOM, an " "optional pure-ASCII sequence before it and arbitrary Unicode after it, " "encoded using UTF-8, then you need to do the following:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1659 msgid "" "Attach a :class:`~logging.Formatter` instance to your :class:`~logging." "handlers.SysLogHandler` instance, with a format string such as::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1665 msgid "" "The Unicode code point U+FEFF, when encoded using UTF-8, will be encoded as " "a UTF-8 BOM -- the byte-string ``b'\\xef\\xbb\\xbf'``." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1668 msgid "" "Replace the ASCII section with whatever placeholders you like, but make sure " "that the data that appears in there after substitution is always ASCII (that " "way, it will remain unchanged after UTF-8 encoding)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1672 msgid "" "Replace the Unicode section with whatever placeholders you like; if the data " "which appears there after substitution contains characters outside the ASCII " "range, that's fine -- it will be encoded using UTF-8." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1676 msgid "" "The formatted message *will* be encoded using UTF-8 encoding by " "``SysLogHandler``. If you follow the above rules, you should be able to " "produce RFC 5424-compliant messages. If you don't, logging may not complain, " "but your messages will not be RFC 5424-compliant, and your syslog daemon may " "complain." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1683 msgid "Implementing structured logging" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1685 msgid "" "Although most logging messages are intended for reading by humans, and thus " "not readily machine-parseable, there might be cirumstances where you want to " "output messages in a structured format which *is* capable of being parsed by " "a program (without needing complex regular expressions to parse the log " "message). This is straightforward to achieve using the logging package. " "There are a number of ways in which this could be achieved, but the " "following is a simple approach which uses JSON to serialise the event in a " "machine-parseable manner::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1709 msgid "If the above script is run, it prints::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1713 #: ../Doc/howto/logging-cookbook.rst:1760 msgid "" "Note that the order of items might be different according to the version of " "Python used." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1716 msgid "" "If you need more specialised processing, you can use a custom JSON encoder, " "as in the following complete example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1756 msgid "When the above script is run, it prints::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1769 msgid "Customizing handlers with :func:`dictConfig`" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1771 msgid "" "There are times when you want to customize logging handlers in particular " "ways, and if you use :func:`dictConfig` you may be able to do this without " "subclassing. As an example, consider that you may want to set the ownership " "of a log file. On POSIX, this is easily done using :func:`shutil.chown`, but " "the file handlers in the stdlib don't offer built-in support. You can " "customize handler creation using a plain function such as::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1785 msgid "" "You can then specify, in a logging configuration passed to :func:" "`dictConfig`, that a logging handler be created by calling this function::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1818 msgid "" "In this example I am setting the ownership using the ``pulse`` user and " "group, just for the purposes of illustration. Putting it together into a " "working script, ``chowntest.py``::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1865 msgid "To run this, you will probably need to run as ``root``:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1875 msgid "" "Note that this example uses Python 3.3 because that's where :func:`shutil." "chown` makes an appearance. This approach should work with any Python " "version that supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. " "With pre-3.3 versions, you would need to implement the actual ownership " "change using e.g. :func:`os.chown`." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1881 msgid "" "In practice, the handler-creating function may be in a utility module " "somewhere in your project. Instead of the line in the configuration::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1886 msgid "you could use e.g.::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1890 msgid "" "where ``project.util`` can be replaced with the actual name of the package " "where the function resides. In the above working script, using ``'ext://" "__main__.owned_file_handler'`` should work. Here, the actual callable is " "resolved by :func:`dictConfig` from the ``ext://`` specification." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1895 msgid "" "This example hopefully also points the way to how you could implement other " "types of file change - e.g. setting specific POSIX permission bits - in the " "same way, using :func:`os.chmod`." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1899 msgid "" "Of course, the approach could also be extended to types of handler other " "than a :class:`~logging.FileHandler` - for example, one of the rotating file " "handlers, or a different type of handler altogether." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1909 msgid "Using particular formatting styles throughout your application" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1911 msgid "" "In Python 3.2, the :class:`~logging.Formatter` gained a ``style`` keyword " "parameter which, while defaulting to ``%`` for backward compatibility, " "allowed the specification of ``{`` or ``$`` to support the formatting " "approaches supported by :meth:`str.format` and :class:`string.Template`. " "Note that this governs the formatting of logging messages for final output " "to logs, and is completely orthogonal to how an individual logging message " "is constructed." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1918 msgid "" "Logging calls (:meth:`~Logger.debug`, :meth:`~Logger.info` etc.) only take " "positional parameters for the actual logging message itself, with keyword " "parameters used only for determining options for how to handle the logging " "call (e.g. the ``exc_info`` keyword parameter to indicate that traceback " "information should be logged, or the ``extra`` keyword parameter to indicate " "additional contextual information to be added to the log). So you cannot " "directly make logging calls using :meth:`str.format` or :class:`string." "Template` syntax, because internally the logging package uses %-formatting " "to merge the format string and the variable arguments. There would no " "changing this while preserving backward compatibility, since all logging " "calls which are out there in existing code will be using %-format strings." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1930 msgid "" "There have been suggestions to associate format styles with specific " "loggers, but that approach also runs into backward compatibility problems " "because any existing code could be using a given logger name and using %-" "formatting." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1934 msgid "" "For logging to work interoperably between any third-party libraries and your " "code, decisions about formatting need to be made at the level of the " "individual logging call. This opens up a couple of ways in which alternative " "formatting styles can be accommodated." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1941 msgid "Using LogRecord factories" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1943 msgid "" "In Python 3.2, along with the :class:`~logging.Formatter` changes mentioned " "above, the logging package gained the ability to allow users to set their " "own :class:`LogRecord` subclasses, using the :func:`setLogRecordFactory` " "function. You can use this to set your own subclass of :class:`LogRecord`, " "which does the Right Thing by overriding the :meth:`~LogRecord.getMessage` " "method. The base class implementation of this method is where the ``msg % " "args`` formatting happens, and where you can substitute your alternate " "formatting; however, you should be careful to support all formatting styles " "and allow %-formatting as the default, to ensure interoperability with other " "code. Care should also be taken to call ``str(self.msg)``, just as the base " "implementation does." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1954 msgid "" "Refer to the reference documentation on :func:`setLogRecordFactory` and :" "class:`LogRecord` for more information." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1959 msgid "Using custom message objects" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1961 msgid "" "There is another, perhaps simpler way that you can use {}- and $- formatting " "to construct your individual log messages. You may recall (from :ref:" "`arbitrary-object-messages`) that when logging you can use an arbitrary " "object as a message format string, and that the logging package will call :" "func:`str` on that object to get the actual format string. Consider the " "following two classes::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:1986 msgid "" "Either of these can be used in place of a format string, to allow {}- or $-" "formatting to be used to build the actual \"message\" part which appears in " "the formatted log output in place of “%(message)s” or “{message}” or " "“$message”. If you find it a little unwieldy to use the class names whenever " "you want to log something, you can make it more palatable if you use an " "alias such as ``M`` or ``_`` for the message (or perhaps ``__``, if you are " "using ``_`` for localization)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:1994 msgid "" "Examples of this approach are given below. Firstly, formatting with :meth:" "`str.format`::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2008 msgid "Secondly, formatting with :class:`string.Template`::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2015 msgid "" "One thing to note is that you pay no significant performance penalty with " "this approach: the actual formatting happens not when you make the logging " "call, but when (and if) the logged message is actually about to be output to " "a log by a handler. So the only slightly unusual thing which might trip you " "up is that the parentheses go around the format string and the arguments, " "not just the format string. That’s because the __ notation is just syntax " "sugar for a constructor call to one of the ``XXXMessage`` classes shown " "above." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2029 msgid "Configuring filters with :func:`dictConfig`" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2031 msgid "" "You *can* configure filters using :func:`~logging.config.dictConfig`, though " "it might not be obvious at first glance how to do it (hence this recipe). " "Since :class:`~logging.Filter` is the only filter class included in the " "standard library, and it is unlikely to cater to many requirements (it's " "only there as a base class), you will typically need to define your own :" "class:`~logging.Filter` subclass with an overridden :meth:`~logging.Filter." "filter` method. To do this, specify the ``()`` key in the configuration " "dictionary for the filter, specifying a callable which will be used to " "create the filter (a class is the most obvious, but you can provide any " "callable which returns a :class:`~logging.Filter` instance). Here is a " "complete example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2084 msgid "" "This example shows how you can pass configuration data to the callable which " "constructs the instance, in the form of keyword parameters. When run, the " "above script will print::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2090 msgid "which shows that the filter is working as configured." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2092 msgid "A couple of extra points to note:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2094 msgid "" "If you can't refer to the callable directly in the configuration (e.g. if it " "lives in a different module, and you can't import it directly where the " "configuration dictionary is), you can use the form ``ext://...`` as " "described in :ref:`logging-config-dict-externalobj`. For example, you could " "have used the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in " "the above example." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2101 msgid "" "As well as for filters, this technique can also be used to configure custom " "handlers and formatters. See :ref:`logging-config-dict-userdef` for more " "information on how logging supports using user-defined objects in its " "configuration, and see the other cookbook recipe :ref:`custom-handlers` " "above." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2110 msgid "Customized exception formatting" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2112 msgid "" "There might be times when you want to do customized exception formatting - " "for argument's sake, let's say you want exactly one line per logged event, " "even when exception information is present. You can do this with a custom " "formatter class, as shown in the following example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2153 msgid "When run, this produces a file with exactly two lines::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2158 msgid "" "While the above treatment is simplistic, it points the way to how exception " "information can be formatted to your liking. The :mod:`traceback` module may " "be helpful for more specialized needs." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2165 msgid "Speaking logging messages" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2167 msgid "" "There might be situations when it is desirable to have logging messages " "rendered in an audible rather than a visible format. This is easy to do if " "you have text- to-speech (TTS) functionality available in your system, even " "if it doesn't have a Python binding. Most TTS systems have a command line " "program you can run, and this can be invoked from a handler using :mod:" "`subprocess`. It's assumed here that TTS command line programs won't expect " "to interact with users or take a long time to complete, and that the " "frequency of logged messages will be not so high as to swamp the user with " "messages, and that it's acceptable to have the messages spoken one at a time " "rather than concurrently, The example implementation below waits for one " "message to be spoken before the next is processed, and this might cause " "other handlers to be kept waiting. Here is a short example showing the " "approach, which assumes that the ``espeak`` TTS package is available::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2209 msgid "" "When run, this script should say \"Hello\" and then \"Goodbye\" in a female " "voice." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2211 msgid "" "The above approach can, of course, be adapted to other TTS systems and even " "other systems altogether which can process messages via external programs " "run from a command line." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2219 msgid "Buffering logging messages and outputting them conditionally" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2221 msgid "" "There might be situations where you want to log messages in a temporary area " "and only output them if a certain condition occurs. For example, you may " "want to start logging debug events in a function, and if the function " "completes without errors, you don't want to clutter the log with the " "collected debug information, but if there is an error, you want all the " "debug information to be output as well as the error." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2228 msgid "" "Here is an example which shows how you could do this using a decorator for " "your functions where you want logging to behave this way. It makes use of " "the :class:`logging.handlers.MemoryHandler`, which allows buffering of " "logged events until some condition occurs, at which point the buffered " "events are ``flushed`` - passed to another handler (the ``target`` handler) " "for processing. By default, the ``MemoryHandler`` flushed when its buffer " "gets filled up or an event whose level is greater than or equal to a " "specified threshold is seen. You can use this recipe with a more specialised " "subclass of ``MemoryHandler`` if you want custom flushing behavior." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2238 msgid "" "The example script has a simple function, ``foo``, which just cycles through " "all the logging levels, writing to ``sys.stderr`` to say what level it's " "about to log at, and then actually logging a message at that level. You can " "pass a parameter to ``foo`` which, if true, will log at ERROR and CRITICAL " "levels - otherwise, it only logs at DEBUG, INFO and WARNING levels." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2244 msgid "" "The script just arranges to decorate ``foo`` with a decorator which will do " "the conditional logging that's required. The decorator takes a logger as a " "parameter and attaches a memory handler for the duration of the call to the " "decorated function. The decorator can be additionally parameterised using a " "target handler, a level at which flushing should occur, and a capacity for " "the buffer. These default to a :class:`~logging.StreamHandler` which writes " "to ``sys.stderr``, ``logging.ERROR`` and ``100`` respectively." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2252 msgid "Here's the script::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2315 msgid "When this script is run, the following output should be observed::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2343 msgid "" "As you can see, actual logging output only occurs when an event is logged " "whose severity is ERROR or greater, but in that case, any previous events at " "lower severities are also logged." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2347 msgid "You can of course use the conventional means of decoration::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2357 msgid "Formatting times using UTC (GMT) via configuration" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2359 msgid "" "Sometimes you want to format times using UTC, which can be done using a " "class such as `UTCFormatter`, shown below::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2368 msgid "" "and you can then use the ``UTCFormatter`` in your code instead of :class:" "`~logging.Formatter`. If you want to do that via configuration, you can use " "the :func:`~logging.config.dictConfig` API with an approach illustrated by " "the following complete example::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2411 msgid "When this script is run, it should print something like::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2416 msgid "" "showing how the time is formatted both as local time and UTC, one for each " "handler." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2423 msgid "Using a context manager for selective logging" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2425 msgid "" "There are times when it would be useful to temporarily change the logging " "configuration and revert it back after doing something. For this, a context " "manager is the most obvious way of saving and restoring the logging context. " "Here is a simple example of such a context manager, which allows you to " "optionally change the logging level and add a logging handler purely in the " "scope of the context manager::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2458 msgid "" "If you specify a level value, the logger's level is set to that value in the " "scope of the with block covered by the context manager. If you specify a " "handler, it is added to the logger on entry to the block and removed on exit " "from the block. You can also ask the manager to close the handler for you on " "block exit - you could do this if you don't need the handler any more." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2464 msgid "" "To illustrate how it works, we can add the following block of code to the " "above::" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2482 msgid "" "We initially set the logger's level to ``INFO``, so message #1 appears and " "message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the " "following ``with`` block, and so message #3 appears. After the block exits, " "the logger's level is restored to ``INFO`` and so message #4 doesn't appear. " "In the next ``with`` block, we set the level to ``DEBUG`` again but also add " "a handler writing to ``sys.stdout``. Thus, message #5 appears twice on the " "console (once 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)." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2492 msgid "If we run the resulting script, the result is as follows:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2503 msgid "" "If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the " "following, which is the only message written to ``stdout``:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2511 msgid "Once again, but piping ``stdout`` to ``/dev/null``, we get:" msgstr "" #: ../Doc/howto/logging-cookbook.rst:2521 msgid "" "In this case, the message #5 printed to ``stdout`` doesn't appear, as " "expected." msgstr "" #: ../Doc/howto/logging-cookbook.rst:2523 msgid "" "Of course, the approach described here can be generalised, for example to " "attach logging filters temporarily. Note that the above code works in Python " "2 as well as Python 3." msgstr "" #: ../Doc/howto/pyporting.rst:5 msgid "Porting Python 2 Code to Python 3" msgstr "" #: ../Doc/howto/pyporting.rst:7 msgid "Brett Cannon" msgstr "" #: ../Doc/howto/pyporting.rst:11 msgid "" "With Python 3 being the future of Python while Python 2 is still in active " "use, it is good to have your project available for both major releases of " "Python. This guide is meant to help you figure out how best to support both " "Python 2 & 3 simultaneously." msgstr "" #: ../Doc/howto/pyporting.rst:16 msgid "" "If you are looking to port an extension module instead of pure Python code, " "please see :ref:`cporting-howto`." msgstr "" #: ../Doc/howto/pyporting.rst:19 msgid "" "If you would like to read one core Python developer's take on why Python 3 " "came into existence, you can read Nick Coghlan's `Python 3 Q & A`_." msgstr "" #: ../Doc/howto/pyporting.rst:22 msgid "" "For help with porting, you can email the python-porting_ mailing list with " "questions." msgstr "" #: ../Doc/howto/pyporting.rst:26 msgid "The Short Explanation" msgstr "" #: ../Doc/howto/pyporting.rst:28 msgid "" "To make your project be single-source Python 2/3 compatible, the basic steps " "are:" msgstr "" #: ../Doc/howto/pyporting.rst:31 msgid "Only worry about supporting Python 2.7" msgstr "" #: ../Doc/howto/pyporting.rst:32 msgid "" "Make sure you have good test coverage (coverage.py_ can help; ``pip install " "coverage``)" msgstr "" #: ../Doc/howto/pyporting.rst:34 ../Doc/howto/pyporting.rst:114 #: ../Doc/howto/pyporting.rst:415 msgid "Learn the differences between Python 2 & 3" msgstr "" #: ../Doc/howto/pyporting.rst:35 msgid "" "Use Modernize_ or Futurize_ to update your code (``pip install modernize`` " "or ``pip install future``, respectively)" msgstr "" #: ../Doc/howto/pyporting.rst:37 msgid "" "Use Pylint_ to help make sure you don't regress on your Python 3 support " "(``pip install pylint``)" msgstr "" #: ../Doc/howto/pyporting.rst:39 msgid "" "Use caniusepython3_ to find out which of your dependencies are blocking your " "use of Python 3 (``pip install caniusepython3``)" msgstr "" #: ../Doc/howto/pyporting.rst:41 msgid "" "Once your dependencies are no longer blocking you, use continuous " "integration to make sure you stay compatible with Python 2 & 3 (tox_ can " "help test against multiple versions of Python; ``pip install tox``)" msgstr "" #: ../Doc/howto/pyporting.rst:45 msgid "" "If you are dropping support for Python 2 entirely, then after you learn the " "differences between Python 2 & 3 you can run 2to3_ over your code and skip " "the rest of the steps outlined above." msgstr "" #: ../Doc/howto/pyporting.rst:51 msgid "Details" msgstr "" #: ../Doc/howto/pyporting.rst:53 msgid "" "A key point about supporting Python 2 & 3 simultaneously is that you can " "start **today**! Even if your dependencies are not supporting Python 3 yet " "that does not mean you can't modernize your code **now** to support Python " "3. Most changes required to support Python 3 lead to cleaner code using " "newer practices even in Python 2." msgstr "" #: ../Doc/howto/pyporting.rst:59 msgid "" "Another key point is that modernizing your Python 2 code to also support " "Python 3 is largely automated for you. While you might have to make some API " "decisions thanks to Python 3 clarifying text data versus binary data, the " "lower-level work is now mostly done for you and thus can at least benefit " "from the automated changes immediately." msgstr "" #: ../Doc/howto/pyporting.rst:65 msgid "" "Keep those key points in mind while you read on about the details of porting " "your code to support Python 2 & 3 simultaneously." msgstr "" #: ../Doc/howto/pyporting.rst:70 msgid "Drop support for Python 2.6 and older" msgstr "" #: ../Doc/howto/pyporting.rst:72 msgid "" "While you can make Python 2.5 work with Python 3, it is **much** easier if " "you only have to work with Python 2.7. If dropping Python 2.5 is not an " "option then the six_ project can help you support Python 2.5 & 3 " "simultaneously (``pip install six``). Do realize, though, that nearly all " "the projects listed in this HOWTO will not be available to you." msgstr "" #: ../Doc/howto/pyporting.rst:78 msgid "" "If you are able to skip Python 2.5 and older, then the required changes to " "your code should continue to look and feel like idiomatic Python code. At " "worst you will have to use a function instead of a method in some instances " "or have to import a function instead of using a built-in one, but otherwise " "the overall transformation should not feel foreign to you." msgstr "" #: ../Doc/howto/pyporting.rst:84 msgid "" "But you should aim for only supporting Python 2.7. Python 2.6 is no longer " "supported and thus is not receiving bugfixes. This means **you** will have " "to work around any issues you come across with Python 2.6. There are also " "some tools mentioned in this HOWTO which do not support Python 2.6 (e.g., " "Pylint_), and this will become more commonplace as time goes on. It will " "simply be easier for you if you only support the versions of Python that you " "have to support." msgstr "" #: ../Doc/howto/pyporting.rst:92 msgid "" "Make sure you specify the proper version support in your ``setup.py`` file" msgstr "" #: ../Doc/howto/pyporting.rst:94 msgid "" "In your ``setup.py`` file you should have the proper `trove classifier`_ " "specifying what versions of Python you support. As your project does not " "support Python 3 yet you should at least have ``Programming Language :: " "Python :: 2 :: Only`` specified. Ideally you should also specify each major/" "minor version of Python that you do support, e.g. ``Programming Language :: " "Python :: 2.7``." msgstr "" #: ../Doc/howto/pyporting.rst:102 msgid "Have good test coverage" msgstr "" #: ../Doc/howto/pyporting.rst:104 msgid "" "Once you have your code supporting the oldest version of Python 2 you want " "it to, you will want to make sure your test suite has good coverage. A good " "rule of thumb is that if you want to be confident enough in your test suite " "that any failures that appear after having tools rewrite your code are " "actual bugs in the tools and not in your code. If you want a number to aim " "for, try to get over 80% coverage (and don't feel bad if you can't easily " "get past 90%). If you don't already have a tool to measure test coverage " "then coverage.py_ is recommended." msgstr "" #: ../Doc/howto/pyporting.rst:116 msgid "" "Once you have your code well-tested you are ready to begin porting your code " "to Python 3! But to fully understand how your code is going to change and " "what you want to look out for while you code, you will want to learn what " "changes Python 3 makes in terms of Python 2. Typically the two best ways of " "doing that is reading the `\"What's New\"`_ doc for each release of Python 3 " "and the `Porting to Python 3`_ book (which is free online). There is also a " "handy `cheat sheet`_ from the Python-Future project." msgstr "" #: ../Doc/howto/pyporting.rst:126 msgid "Update your code" msgstr "" #: ../Doc/howto/pyporting.rst:128 msgid "" "Once you feel like you know what is different in Python 3 compared to Python " "2, it's time to update your code! You have a choice between two tools in " "porting your code automatically: Modernize_ and Futurize_. Which tool you " "choose will depend on how much like Python 3 you want your code to be. " "Futurize_ does its best to make Python 3 idioms and practices exist in " "Python 2, e.g. backporting the ``bytes`` type from Python 3 so that you have " "semantic parity between the major versions of Python. Modernize_, on the " "other hand, is more conservative and targets a Python 2/3 subset of Python, " "relying on six_ to help provide compatibility." msgstr "" #: ../Doc/howto/pyporting.rst:138 msgid "" "Regardless of which tool you choose, they will update your code to run under " "Python 3 while staying compatible with the version of Python 2 you started " "with. Depending on how conservative you want to be, you may want to run the " "tool over your test suite first and visually inspect the diff to make sure " "the transformation is accurate. After you have transformed your test suite " "and verified that all the tests still pass as expected, then you can " "transform your application code knowing that any tests which fail is a " "translation failure." msgstr "" #: ../Doc/howto/pyporting.rst:146 msgid "" "Unfortunately the tools can't automate everything to make your code work " "under Python 3 and so there are a handful of things you will need to update " "manually to get full Python 3 support (which of these steps are necessary " "vary between the tools). Read the documentation for the tool you choose to " "use to see what it fixes by default and what it can do optionally to know " "what will (not) be fixed for you and what you may have to fix on your own (e." "g. using ``io.open()`` over the built-in ``open()`` function is off by " "default in Modernize). Luckily, though, there are only a couple of things to " "watch out for which can be considered large issues that may be hard to debug " "if not watched for." msgstr "" #: ../Doc/howto/pyporting.rst:157 msgid "Division" msgstr "" #: ../Doc/howto/pyporting.rst:159 msgid "" "In Python 3, ``5 / 2 == 2.5`` and not ``2``; all division between ``int`` " "values result in a ``float``. This change has actually been planned since " "Python 2.2 which was released in 2002. Since then users have been encouraged " "to add ``from __future__ import division`` to any and all files which use " "the ``/`` and ``//`` operators or to be running the interpreter with the ``-" "Q`` flag. If you have not been doing this then you will need to go through " "your code and do two things:" msgstr "" #: ../Doc/howto/pyporting.rst:167 msgid "Add ``from __future__ import division`` to your files" msgstr "" #: ../Doc/howto/pyporting.rst:168 msgid "" "Update any division operator as necessary to either use ``//`` to use floor " "division or continue using ``/`` and expect a float" msgstr "" #: ../Doc/howto/pyporting.rst:171 msgid "" "The reason that ``/`` isn't simply translated to ``//`` automatically is " "that if an object defines a ``__truediv__`` method but not ``__floordiv__`` " "then your code would begin to fail (e.g. a user-defined class that uses ``/" "`` to signify some operation but not ``//`` for the same thing or at all)." msgstr "" #: ../Doc/howto/pyporting.rst:177 msgid "Text versus binary data" msgstr "" #: ../Doc/howto/pyporting.rst:179 msgid "" "In Python 2 you could use the ``str`` type for both text and binary data. " "Unfortunately this confluence of two different concepts could lead to " "brittle code which sometimes worked for either kind of data, sometimes not. " "It also could lead to confusing APIs if people didn't explicitly state that " "something that accepted ``str`` accepted either text or binary data instead " "of one specific type. This complicated the situation especially for anyone " "supporting multiple languages as APIs wouldn't bother explicitly supporting " "``unicode`` when they claimed text data support." msgstr "" #: ../Doc/howto/pyporting.rst:188 msgid "" "To make the distinction between text and binary data clearer and more " "pronounced, Python 3 did what most languages created in the age of the " "internet have done and made text and binary data distinct types that cannot " "blindly be mixed together (Python predates widespread access to the " "internet). For any code that only deals with text or only binary data, this " "separation doesn't pose an issue. But for code that has to deal with both, " "it does mean you might have to now care about when you are using text " "compared to binary data, which is why this cannot be entirely automated." msgstr "" #: ../Doc/howto/pyporting.rst:197 msgid "" "To start, you will need to decide which APIs take text and which take binary " "(it is **highly** recommended you don't design APIs that can take both due " "to the difficulty of keeping the code working; as stated earlier it is " "difficult to do well). In Python 2 this means making sure the APIs that take " "text can work with ``unicode`` in Python 2 and those that work with binary " "data work with the ``bytes`` type from Python 3 and thus a subset of ``str`` " "in Python 2 (which the ``bytes`` type in Python 2 is an alias for). Usually " "the biggest issue is realizing which methods exist for which types in Python " "2 & 3 simultaneously (for text that's ``unicode`` in Python 2 and ``str`` in " "Python 3, for binary that's ``str``/``bytes`` in Python 2 and ``bytes`` in " "Python 3). The following table lists the **unique** methods of each data " "type across Python 2 & 3 (e.g., the ``decode()`` method is usable on the " "equivalent binary data type in either Python 2 or 3, but it can't be used by " "the text data type consistently between Python 2 and 3 because ``str`` in " "Python 3 doesn't have the method). Do note that as of Python 3.5 the " "``__mod__`` method was added to the bytes type." msgstr "" #: ../Doc/howto/pyporting.rst:214 msgid "**Text data**" msgstr "" #: ../Doc/howto/pyporting.rst:214 msgid "**Binary data**" msgstr "" #: ../Doc/howto/pyporting.rst:216 msgid "\\" msgstr "" #: ../Doc/howto/pyporting.rst:216 msgid "decode" msgstr "" #: ../Doc/howto/pyporting.rst:218 msgid "encode" msgstr "" #: ../Doc/howto/pyporting.rst:220 msgid "format" msgstr "" #: ../Doc/howto/pyporting.rst:222 msgid "isdecimal" msgstr "" #: ../Doc/howto/pyporting.rst:224 msgid "isnumeric" msgstr "" #: ../Doc/howto/pyporting.rst:227 msgid "" "Making the distinction easier to handle can be accomplished by encoding and " "decoding between binary data and text at the edge of your code. This means " "that when you receive text in binary data, you should immediately decode it. " "And if your code needs to send text as binary data then encode it as late as " "possible. This allows your code to work with only text internally and thus " "eliminates having to keep track of what type of data you are working with." msgstr "" #: ../Doc/howto/pyporting.rst:234 msgid "" "The next issue is making sure you know whether the string literals in your " "code represent text or binary data. At minimum you should add a ``b`` prefix " "to any literal that presents binary data. For text you should either use the " "``from __future__ import unicode_literals`` statement or add a ``u`` prefix " "to the text literal." msgstr "" #: ../Doc/howto/pyporting.rst:240 msgid "" "As part of this dichotomy you also need to be careful about opening files. " "Unless you have been working on Windows, there is a chance you have not " "always bothered to add the ``b`` mode when opening a binary file (e.g., " "``rb`` for binary reading). Under Python 3, binary files and text files are " "clearly distinct and mutually incompatible; see the :mod:`io` module for " "details. Therefore, you **must** make a decision of whether a file will be " "used for binary access (allowing binary data to be read and/or written) or " "text access (allowing text data to be read and/or written). You should also " "use :func:`io.open` for opening files instead of the built-in :func:`open` " "function as the :mod:`io` module is consistent from Python 2 to 3 while the " "built-in :func:`open` function is not (in Python 3 it's actually :func:`io." "open`)." msgstr "" #: ../Doc/howto/pyporting.rst:252 msgid "" "The constructors of both ``str`` and ``bytes`` have different semantics for " "the same arguments between Python 2 & 3. Passing an integer to ``bytes`` in " "Python 2 will give you the string representation of the integer: ``bytes(3) " "== '3'``. But in Python 3, an integer argument to ``bytes`` will give you a " "bytes object as long as the integer specified, filled with null bytes: " "``bytes(3) == b'\\x00\\x00\\x00'``. A similar worry is necessary when " "passing a bytes object to ``str``. In Python 2 you just get the bytes object " "back: ``str(b'3') == b'3'``. But in Python 3 you get the string " "representation of the bytes object: ``str(b'3') == \"b'3'\"``." msgstr "" #: ../Doc/howto/pyporting.rst:262 msgid "" "Finally, the indexing of binary data requires careful handling (slicing does " "**not** require any special handling). In Python 2, ``b'123'[1] == b'2'`` " "while in Python 3 ``b'123'[1] == 50``. Because binary data is simply a " "collection of binary numbers, Python 3 returns the integer value for the " "byte you index on. But in Python 2 because ``bytes == str``, indexing " "returns a one-item slice of bytes. The six_ project has a function named " "``six.indexbytes()`` which will return an integer like in Python 3: ``six." "indexbytes(b'123', 1)``." msgstr "" #: ../Doc/howto/pyporting.rst:271 msgid "To summarize:" msgstr "" #: ../Doc/howto/pyporting.rst:273 msgid "Decide which of your APIs take text and which take binary data" msgstr "" #: ../Doc/howto/pyporting.rst:274 msgid "" "Make sure that your code that works with text also works with ``unicode`` " "and code for binary data works with ``bytes`` in Python 2 (see the table " "above for what methods you cannot use for each type)" msgstr "" #: ../Doc/howto/pyporting.rst:277 msgid "" "Mark all binary literals with a ``b`` prefix, use a ``u`` prefix or :mod:" "`__future__` import statement for text literals" msgstr "" #: ../Doc/howto/pyporting.rst:279 msgid "" "Decode binary data to text as soon as possible, encode text as binary data " "as late as possible" msgstr "" #: ../Doc/howto/pyporting.rst:281 msgid "" "Open files using :func:`io.open` and make sure to specify the ``b`` mode " "when appropriate" msgstr "" #: ../Doc/howto/pyporting.rst:283 msgid "Be careful when indexing binary data" msgstr "" #: ../Doc/howto/pyporting.rst:287 msgid "Use feature detection instead of version detection" msgstr "" #: ../Doc/howto/pyporting.rst:288 msgid "" "Inevitably you will have code that has to choose what to do based on what " "version of Python is running. The best way to do this is with feature " "detection of whether the version of Python you're running under supports " "what you need. If for some reason that doesn't work then you should make the " "version check is against Python 2 and not Python 3. To help explain this, " "let's look at an example." msgstr "" #: ../Doc/howto/pyporting.rst:295 msgid "" "Let's pretend that you need access to a feature of importlib_ that is " "available in Python's standard library since Python 3.3 and available for " "Python 2 through importlib2_ on PyPI. You might be tempted to write code to " "access e.g. the ``importlib.abc`` module by doing the following::" msgstr "" #: ../Doc/howto/pyporting.rst:307 msgid "" "The problem with this code is what happens when Python 4 comes out? It would " "be better to treat Python 2 as the exceptional case instead of Python 3 and " "assume that future Python versions will be more compatible with Python 3 " "than Python 2::" msgstr "" #: ../Doc/howto/pyporting.rst:319 msgid "" "The best solution, though, is to do no version detection at all and instead " "rely on feature detection. That avoids any potential issues of getting the " "version detection wrong and helps keep you future-compatible::" msgstr "" #: ../Doc/howto/pyporting.rst:330 msgid "Prevent compatibility regressions" msgstr "" #: ../Doc/howto/pyporting.rst:332 msgid "" "Once you have fully translated your code to be compatible with Python 3, you " "will want to make sure your code doesn't regress and stop working under " "Python 3. This is especially true if you have a dependency which is blocking " "you from actually running under Python 3 at the moment." msgstr "" #: ../Doc/howto/pyporting.rst:337 msgid "" "To help with staying compatible, any new modules you create should have at " "least the following block of code at the top of it::" msgstr "" #: ../Doc/howto/pyporting.rst:345 msgid "" "You can also run Python 2 with the ``-3`` flag to be warned about various " "compatibility issues your code triggers during execution. If you turn " "warnings into errors with ``-Werror`` then you can make sure that you don't " "accidentally miss a warning." msgstr "" #: ../Doc/howto/pyporting.rst:351 msgid "" "You can also use the Pylint_ project and its ``--py3k`` flag to lint your " "code to receive warnings when your code begins to deviate from Python 3 " "compatibility. This also prevents you from having to run Modernize_ or " "Futurize_ over your code regularly to catch compatibility regressions. This " "does require you only support Python 2.7 and Python 3.4 or newer as that is " "Pylint's minimum Python version support." msgstr "" #: ../Doc/howto/pyporting.rst:360 msgid "Check which dependencies block your transition" msgstr "" #: ../Doc/howto/pyporting.rst:362 msgid "" "**After** you have made your code compatible with Python 3 you should begin " "to care about whether your dependencies have also been ported. The " "caniusepython3_ project was created to help you determine which projects -- " "directly or indirectly -- are blocking you from supporting Python 3. There " "is both a command-line tool as well as a web interface at https://" "caniusepython3.com ." msgstr "" #: ../Doc/howto/pyporting.rst:369 msgid "" "The project also provides code which you can integrate into your test suite " "so that you will have a failing test when you no longer have dependencies " "blocking you from using Python 3. This allows you to avoid having to " "manually check your dependencies and to be notified quickly when you can " "start running on Python 3." msgstr "" #: ../Doc/howto/pyporting.rst:375 msgid "Update your ``setup.py`` file to denote Python 3 compatibility" msgstr "" #: ../Doc/howto/pyporting.rst:377 msgid "" "Once your code works under Python 3, you should update the classifiers in " "your ``setup.py`` to contain ``Programming Language :: Python :: 3`` and to " "not specify sole Python 2 support. This will tell anyone using your code " "that you support Python 2 **and** 3. Ideally you will also want to add " "classifiers for each major/minor version of Python you now support." msgstr "" #: ../Doc/howto/pyporting.rst:385 msgid "Use continuous integration to stay compatible" msgstr "" #: ../Doc/howto/pyporting.rst:387 msgid "" "Once you are able to fully run under Python 3 you will want to make sure " "your code always works under both Python 2 & 3. Probably the best tool for " "running your tests under multiple Python interpreters is tox_. You can then " "integrate tox with your continuous integration system so that you never " "accidentally break Python 2 or 3 support." msgstr "" #: ../Doc/howto/pyporting.rst:393 msgid "" "You may also want to use the ``-bb`` flag with the Python 3 interpreter to " "trigger an exception when you are comparing bytes to strings or bytes to an " "int (the latter is available starting in Python 3.5). By default type-" "differing comparisons simply return ``False``, but if you made a mistake in " "your separation of text/binary data handling or indexing on bytes you " "wouldn't easily find the mistake. This flag will raise an exception when " "these kinds of comparisons occur, making the mistake much easier to track " "down." msgstr "" #: ../Doc/howto/pyporting.rst:401 msgid "" "And that's mostly it! At this point your code base is compatible with both " "Python 2 and 3 simultaneously. Your testing will also be set up so that you " "don't accidentally break Python 2 or 3 compatibility regardless of which " "version you typically run your tests under while developing." msgstr "" #: ../Doc/howto/pyporting.rst:408 msgid "Dropping Python 2 support completely" msgstr "" #: ../Doc/howto/pyporting.rst:410 msgid "" "If you are able to fully drop support for Python 2, then the steps required " "to transition to Python 3 simplify greatly." msgstr "" #: ../Doc/howto/pyporting.rst:413 msgid "Update your code to only support Python 2.7" msgstr "" #: ../Doc/howto/pyporting.rst:414 msgid "Make sure you have good test coverage (coverage.py_ can help)" msgstr "" #: ../Doc/howto/pyporting.rst:416 msgid "Use 2to3_ to rewrite your code to run only under Python 3" msgstr "" #: ../Doc/howto/pyporting.rst:418 msgid "" "After this your code will be fully Python 3 compliant but in a way that is " "not supported by Python 2. You should also update the classifiers in your " "``setup.py`` to contain ``Programming Language :: Python :: 3 :: Only``." msgstr "" #: ../Doc/howto/regex.rst:5 msgid "Regular Expression HOWTO" msgstr "" #: ../Doc/howto/regex.rst:7 msgid "A.M. Kuchling " msgstr "" #: ../Doc/howto/regex.rst:18 msgid "" "This document is an introductory tutorial to using regular expressions in " "Python with the :mod:`re` module. It provides a gentler introduction than " "the corresponding section in the Library Reference." msgstr "" #: ../Doc/howto/regex.rst:26 msgid "" "Regular expressions (called REs, or regexes, or regex patterns) are " "essentially a tiny, highly specialized programming language embedded inside " "Python and made available through the :mod:`re` module. Using this little " "language, you specify the rules for the set of possible strings that you " "want to match; this set might contain English sentences, or e-mail " "addresses, or TeX commands, or anything you like. You can then ask " "questions such as \"Does this string match the pattern?\", or \"Is there a " "match for the pattern anywhere in this string?\". You can also use REs to " "modify a string or to split it apart in various ways." msgstr "" #: ../Doc/howto/regex.rst:35 msgid "" "Regular expression patterns are compiled into a series of bytecodes which " "are then executed by a matching engine written in C. For advanced use, it " "may be necessary to pay careful attention to how the engine will execute a " "given RE, and write the RE in a certain way in order to produce bytecode " "that runs faster. Optimization isn't covered in this document, because it " "requires that you have a good understanding of the matching engine's " "internals." msgstr "" #: ../Doc/howto/regex.rst:42 msgid "" "The regular expression language is relatively small and restricted, so not " "all possible string processing tasks can be done using regular expressions. " "There are also tasks that *can* be done with regular expressions, but the " "expressions turn out to be very complicated. In these cases, you may be " "better off writing Python code to do the processing; while Python code will " "be slower than an elaborate regular expression, it will also probably be " "more understandable." msgstr "" #: ../Doc/howto/regex.rst:51 msgid "Simple Patterns" msgstr "" #: ../Doc/howto/regex.rst:53 msgid "" "We'll start by learning about the simplest possible regular expressions. " "Since regular expressions are used to operate on strings, we'll begin with " "the most common task: matching characters." msgstr "" #: ../Doc/howto/regex.rst:57 msgid "" "For a detailed explanation of the computer science underlying regular " "expressions (deterministic and non-deterministic finite automata), you can " "refer to almost any textbook on writing compilers." msgstr "" #: ../Doc/howto/regex.rst:63 msgid "Matching Characters" msgstr "" #: ../Doc/howto/regex.rst:65 msgid "" "Most letters and characters will simply match themselves. For example, the " "regular expression ``test`` will match the string ``test`` exactly. (You " "can enable a case-insensitive mode that would let this RE match ``Test`` or " "``TEST`` as well; more about this later.)" msgstr "" #: ../Doc/howto/regex.rst:70 msgid "" "There are exceptions to this rule; some characters are special :dfn:" "`metacharacters`, and don't match themselves. Instead, they signal that " "some out-of-the-ordinary thing should be matched, or they affect other " "portions of the RE by repeating them or changing their meaning. Much of " "this document is devoted to discussing various metacharacters and what they " "do." msgstr "" #: ../Doc/howto/regex.rst:76 msgid "" "Here's a complete list of the metacharacters; their meanings will be " "discussed in the rest of this HOWTO." msgstr "" #: ../Doc/howto/regex.rst:83 msgid "" "The first metacharacters we'll look at are ``[`` and ``]``. They're used for " "specifying a character class, which is a set of characters that you wish to " "match. Characters can be listed individually, or a range of characters can " "be indicated by giving two characters and separating them by a ``'-'``. For " "example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; " "this is the same as ``[a-c]``, which uses a range to express the same set of " "characters. If you wanted to match only lowercase letters, your RE would be " "``[a-z]``." msgstr "" #: ../Doc/howto/regex.rst:92 msgid "" "Metacharacters are not active inside classes. For example, ``[akm$]`` will " "match any of the characters ``'a'``, ``'k'``, ``'m'``, or ``'$'``; ``'$'`` " "is usually a metacharacter, but inside a character class it's stripped of " "its special nature." msgstr "" #: ../Doc/howto/regex.rst:97 msgid "" "You can match the characters not listed within the class by :dfn:" "`complementing` the set. This is indicated by including a ``'^'`` as the " "first character of the class; ``'^'`` outside a character class will simply " "match the ``'^'`` character. For example, ``[^5]`` will match any character " "except ``'5'``." msgstr "" #: ../Doc/howto/regex.rst:102 msgid "" "Perhaps the most important metacharacter is the backslash, ``\\``. As in " "Python string literals, the backslash can be followed by various characters " "to signal various special sequences. It's also used to escape all the " "metacharacters so you can still match them in patterns; for example, if you " "need to match a ``[`` or ``\\``, you can precede them with a backslash to " "remove their special meaning: ``\\[`` or ``\\\\``." msgstr "" #: ../Doc/howto/regex.rst:109 msgid "" "Some of the special sequences beginning with ``'\\'`` represent predefined " "sets of characters that are often useful, such as the set of digits, the set " "of letters, or the set of anything that isn't whitespace." msgstr "" #: ../Doc/howto/regex.rst:114 msgid "" "Let's take an example: ``\\w`` matches any alphanumeric character. If the " "regex pattern is expressed in bytes, this is equivalent to the class ``[a-zA-" "Z0-9_]``. If the regex pattern is a string, ``\\w`` will match all the " "characters marked as letters in the Unicode database provided by the :mod:" "`unicodedata` module. You can use the more restricted definition of ``\\w`` " "in a string pattern by supplying the :const:`re.ASCII` flag when compiling " "the regular expression." msgstr "" #: ../Doc/howto/regex.rst:122 msgid "" "The following list of special sequences isn't complete. For a complete list " "of sequences and expanded class definitions for Unicode string patterns, see " "the last part of :ref:`Regular Expression Syntax ` in the " "Standard Library reference. In general, the Unicode versions match any " "character that's in the appropriate category in the Unicode database." msgstr "" #: ../Doc/howto/regex.rst:130 msgid "``\\d``" msgstr "``\\d``" #: ../Doc/howto/regex.rst:130 msgid "Matches any decimal digit; this is equivalent to the class ``[0-9]``." msgstr "" #: ../Doc/howto/regex.rst:133 msgid "``\\D``" msgstr "``\\D``" #: ../Doc/howto/regex.rst:133 msgid "" "Matches any non-digit character; this is equivalent to the class ``[^0-9]``." msgstr "" #: ../Doc/howto/regex.rst:137 msgid "``\\s``" msgstr "``\\s``" #: ../Doc/howto/regex.rst:136 msgid "" "Matches any whitespace character; this is equivalent to the class ``[ \\t\\n" "\\r\\f\\v]``." msgstr "" #: ../Doc/howto/regex.rst:141 msgid "``\\S``" msgstr "``\\S``" #: ../Doc/howto/regex.rst:140 msgid "" "Matches any non-whitespace character; this is equivalent to the class ``[^ " "\\t\\n\\r\\f\\v]``." msgstr "" #: ../Doc/howto/regex.rst:145 msgid "``\\w``" msgstr "``\\w``" #: ../Doc/howto/regex.rst:144 msgid "" "Matches any alphanumeric character; this is equivalent to the class ``[a-zA-" "Z0-9_]``." msgstr "" #: ../Doc/howto/regex.rst:149 msgid "``\\W``" msgstr "``\\W``" #: ../Doc/howto/regex.rst:148 msgid "" "Matches any non-alphanumeric character; this is equivalent to the class " "``[^a-zA-Z0-9_]``." msgstr "" #: ../Doc/howto/regex.rst:151 msgid "" "These sequences can be included inside a character class. For example, " "``[\\s,.]`` is a character class that will match any whitespace character, " "or ``','`` or ``'.'``." msgstr "" #: ../Doc/howto/regex.rst:155 msgid "" "The final metacharacter in this section is ``.``. It matches anything " "except a newline character, and there's an alternate mode (``re.DOTALL``) " "where it will match even a newline. ``'.'`` is often used where you want to " "match \"any character\"." msgstr "" #: ../Doc/howto/regex.rst:162 msgid "Repeating Things" msgstr "" #: ../Doc/howto/regex.rst:164 msgid "" "Being able to match varying sets of characters is the first thing regular " "expressions can do that isn't already possible with the methods available on " "strings. However, if that was the only additional capability of regexes, " "they wouldn't be much of an advance. Another capability is that you can " "specify that portions of the RE must be repeated a certain number of times." msgstr "" #: ../Doc/howto/regex.rst:170 msgid "" "The first metacharacter for repeating things that we'll look at is ``*``. " "``*`` doesn't match the literal character ``*``; instead, it specifies that " "the previous character can be matched zero or more times, instead of exactly " "once." msgstr "" #: ../Doc/howto/regex.rst:174 msgid "" "For example, ``ca*t`` will match ``ct`` (0 ``a`` characters), ``cat`` (1 " "``a``), ``caaat`` (3 ``a`` characters), and so forth. The RE engine has " "various internal limitations stemming from the size of C's ``int`` type that " "will prevent it from matching over 2 billion ``a`` characters; patterns are " "usually not written to match that much data." msgstr "" #: ../Doc/howto/regex.rst:180 msgid "" "Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the " "matching engine will try to repeat it as many times as possible. If later " "portions of the pattern don't match, the matching engine will then back up " "and try again with fewer repetitions." msgstr "" #: ../Doc/howto/regex.rst:185 msgid "" "A step-by-step example will make this more obvious. Let's consider the " "expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more " "letters from the class ``[bcd]``, and finally ends with a ``'b'``. Now " "imagine matching this RE against the string ``abcbd``." msgstr "" #: ../Doc/howto/regex.rst:191 msgid "Step" msgstr "" #: ../Doc/howto/regex.rst:191 msgid "Matched" msgstr "" #: ../Doc/howto/regex.rst:191 msgid "Explanation" msgstr "" #: ../Doc/howto/regex.rst:193 msgid "1" msgstr "1" #: ../Doc/howto/regex.rst:193 msgid "``a``" msgstr "" #: ../Doc/howto/regex.rst:193 msgid "The ``a`` in the RE matches." msgstr "" #: ../Doc/howto/regex.rst:195 msgid "2" msgstr "2" #: ../Doc/howto/regex.rst:195 msgid "``abcbd``" msgstr "" #: ../Doc/howto/regex.rst:195 msgid "" "The engine matches ``[bcd]*``, going as far as it can, which is to the end " "of the string." msgstr "" #: ../Doc/howto/regex.rst:199 msgid "3" msgstr "3" #: ../Doc/howto/regex.rst:199 ../Doc/howto/regex.rst:207 msgid "*Failure*" msgstr "" #: ../Doc/howto/regex.rst:199 msgid "" "The engine tries to match ``b``, but the current position is at the end of " "the string, so it fails." msgstr "" #: ../Doc/howto/regex.rst:204 msgid "4" msgstr "4" #: ../Doc/howto/regex.rst:204 ../Doc/howto/regex.rst:215 msgid "``abcb``" msgstr "" #: ../Doc/howto/regex.rst:204 msgid "Back up, so that ``[bcd]*`` matches one less character." msgstr "" #: ../Doc/howto/regex.rst:207 msgid "5" msgstr "5" #: ../Doc/howto/regex.rst:207 msgid "" "Try ``b`` again, but the current position is at the last character, which is " "a ``'d'``." msgstr "" #: ../Doc/howto/regex.rst:211 ../Doc/howto/regex.rst:215 msgid "6" msgstr "6" #: ../Doc/howto/regex.rst:211 msgid "``abc``" msgstr "" #: ../Doc/howto/regex.rst:211 msgid "Back up again, so that ``[bcd]*`` is only matching ``bc``." msgstr "" #: ../Doc/howto/regex.rst:215 msgid "" "Try ``b`` again. This time the character at the current position is " "``'b'``, so it succeeds." msgstr "" #: ../Doc/howto/regex.rst:221 msgid "" "The end of the RE has now been reached, and it has matched ``abcb``. This " "demonstrates how the matching engine goes as far as it can at first, and if " "no match is found it will then progressively back up and retry the rest of " "the RE again and again. It will back up until it has tried zero matches for " "``[bcd]*``, and if that subsequently fails, the engine will conclude that " "the string doesn't match the RE at all." msgstr "" #: ../Doc/howto/regex.rst:228 msgid "" "Another repeating metacharacter is ``+``, which matches one or more times. " "Pay careful attention to the difference between ``*`` and ``+``; ``*`` " "matches *zero* or more times, so whatever's being repeated may not be " "present at all, while ``+`` requires at least *one* occurrence. To use a " "similar example, ``ca+t`` will match ``cat`` (1 ``a``), ``caaat`` (3 " "``a``'s), but won't match ``ct``." msgstr "" #: ../Doc/howto/regex.rst:235 msgid "" "There are two more repeating qualifiers. The question mark character, ``?" "``, matches either once or zero times; you can think of it as marking " "something as being optional. For example, ``home-?brew`` matches either " "``homebrew`` or ``home-brew``." msgstr "" #: ../Doc/howto/regex.rst:240 msgid "" "The most complicated repeated qualifier is ``{m,n}``, where *m* and *n* are " "decimal integers. This qualifier means there must be at least *m* " "repetitions, and at most *n*. For example, ``a/{1,3}b`` will match ``a/b``, " "``a//b``, and ``a///b``. It won't match ``ab``, which has no slashes, or " "``a////b``, which has four." msgstr "" #: ../Doc/howto/regex.rst:246 msgid "" "You can omit either *m* or *n*; in that case, a reasonable value is assumed " "for the missing value. Omitting *m* is interpreted as a lower limit of 0, " "while omitting *n* results in an upper bound of infinity --- actually, the " "upper bound is the 2-billion limit mentioned earlier, but that might as well " "be infinity." msgstr "" #: ../Doc/howto/regex.rst:251 msgid "" "Readers of a reductionist bent may notice that the three other qualifiers " "can all be expressed using this notation. ``{0,}`` is the same as ``*``, " "``{1,}`` is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's " "better to use ``*``, ``+``, or ``?`` when you can, simply because they're " "shorter and easier to read." msgstr "" #: ../Doc/howto/regex.rst:259 msgid "Using Regular Expressions" msgstr "" #: ../Doc/howto/regex.rst:261 msgid "" "Now that we've looked at some simple regular expressions, how do we actually " "use them in Python? The :mod:`re` module provides an interface to the " "regular expression engine, allowing you to compile REs into objects and then " "perform matches with them." msgstr "" #: ../Doc/howto/regex.rst:268 msgid "Compiling Regular Expressions" msgstr "" #: ../Doc/howto/regex.rst:270 msgid "" "Regular expressions are compiled into pattern objects, which have methods " "for various operations such as searching for pattern matches or performing " "string substitutions. ::" msgstr "" #: ../Doc/howto/regex.rst:279 msgid "" ":func:`re.compile` also accepts an optional *flags* argument, used to enable " "various special features and syntax variations. We'll go over the available " "settings later, but for now a single example will do::" msgstr "" #: ../Doc/howto/regex.rst:285 msgid "" "The RE is passed to :func:`re.compile` as a string. REs are handled as " "strings because regular expressions aren't part of the core Python language, " "and no special syntax was created for expressing them. (There are " "applications that don't need REs at all, so there's no need to bloat the " "language specification by including them.) Instead, the :mod:`re` module is " "simply a C extension module included with Python, just like the :mod:" "`socket` or :mod:`zlib` modules." msgstr "" #: ../Doc/howto/regex.rst:292 msgid "" "Putting REs in strings keeps the Python language simpler, but has one " "disadvantage which is the topic of the next section." msgstr "" #: ../Doc/howto/regex.rst:297 msgid "The Backslash Plague" msgstr "" #: ../Doc/howto/regex.rst:299 msgid "" "As stated earlier, regular expressions use the backslash character " "(``'\\'``) to indicate special forms or to allow special characters to be " "used without invoking their special meaning. This conflicts with Python's " "usage of the same character for the same purpose in string literals." msgstr "" #: ../Doc/howto/regex.rst:304 msgid "" "Let's say you want to write a RE that matches the string ``\\section``, " "which might be found in a LaTeX file. To figure out what to write in the " "program code, start with the desired string to be matched. Next, you must " "escape any backslashes and other metacharacters by preceding them with a " "backslash, resulting in the string ``\\\\section``. The resulting string " "that must be passed to :func:`re.compile` must be ``\\\\section``. However, " "to express this as a Python string literal, both backslashes must be escaped " "*again*." msgstr "" #: ../Doc/howto/regex.rst:313 msgid "Characters" msgstr "Caractères" #: ../Doc/howto/regex.rst:313 msgid "Stage" msgstr "" #: ../Doc/howto/regex.rst:315 msgid "``\\section``" msgstr "" #: ../Doc/howto/regex.rst:315 msgid "Text string to be matched" msgstr "" #: ../Doc/howto/regex.rst:317 msgid "``\\\\section``" msgstr "" #: ../Doc/howto/regex.rst:317 msgid "Escaped backslash for :func:`re.compile`" msgstr "" #: ../Doc/howto/regex.rst:319 ../Doc/howto/regex.rst:339 msgid "``\"\\\\\\\\section\"``" msgstr "" #: ../Doc/howto/regex.rst:319 msgid "Escaped backslashes for a string literal" msgstr "" #: ../Doc/howto/regex.rst:322 msgid "" "In short, to match a literal backslash, one has to write ``'\\\\\\\\'`` as " "the RE string, because the regular expression must be ``\\\\``, and each " "backslash must be expressed as ``\\\\`` inside a regular Python string " "literal. In REs that feature backslashes repeatedly, this leads to lots of " "repeated backslashes and makes the resulting strings difficult to understand." msgstr "" #: ../Doc/howto/regex.rst:328 msgid "" "The solution is to use Python's raw string notation for regular expressions; " "backslashes are not handled in any special way in a string literal prefixed " "with ``'r'``, so ``r\"\\n\"`` is a two-character string containing ``'\\'`` " "and ``'n'``, while ``\"\\n\"`` is a one-character string containing a " "newline. Regular expressions will often be written in Python code using this " "raw string notation." msgstr "" #: ../Doc/howto/regex.rst:335 msgid "Regular String" msgstr "" #: ../Doc/howto/regex.rst:335 msgid "Raw string" msgstr "" #: ../Doc/howto/regex.rst:337 msgid "``\"ab*\"``" msgstr "" #: ../Doc/howto/regex.rst:337 msgid "``r\"ab*\"``" msgstr "" #: ../Doc/howto/regex.rst:339 msgid "``r\"\\\\section\"``" msgstr "" #: ../Doc/howto/regex.rst:341 msgid "``\"\\\\w+\\\\s+\\\\1\"``" msgstr "" #: ../Doc/howto/regex.rst:341 msgid "``r\"\\w+\\s+\\1\"``" msgstr "" #: ../Doc/howto/regex.rst:346 msgid "Performing Matches" msgstr "" #: ../Doc/howto/regex.rst:348 msgid "" "Once you have an object representing a compiled regular expression, what do " "you do with it? Pattern objects have several methods and attributes. Only " "the most significant ones will be covered here; consult the :mod:`re` docs " "for a complete listing." msgstr "" #: ../Doc/howto/regex.rst:354 ../Doc/howto/regex.rst:412 #: ../Doc/howto/regex.rst:1029 msgid "Method/Attribute" msgstr "" #: ../Doc/howto/regex.rst:354 ../Doc/howto/regex.rst:412 #: ../Doc/howto/regex.rst:1029 msgid "Purpose" msgstr "" #: ../Doc/howto/regex.rst:356 msgid "``match()``" msgstr "" #: ../Doc/howto/regex.rst:356 msgid "Determine if the RE matches at the beginning of the string." msgstr "" #: ../Doc/howto/regex.rst:359 msgid "``search()``" msgstr "" #: ../Doc/howto/regex.rst:359 msgid "Scan through a string, looking for any location where this RE matches." msgstr "" #: ../Doc/howto/regex.rst:362 msgid "``findall()``" msgstr "" #: ../Doc/howto/regex.rst:362 msgid "Find all substrings where the RE matches, and returns them as a list." msgstr "" #: ../Doc/howto/regex.rst:365 msgid "``finditer()``" msgstr "" #: ../Doc/howto/regex.rst:365 msgid "" "Find all substrings where the RE matches, and returns them as an :term:" "`iterator`." msgstr "" #: ../Doc/howto/regex.rst:369 msgid "" ":meth:`~re.regex.match` and :meth:`~re.regex.search` return ``None`` if no " "match can be found. If they're successful, a :ref:`match object ` instance is returned, containing information about the match: " "where it starts and ends, the substring it matched, and more." msgstr "" #: ../Doc/howto/regex.rst:374 msgid "" "You can learn about this by interactively experimenting with the :mod:`re` " "module. If you have :mod:`tkinter` available, you may also want to look at :" "source:`Tools/demo/redemo.py`, a demonstration program included with the " "Python distribution. It allows you to enter REs and strings, and displays " "whether the RE matches or fails. :file:`redemo.py` can be quite useful when " "trying to debug a complicated RE." msgstr "" #: ../Doc/howto/regex.rst:381 msgid "" "This HOWTO uses the standard Python interpreter for its examples. First, run " "the Python interpreter, import the :mod:`re` module, and compile a RE::" msgstr "" #: ../Doc/howto/regex.rst:389 msgid "" "Now, you can try matching various strings against the RE ``[a-z]+``. An " "empty string shouldn't match at all, since ``+`` means 'one or more " "repetitions'. :meth:`match` should return ``None`` in this case, which will " "cause the interpreter to print no output. You can explicitly print the " "result of :meth:`match` to make this clear. ::" msgstr "" #: ../Doc/howto/regex.rst:399 msgid "" "Now, let's try it on a string that it should match, such as ``tempo``. In " "this case, :meth:`match` will return a :ref:`match object `, " "so you should store the result in a variable for later use. ::" msgstr "" #: ../Doc/howto/regex.rst:407 msgid "" "Now you can query the :ref:`match object ` for information " "about the matching string. :ref:`match object ` instances " "also have several methods and attributes; the most important ones are:" msgstr "" #: ../Doc/howto/regex.rst:414 msgid "``group()``" msgstr "" #: ../Doc/howto/regex.rst:414 msgid "Return the string matched by the RE" msgstr "" #: ../Doc/howto/regex.rst:416 msgid "``start()``" msgstr "" #: ../Doc/howto/regex.rst:416 msgid "Return the starting position of the match" msgstr "" #: ../Doc/howto/regex.rst:418 msgid "``end()``" msgstr "" #: ../Doc/howto/regex.rst:418 msgid "Return the ending position of the match" msgstr "" #: ../Doc/howto/regex.rst:420 msgid "``span()``" msgstr "" #: ../Doc/howto/regex.rst:420 msgid "Return a tuple containing the (start, end) positions of the match" msgstr "" #: ../Doc/howto/regex.rst:424 msgid "Trying these methods will soon clarify their meaning::" msgstr "" #: ../Doc/howto/regex.rst:433 msgid "" ":meth:`~re.match.group` returns the substring that was matched by the RE. :" "meth:`~re.match.start` and :meth:`~re.match.end` return the starting and " "ending index of the match. :meth:`~re.match.span` returns both start and end " "indexes in a single tuple. Since the :meth:`match` method only checks if " "the RE matches at the start of a string, :meth:`start` will always be zero. " "However, the :meth:`search` method of patterns scans through the string, so " "the match may not start at zero in that case. ::" msgstr "" #: ../Doc/howto/regex.rst:450 msgid "" "In actual programs, the most common style is to store the :ref:`match object " "` in a variable, and then check if it was ``None``. This " "usually looks like::" msgstr "" #: ../Doc/howto/regex.rst:461 msgid "" "Two pattern methods return all of the matches for a pattern. :meth:`~re." "regex.findall` returns a list of matching strings::" msgstr "" #: ../Doc/howto/regex.rst:468 msgid "" ":meth:`findall` has to create the entire list before it can be returned as " "the result. The :meth:`~re.regex.finditer` method returns a sequence of :" "ref:`match object ` instances as an :term:`iterator`::" msgstr "" #: ../Doc/howto/regex.rst:484 msgid "Module-Level Functions" msgstr "" #: ../Doc/howto/regex.rst:486 msgid "" "You don't have to create a pattern object and call its methods; the :mod:" "`re` module also provides top-level functions called :func:`~re.match`, :" "func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, and so forth. " "These functions take the same arguments as the corresponding pattern method " "with the RE string added as the first argument, and still return either " "``None`` or a :ref:`match object ` instance. ::" msgstr "" #: ../Doc/howto/regex.rst:498 msgid "" "Under the hood, these functions simply create a pattern object for you and " "call the appropriate method on it. They also store the compiled object in a " "cache, so future calls using the same RE won't need to parse the pattern " "again and again." msgstr "" #: ../Doc/howto/regex.rst:503 msgid "" "Should you use these module-level functions, or should you get the pattern " "and call its methods yourself? If you're accessing a regex within a loop, " "pre-compiling it will save a few function calls. Outside of loops, there's " "not much difference thanks to the internal cache." msgstr "" #: ../Doc/howto/regex.rst:511 msgid "Compilation Flags" msgstr "" #: ../Doc/howto/regex.rst:513 msgid "" "Compilation flags let you modify some aspects of how regular expressions " "work. Flags are available in the :mod:`re` module under two names, a long " "name such as :const:`IGNORECASE` and a short, one-letter form such as :const:" "`I`. (If you're familiar with Perl's pattern modifiers, the one-letter " "forms use the same letters; the short form of :const:`re.VERBOSE` is :const:" "`re.X`, for example.) Multiple flags can be specified by bitwise OR-ing " "them; ``re.I | re.M`` sets both the :const:`I` and :const:`M` flags, for " "example." msgstr "" #: ../Doc/howto/regex.rst:521 msgid "" "Here's a table of the available flags, followed by a more detailed " "explanation of each one." msgstr "" #: ../Doc/howto/regex.rst:525 msgid "Flag" msgstr "Option" #: ../Doc/howto/regex.rst:525 msgid "Meaning" msgstr "Signification" #: ../Doc/howto/regex.rst:527 msgid ":const:`ASCII`, :const:`A`" msgstr "" #: ../Doc/howto/regex.rst:527 msgid "" "Makes several escapes like ``\\w``, ``\\b``, ``\\s`` and ``\\d`` match only " "on ASCII characters with the respective property." msgstr "" #: ../Doc/howto/regex.rst:531 msgid ":const:`DOTALL`, :const:`S`" msgstr "" #: ../Doc/howto/regex.rst:531 msgid "Make ``.`` match any character, including newlines" msgstr "" #: ../Doc/howto/regex.rst:534 msgid ":const:`IGNORECASE`, :const:`I`" msgstr "" #: ../Doc/howto/regex.rst:534 msgid "Do case-insensitive matches" msgstr "" #: ../Doc/howto/regex.rst:536 msgid ":const:`LOCALE`, :const:`L`" msgstr "" #: ../Doc/howto/regex.rst:536 msgid "Do a locale-aware match" msgstr "" #: ../Doc/howto/regex.rst:538 msgid ":const:`MULTILINE`, :const:`M`" msgstr "" #: ../Doc/howto/regex.rst:538 msgid "Multi-line matching, affecting ``^`` and ``$``" msgstr "" #: ../Doc/howto/regex.rst:541 msgid ":const:`VERBOSE`, :const:`X` (for 'extended')" msgstr "" #: ../Doc/howto/regex.rst:541 msgid "" "Enable verbose REs, which can be organized more cleanly and understandably." msgstr "" #: ../Doc/howto/regex.rst:550 msgid "" "Perform case-insensitive matching; character class and literal strings will " "match letters by ignoring case. For example, ``[A-Z]`` will match lowercase " "letters, too, and ``Spam`` will match ``Spam``, ``spam``, or ``spAM``. This " "lowercasing doesn't take the current locale into account; it will if you " "also set the :const:`LOCALE` flag." msgstr "" #: ../Doc/howto/regex.rst:561 msgid "" "Make ``\\w``, ``\\W``, ``\\b``, and ``\\B``, dependent on the current locale " "instead of the Unicode database." msgstr "" #: ../Doc/howto/regex.rst:564 msgid "" "Locales are a feature of the C library intended to help in writing programs " "that take account of language differences. For example, if you're " "processing French text, you'd want to be able to write ``\\w+`` to match " "words, but ``\\w`` only matches the character class ``[A-Za-z]``; it won't " "match ``'é'`` or ``'ç'``. If your system is configured properly and a " "French locale is selected, certain C functions will tell the program that " "``'é'`` should also be considered a letter. Setting the :const:`LOCALE` flag " "when compiling a regular expression will cause the resulting compiled object " "to use these C functions for ``\\w``; this is slower, but also enables ``\\w" "+`` to match French words as you'd expect." msgstr "" #: ../Doc/howto/regex.rst:579 msgid "" "(``^`` and ``$`` haven't been explained yet; they'll be introduced in " "section :ref:`more-metacharacters`.)" msgstr "" #: ../Doc/howto/regex.rst:582 msgid "" "Usually ``^`` matches only at the beginning of the string, and ``$`` matches " "only at the end of the string and immediately before the newline (if any) at " "the end of the string. When this flag is specified, ``^`` matches at the " "beginning of the string and at the beginning of each line within the string, " "immediately following each newline. Similarly, the ``$`` metacharacter " "matches either at the end of the string and at the end of each line " "(immediately preceding each newline)." msgstr "" #: ../Doc/howto/regex.rst:595 msgid "" "Makes the ``'.'`` special character match any character at all, including a " "newline; without this flag, ``'.'`` will match anything *except* a newline." msgstr "" #: ../Doc/howto/regex.rst:603 msgid "" "Make ``\\w``, ``\\W``, ``\\b``, ``\\B``, ``\\s`` and ``\\S`` perform ASCII-" "only matching instead of full Unicode matching. This is only meaningful for " "Unicode patterns, and is ignored for byte patterns." msgstr "" #: ../Doc/howto/regex.rst:612 msgid "" "This flag allows you to write regular expressions that are more readable by " "granting you more flexibility in how you can format them. When this flag " "has been specified, whitespace within the RE string is ignored, except when " "the whitespace is in a character class or preceded by an unescaped " "backslash; this lets you organize and indent the RE more clearly. This flag " "also lets you put comments within a RE that will be ignored by the engine; " "comments are marked by a ``'#'`` that's neither in a character class or " "preceded by an unescaped backslash." msgstr "" #: ../Doc/howto/regex.rst:621 msgid "" "For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier " "it is to read? ::" msgstr "" #: ../Doc/howto/regex.rst:634 msgid "Without the verbose setting, the RE would look like this::" msgstr "" #: ../Doc/howto/regex.rst:640 msgid "" "In the above example, Python's automatic concatenation of string literals " "has been used to break up the RE into smaller pieces, but it's still more " "difficult to understand than the version using :const:`re.VERBOSE`." msgstr "" #: ../Doc/howto/regex.rst:646 msgid "More Pattern Power" msgstr "" #: ../Doc/howto/regex.rst:648 msgid "" "So far we've only covered a part of the features of regular expressions. In " "this section, we'll cover some new metacharacters, and how to use groups to " "retrieve portions of the text that was matched." msgstr "" #: ../Doc/howto/regex.rst:656 msgid "More Metacharacters" msgstr "" #: ../Doc/howto/regex.rst:658 msgid "" "There are some metacharacters that we haven't covered yet. Most of them " "will be covered in this section." msgstr "" #: ../Doc/howto/regex.rst:661 msgid "" "Some of the remaining metacharacters to be discussed are :dfn:`zero-width " "assertions`. They don't cause the engine to advance through the string; " "instead, they consume no characters at all, and simply succeed or fail. For " "example, ``\\b`` is an assertion that the current position is located at a " "word boundary; the position isn't changed by the ``\\b`` at all. This means " "that zero-width assertions should never be repeated, because if they match " "once at a given location, they can obviously be matched an infinite number " "of times." msgstr "" #: ../Doc/howto/regex.rst:677 msgid "``|``" msgstr "" #: ../Doc/howto/regex.rst:670 msgid "" "Alternation, or the \"or\" operator. If A and B are regular expressions, " "``A|B`` will match any string that matches either ``A`` or ``B``. ``|`` has " "very low precedence in order to make it work reasonably when you're " "alternating multi-character strings. ``Crow|Servo`` will match either " "``Crow`` or ``Servo``, not ``Cro``, a ``'w'`` or an ``'S'``, and ``ervo``." msgstr "" #: ../Doc/howto/regex.rst:676 msgid "" "To match a literal ``'|'``, use ``\\|``, or enclose it inside a character " "class, as in ``[|]``." msgstr "" #: ../Doc/howto/regex.rst:693 msgid "``^``" msgstr "" #: ../Doc/howto/regex.rst:680 msgid "" "Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has " "been set, this will only match at the beginning of the string. In :const:" "`MULTILINE` mode, this also matches immediately after each newline within " "the string." msgstr "" #: ../Doc/howto/regex.rst:684 msgid "" "For example, if you wish to match the word ``From`` only at the beginning of " "a line, the RE to use is ``^From``. ::" msgstr "" #: ../Doc/howto/regex.rst:707 msgid "``$``" msgstr "" #: ../Doc/howto/regex.rst:696 msgid "" "Matches at the end of a line, which is defined as either the end of the " "string, or any location followed by a newline character. ::" msgstr "" #: ../Doc/howto/regex.rst:706 msgid "" "To match a literal ``'$'``, use ``\\$`` or enclose it inside a character " "class, as in ``[$]``." msgstr "" #: ../Doc/howto/regex.rst:713 msgid "``\\A``" msgstr "``\\A``" #: ../Doc/howto/regex.rst:710 msgid "" "Matches only at the start of the string. When not in :const:`MULTILINE` " "mode, ``\\A`` and ``^`` are effectively the same. In :const:`MULTILINE` " "mode, they're different: ``\\A`` still matches only at the beginning of the " "string, but ``^`` may match at any location inside the string that follows a " "newline character." msgstr "" #: ../Doc/howto/regex.rst:716 msgid "``\\Z``" msgstr "``\\Z``" #: ../Doc/howto/regex.rst:716 msgid "Matches only at the end of the string." msgstr "" #: ../Doc/howto/regex.rst:751 msgid "``\\b``" msgstr "``\\b``" #: ../Doc/howto/regex.rst:719 msgid "" "Word boundary. This is a zero-width assertion that matches only at the " "beginning or end of a word. A word is defined as a sequence of alphanumeric " "characters, so the end of a word is indicated by whitespace or a non-" "alphanumeric character." msgstr "" #: ../Doc/howto/regex.rst:724 msgid "" "The following example matches ``class`` only when it's a complete word; it " "won't match when it's contained inside another word. ::" msgstr "" #: ../Doc/howto/regex.rst:735 msgid "" "There are two subtleties you should remember when using this special " "sequence. First, this is the worst collision between Python's string " "literals and regular expression sequences. In Python's string literals, ``" "\\b`` is the backspace character, ASCII value 8. If you're not using raw " "strings, then Python will convert the ``\\b`` to a backspace, and your RE " "won't match as you expect it to. The following example looks the same as our " "previous RE, but omits the ``'r'`` in front of the RE string. ::" msgstr "" #: ../Doc/howto/regex.rst:749 msgid "" "Second, inside a character class, where there's no use for this assertion, ``" "\\b`` represents the backspace character, for compatibility with Python's " "string literals." msgstr "" #: ../Doc/howto/regex.rst:756 msgid "``\\B``" msgstr "``\\B``" #: ../Doc/howto/regex.rst:754 msgid "" "Another zero-width assertion, this is the opposite of ``\\b``, only matching " "when the current position is not at a word boundary." msgstr "" #: ../Doc/howto/regex.rst:759 msgid "Grouping" msgstr "" #: ../Doc/howto/regex.rst:761 msgid "" "Frequently you need to obtain more information than just whether the RE " "matched or not. Regular expressions are often used to dissect strings by " "writing a RE divided into several subgroups which match different components " "of interest. For example, an RFC-822 header line is divided into a header " "name and a value, separated by a ``':'``, like this::" msgstr "" #: ../Doc/howto/regex.rst:772 msgid "" "This can be handled by writing a regular expression which matches an entire " "header line, and has one group which matches the header name, and another " "group which matches the header's value." msgstr "" #: ../Doc/howto/regex.rst:776 msgid "" "Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and " "``')'`` have much the same meaning as they do in mathematical expressions; " "they group together the expressions contained inside them, and you can " "repeat the contents of a group with a repeating qualifier, such as ``*``, ``" "+``, ``?``, or ``{m,n}``. For example, ``(ab)*`` will match zero or more " "repetitions of ``ab``. ::" msgstr "" #: ../Doc/howto/regex.rst:787 msgid "" "Groups indicated with ``'('``, ``')'`` also capture the starting and ending " "index of the text that they match; this can be retrieved by passing an " "argument to :meth:`group`, :meth:`start`, :meth:`end`, and :meth:`span`. " "Groups are numbered starting with 0. Group 0 is always present; it's the " "whole RE, so :ref:`match object ` methods all have group 0 as " "their default argument. Later we'll see how to express groups that don't " "capture the span of text that they match. ::" msgstr "" #: ../Doc/howto/regex.rst:802 msgid "" "Subgroups are numbered from left to right, from 1 upward. Groups can be " "nested; to determine the number, just count the opening parenthesis " "characters, going from left to right. ::" msgstr "" #: ../Doc/howto/regex.rst:815 msgid "" ":meth:`group` can be passed multiple group numbers at a time, in which case " "it will return a tuple containing the corresponding values for those " "groups. ::" msgstr "" #: ../Doc/howto/regex.rst:821 msgid "" "The :meth:`groups` method returns a tuple containing the strings for all the " "subgroups, from 1 up to however many there are. ::" msgstr "" #: ../Doc/howto/regex.rst:827 msgid "" "Backreferences in a pattern allow you to specify that the contents of an " "earlier capturing group must also be found at the current location in the " "string. For example, ``\\1`` will succeed if the exact contents of group 1 " "can be found at the current position, and fails otherwise. Remember that " "Python's string literals also use a backslash followed by numbers to allow " "including arbitrary characters in a string, so be sure to use a raw string " "when incorporating backreferences in a RE." msgstr "" #: ../Doc/howto/regex.rst:835 msgid "For example, the following RE detects doubled words in a string. ::" msgstr "" #: ../Doc/howto/regex.rst:841 msgid "" "Backreferences like this aren't often useful for just searching through a " "string --- there are few text formats which repeat data in this way --- but " "you'll soon find out that they're *very* useful when performing string " "substitutions." msgstr "" #: ../Doc/howto/regex.rst:847 msgid "Non-capturing and Named Groups" msgstr "" #: ../Doc/howto/regex.rst:849 msgid "" "Elaborate REs may use many groups, both to capture substrings of interest, " "and to group and structure the RE itself. In complex REs, it becomes " "difficult to keep track of the group numbers. There are two features which " "help with this problem. Both of them use a common syntax for regular " "expression extensions, so we'll look at that first." msgstr "" #: ../Doc/howto/regex.rst:855 msgid "" "Perl 5 is well known for its powerful additions to standard regular " "expressions. For these new features the Perl developers couldn't choose new " "single-keystroke metacharacters or new special sequences beginning with ``" "\\`` without making Perl's regular expressions confusingly different from " "standard REs. If they chose ``&`` as a new metacharacter, for example, old " "expressions would be assuming that ``&`` was a regular character and " "wouldn't have escaped it by writing ``\\&`` or ``[&]``." msgstr "" #: ../Doc/howto/regex.rst:862 msgid "" "The solution chosen by the Perl developers was to use ``(?...)`` as the " "extension syntax. ``?`` immediately after a parenthesis was a syntax error " "because the ``?`` would have nothing to repeat, so this didn't introduce any " "compatibility problems. The characters immediately after the ``?`` " "indicate what extension is being used, so ``(?=foo)`` is one thing (a " "positive lookahead assertion) and ``(?:foo)`` is something else (a non-" "capturing group containing the subexpression ``foo``)." msgstr "" #: ../Doc/howto/regex.rst:870 msgid "" "Python supports several of Perl's extensions and adds an extension syntax to " "Perl's extension syntax. If the first character after the question mark is " "a ``P``, you know that it's an extension that's specific to Python." msgstr "" #: ../Doc/howto/regex.rst:875 msgid "" "Now that we've looked at the general extension syntax, we can return to the " "features that simplify working with groups in complex REs." msgstr "" #: ../Doc/howto/regex.rst:878 msgid "" "Sometimes you'll want to use a group to denote a part of a regular " "expression, but aren't interested in retrieving the group's contents. You " "can make this fact explicit by using a non-capturing group: ``(?:...)``, " "where you can replace the ``...`` with any other regular expression. ::" msgstr "" #: ../Doc/howto/regex.rst:890 msgid "" "Except for the fact that you can't retrieve the contents of what the group " "matched, a non-capturing group behaves exactly the same as a capturing " "group; you can put anything inside it, repeat it with a repetition " "metacharacter such as ``*``, and nest it within other groups (capturing or " "non-capturing). ``(?:...)`` is particularly useful when modifying an " "existing pattern, since you can add new groups without changing how all the " "other groups are numbered. It should be mentioned that there's no " "performance difference in searching between capturing and non-capturing " "groups; neither form is any faster than the other." msgstr "" #: ../Doc/howto/regex.rst:899 msgid "" "A more significant feature is named groups: instead of referring to them by " "numbers, groups can be referenced by a name." msgstr "" #: ../Doc/howto/regex.rst:902 msgid "" "The syntax for a named group is one of the Python-specific extensions: ``(?" "P...)``. *name* is, obviously, the name of the group. Named groups " "behave exactly like capturing groups, and additionally associate a name with " "a group. The :ref:`match object ` methods that deal with " "capturing groups all accept either integers that refer to the group by " "number or strings that contain the desired group's name. Named groups are " "still given numbers, so you can retrieve information about a group in two " "ways::" msgstr "" #: ../Doc/howto/regex.rst:917 msgid "" "Named groups are handy because they let you use easily-remembered names, " "instead of having to remember numbers. Here's an example RE from the :mod:" "`imaplib` module::" msgstr "" #: ../Doc/howto/regex.rst:928 msgid "" "It's obviously much easier to retrieve ``m.group('zonem')``, instead of " "having to remember to retrieve group 9." msgstr "" #: ../Doc/howto/regex.rst:931 msgid "" "The syntax for backreferences in an expression such as ``(...)\\1`` refers " "to the number of the group. There's naturally a variant that uses the group " "name instead of the number. This is another Python extension: ``(?P=name)`` " "indicates that the contents of the group called *name* should again be " "matched at the current point. The regular expression for finding doubled " "words, ``(\\b\\w+)\\s+\\1`` can also be written as ``(?P\\b\\w+)\\s+(?" "P=word)``::" msgstr "" #: ../Doc/howto/regex.rst:944 msgid "Lookahead Assertions" msgstr "" #: ../Doc/howto/regex.rst:946 msgid "" "Another zero-width assertion is the lookahead assertion. Lookahead " "assertions are available in both positive and negative form, and look like " "this:" msgstr "" #: ../Doc/howto/regex.rst:954 msgid "``(?=...)``" msgstr "``(?=...)``" #: ../Doc/howto/regex.rst:950 msgid "" "Positive lookahead assertion. This succeeds if the contained regular " "expression, represented here by ``...``, successfully matches at the current " "location, and fails otherwise. But, once the contained expression has been " "tried, the matching engine doesn't advance at all; the rest of the pattern " "is tried right where the assertion started." msgstr "" #: ../Doc/howto/regex.rst:959 msgid "``(?!...)``" msgstr "``(?!...)``" #: ../Doc/howto/regex.rst:957 msgid "" "Negative lookahead assertion. This is the opposite of the positive " "assertion; it succeeds if the contained expression *doesn't* match at the " "current position in the string." msgstr "" #: ../Doc/howto/regex.rst:961 msgid "" "To make this concrete, let's look at a case where a lookahead is useful. " "Consider a simple pattern to match a filename and split it apart into a base " "name and an extension, separated by a ``.``. For example, in ``news.rc``, " "``news`` is the base name, and ``rc`` is the filename's extension." msgstr "" #: ../Doc/howto/regex.rst:966 msgid "The pattern to match this is quite simple:" msgstr "" #: ../Doc/howto/regex.rst:968 msgid "``.*[.].*$``" msgstr "" #: ../Doc/howto/regex.rst:970 msgid "" "Notice that the ``.`` needs to be treated specially because it's a " "metacharacter, so it's inside a character class to only match that specific " "character. Also notice the trailing ``$``; this is added to ensure that all " "the rest of the string must be included in the extension. This regular " "expression matches ``foo.bar`` and ``autoexec.bat`` and ``sendmail.cf`` and " "``printers.conf``." msgstr "" #: ../Doc/howto/regex.rst:977 msgid "" "Now, consider complicating the problem a bit; what if you want to match " "filenames where the extension is not ``bat``? Some incorrect attempts:" msgstr "" #: ../Doc/howto/regex.rst:980 msgid "" "``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by " "requiring that the first character of the extension is not a ``b``. This is " "wrong, because the pattern also doesn't match ``foo.bar``." msgstr "" #: ../Doc/howto/regex.rst:984 msgid "``.*[.]([^b]..|.[^a].|..[^t])$``" msgstr "" #: ../Doc/howto/regex.rst:986 msgid "" "The expression gets messier when you try to patch up the first solution by " "requiring one of the following cases to match: the first character of the " "extension isn't ``b``; the second character isn't ``a``; or the third " "character isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec." "bat``, but it requires a three-letter extension and won't accept a filename " "with a two-letter extension such as ``sendmail.cf``. We'll complicate the " "pattern again in an effort to fix it." msgstr "" #: ../Doc/howto/regex.rst:994 msgid "``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``" msgstr "" #: ../Doc/howto/regex.rst:996 msgid "" "In the third attempt, the second and third letters are all made optional in " "order to allow matching extensions shorter than three characters, such as " "``sendmail.cf``." msgstr "" #: ../Doc/howto/regex.rst:1000 msgid "" "The pattern's getting really complicated now, which makes it hard to read " "and understand. Worse, if the problem changes and you want to exclude both " "``bat`` and ``exe`` as extensions, the pattern would get even more " "complicated and confusing." msgstr "" #: ../Doc/howto/regex.rst:1005 msgid "A negative lookahead cuts through all this confusion:" msgstr "" #: ../Doc/howto/regex.rst:1007 msgid "" "``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression " "``bat`` doesn't match at this point, try the rest of the pattern; if ``bat" "$`` does match, the whole pattern will fail. The trailing ``$`` is required " "to ensure that something like ``sample.batch``, where the extension only " "starts with ``bat``, will be allowed. The ``[^.]*`` makes sure that the " "pattern works when there are multiple dots in the filename." msgstr "" #: ../Doc/howto/regex.rst:1014 msgid "" "Excluding another filename extension is now easy; simply add it as an " "alternative inside the assertion. The following pattern excludes filenames " "that end in either ``bat`` or ``exe``:" msgstr "" #: ../Doc/howto/regex.rst:1018 msgid "``.*[.](?!bat$|exe$)[^.]*$``" msgstr "" #: ../Doc/howto/regex.rst:1022 msgid "Modifying Strings" msgstr "" #: ../Doc/howto/regex.rst:1024 msgid "" "Up to this point, we've simply performed searches against a static string. " "Regular expressions are also commonly used to modify strings in various " "ways, using the following pattern methods:" msgstr "" #: ../Doc/howto/regex.rst:1031 msgid "``split()``" msgstr "" #: ../Doc/howto/regex.rst:1031 msgid "Split the string into a list, splitting it wherever the RE matches" msgstr "" #: ../Doc/howto/regex.rst:1034 msgid "``sub()``" msgstr "" #: ../Doc/howto/regex.rst:1034 msgid "" "Find all substrings where the RE matches, and replace them with a different " "string" msgstr "" #: ../Doc/howto/regex.rst:1037 msgid "``subn()``" msgstr "" #: ../Doc/howto/regex.rst:1037 msgid "" "Does the same thing as :meth:`sub`, but returns the new string and the " "number of replacements" msgstr "" #: ../Doc/howto/regex.rst:1044 msgid "Splitting Strings" msgstr "" #: ../Doc/howto/regex.rst:1046 msgid "" "The :meth:`split` method of a pattern splits a string apart wherever the RE " "matches, returning a list of the pieces. It's similar to the :meth:`split` " "method of strings but provides much more generality in the delimiters that " "you can split by; string :meth:`split` only supports splitting by whitespace " "or by a fixed string. As you'd expect, there's a module-level :func:`re." "split` function, too." msgstr "" #: ../Doc/howto/regex.rst:1057 msgid "" "Split *string* by the matches of the regular expression. If capturing " "parentheses are used in the RE, then their contents will also be returned as " "part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* " "splits are performed." msgstr "" #: ../Doc/howto/regex.rst:1062 msgid "" "You can limit the number of splits made, by passing a value for *maxsplit*. " "When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the " "remainder of the string is returned as the final element of the list. In " "the following example, the delimiter is any sequence of non-alphanumeric " "characters. ::" msgstr "" #: ../Doc/howto/regex.rst:1074 msgid "" "Sometimes you're not only interested in what the text between delimiters is, " "but also need to know what the delimiter was. If capturing parentheses are " "used in the RE, then their values are also returned as part of the list. " "Compare the following calls::" msgstr "" #: ../Doc/howto/regex.rst:1086 msgid "" "The module-level function :func:`re.split` adds the RE to be used as the " "first argument, but is otherwise the same. ::" msgstr "" #: ../Doc/howto/regex.rst:1098 msgid "Search and Replace" msgstr "" #: ../Doc/howto/regex.rst:1100 msgid "" "Another common task is to find all the matches for a pattern, and replace " "them with a different string. The :meth:`sub` method takes a replacement " "value, which can be either a string or a function, and the string to be " "processed." msgstr "" #: ../Doc/howto/regex.rst:1107 msgid "" "Returns the string obtained by replacing the leftmost non-overlapping " "occurrences of the RE in *string* by the replacement *replacement*. If the " "pattern isn't found, *string* is returned unchanged." msgstr "" #: ../Doc/howto/regex.rst:1111 msgid "" "The optional argument *count* is the maximum number of pattern occurrences " "to be replaced; *count* must be a non-negative integer. The default value " "of 0 means to replace all occurrences." msgstr "" #: ../Doc/howto/regex.rst:1115 msgid "" "Here's a simple example of using the :meth:`sub` method. It replaces colour " "names with the word ``colour``::" msgstr "" #: ../Doc/howto/regex.rst:1124 msgid "" "The :meth:`subn` method does the same work, but returns a 2-tuple containing " "the new string value and the number of replacements that were performed::" msgstr "" #: ../Doc/howto/regex.rst:1133 msgid "" "Empty matches are replaced only when they're not adjacent to a previous " "match. ::" msgstr "" #: ../Doc/howto/regex.rst:1140 msgid "" "If *replacement* is a string, any backslash escapes in it are processed. " "That is, ``\\n`` is converted to a single newline character, ``\\r`` is " "converted to a carriage return, and so forth. Unknown escapes such as ``" "\\&`` are left alone. Backreferences, such as ``\\6``, are replaced with the " "substring matched by the corresponding group in the RE. This lets you " "incorporate portions of the original text in the resulting replacement " "string." msgstr "" #: ../Doc/howto/regex.rst:1147 msgid "" "This example matches the word ``section`` followed by a string enclosed in " "``{``, ``}``, and changes ``section`` to ``subsection``::" msgstr "" #: ../Doc/howto/regex.rst:1154 msgid "" "There's also a syntax for referring to named groups as defined by the ``(?" "P...)`` syntax. ``\\g`` will use the substring matched by the " "group named ``name``, and ``\\g`` uses the corresponding group " "number. ``\\g<2>`` is therefore equivalent to ``\\2``, but isn't ambiguous " "in a replacement string such as ``\\g<2>0``. (``\\20`` would be interpreted " "as a reference to group 20, not a reference to group 2 followed by the " "literal character ``'0'``.) The following substitutions are all equivalent, " "but use all three variations of the replacement string. ::" msgstr "" #: ../Doc/howto/regex.rst:1171 msgid "" "*replacement* can also be a function, which gives you even more control. If " "*replacement* is a function, the function is called for every non-" "overlapping occurrence of *pattern*. On each call, the function is passed " "a :ref:`match object ` argument for the match and can use " "this information to compute the desired replacement string and return it." msgstr "" #: ../Doc/howto/regex.rst:1177 msgid "" "In the following example, the replacement function translates decimals into " "hexadecimal::" msgstr "" #: ../Doc/howto/regex.rst:1189 msgid "" "When using the module-level :func:`re.sub` function, the pattern is passed " "as the first argument. The pattern may be provided as an object or as a " "string; if you need to specify regular expression flags, you must either use " "a pattern object as the first parameter, or use embedded modifiers in the " "pattern string, e.g. ``sub(\"(?i)b+\", \"x\", \"bbbb BBBB\")`` returns ``'x " "x'``." msgstr "" #: ../Doc/howto/regex.rst:1197 msgid "Common Problems" msgstr "" #: ../Doc/howto/regex.rst:1199 msgid "" "Regular expressions are a powerful tool for some applications, but in some " "ways their behaviour isn't intuitive and at times they don't behave the way " "you may expect them to. This section will point out some of the most common " "pitfalls." msgstr "" #: ../Doc/howto/regex.rst:1205 msgid "Use String Methods" msgstr "" #: ../Doc/howto/regex.rst:1207 msgid "" "Sometimes using the :mod:`re` module is a mistake. If you're matching a " "fixed string, or a single character class, and you're not using any :mod:" "`re` features such as the :const:`IGNORECASE` flag, then the full power of " "regular expressions may not be required. Strings have several methods for " "performing operations with fixed strings and they're usually much faster, " "because the implementation is a single small C loop that's been optimized " "for the purpose, instead of the large, more generalized regular expression " "engine." msgstr "" #: ../Doc/howto/regex.rst:1215 msgid "" "One example might be replacing a single fixed string with another one; for " "example, you might replace ``word`` with ``deed``. ``re.sub()`` seems like " "the function to use for this, but consider the :meth:`replace` method. Note " "that :func:`replace` will also replace ``word`` inside words, turning " "``swordfish`` into ``sdeedfish``, but the naive RE ``word`` would have done " "that, too. (To avoid performing the substitution on parts of words, the " "pattern would have to be ``\\bword\\b``, in order to require that ``word`` " "have a word boundary on either side. This takes the job beyond :meth:" "`replace`'s abilities.)" msgstr "" #: ../Doc/howto/regex.rst:1224 msgid "" "Another common task is deleting every occurrence of a single character from " "a string or replacing it with another single character. You might do this " "with something like ``re.sub('\\n', ' ', S)``, but :meth:`translate` is " "capable of doing both tasks and will be faster than any regular expression " "operation can be." msgstr "" #: ../Doc/howto/regex.rst:1230 msgid "" "In short, before turning to the :mod:`re` module, consider whether your " "problem can be solved with a faster and simpler string method." msgstr "" #: ../Doc/howto/regex.rst:1235 msgid "match() versus search()" msgstr "" #: ../Doc/howto/regex.rst:1237 msgid "" "The :func:`match` function only checks if the RE matches at the beginning of " "the string while :func:`search` will scan forward through the string for a " "match. It's important to keep this distinction in mind. Remember, :func:" "`match` will only report a successful match which will start at 0; if the " "match wouldn't start at zero, :func:`match` will *not* report it. ::" msgstr "" #: ../Doc/howto/regex.rst:1248 msgid "" "On the other hand, :func:`search` will scan forward through the string, " "reporting the first match it finds. ::" msgstr "" #: ../Doc/howto/regex.rst:1256 msgid "" "Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``." "*`` to the front of your RE. Resist this temptation and use :func:`re." "search` instead. The regular expression compiler does some analysis of REs " "in order to speed up the process of looking for a match. One such analysis " "figures out what the first character of a match must be; for example, a " "pattern starting with ``Crow`` must match starting with a ``'C'``. The " "analysis lets the engine quickly scan through the string looking for the " "starting character, only trying the full match if a ``'C'`` is found." msgstr "" #: ../Doc/howto/regex.rst:1265 msgid "" "Adding ``.*`` defeats this optimization, requiring scanning to the end of " "the string and then backtracking to find a match for the rest of the RE. " "Use :func:`re.search` instead." msgstr "" #: ../Doc/howto/regex.rst:1271 msgid "Greedy versus Non-Greedy" msgstr "" #: ../Doc/howto/regex.rst:1273 msgid "" "When repeating a regular expression, as in ``a*``, the resulting action is " "to consume as much of the pattern as possible. This fact often bites you " "when you're trying to match a pair of balanced delimiters, such as the angle " "brackets surrounding an HTML tag. The naive pattern for matching a single " "HTML tag doesn't work because of the greedy nature of ``.*``. ::" msgstr "" #: ../Doc/howto/regex.rst:1287 msgid "" "The RE matches the ``'<'`` in ````, and the ``.*`` consumes the rest " "of the string. There's still more left in the RE, though, and the ``>`` " "can't match at the end of the string, so the regular expression engine has " "to backtrack character by character until it finds a match for the ``>``. " "The final match extends from the ``'<'`` in ```` to the ``'>'`` in ````, which isn't what you want." msgstr "" #: ../Doc/howto/regex.rst:1294 msgid "" "In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?" "``, ``??``, or ``{m,n}?``, which match as *little* text as possible. In the " "above example, the ``'>'`` is tried immediately after the first ``'<'`` " "matches, and when it fails, the engine advances a character at a time, " "retrying the ``'>'`` at every step. This produces just the right result::" msgstr "" #: ../Doc/howto/regex.rst:1303 msgid "" "(Note that parsing HTML or XML with regular expressions is painful. Quick-" "and-dirty patterns will handle common cases, but HTML and XML have special " "cases that will break the obvious regular expression; by the time you've " "written a regular expression that handles all of the possible cases, the " "patterns will be *very* complicated. Use an HTML or XML parser module for " "such tasks.)" msgstr "" #: ../Doc/howto/regex.rst:1311 msgid "Using re.VERBOSE" msgstr "" #: ../Doc/howto/regex.rst:1313 msgid "" "By now you've probably noticed that regular expressions are a very compact " "notation, but they're not terribly readable. REs of moderate complexity can " "become lengthy collections of backslashes, parentheses, and metacharacters, " "making them difficult to read and understand." msgstr "" #: ../Doc/howto/regex.rst:1318 msgid "" "For such REs, specifying the ``re.VERBOSE`` flag when compiling the regular " "expression can be helpful, because it allows you to format the regular " "expression more clearly." msgstr "" #: ../Doc/howto/regex.rst:1322 msgid "" "The ``re.VERBOSE`` flag has several effects. Whitespace in the regular " "expression that *isn't* inside a character class is ignored. This means " "that an expression such as ``dog | cat`` is equivalent to the less readable " "``dog|cat``, but ``[a b]`` will still match the characters ``'a'``, ``'b'``, " "or a space. In addition, you can also put comments inside a RE; comments " "extend from a ``#`` character to the next newline. When used with triple-" "quoted strings, this enables REs to be formatted more neatly::" msgstr "" #: ../Doc/howto/regex.rst:1339 msgid "This is far more readable than::" msgstr "" #: ../Doc/howto/regex.rst:1345 msgid "Feedback" msgstr "" #: ../Doc/howto/regex.rst:1347 msgid "" "Regular expressions are a complicated topic. Did this document help you " "understand them? Were there parts that were unclear, or Problems you " "encountered that weren't covered here? If so, please send suggestions for " "improvements to the author." msgstr "" #: ../Doc/howto/regex.rst:1352 msgid "" "The most complete book on regular expressions is almost certainly Jeffrey " "Friedl's Mastering Regular Expressions, published by O'Reilly. " "Unfortunately, it exclusively concentrates on Perl and Java's flavours of " "regular expressions, and doesn't contain any Python material at all, so it " "won't be useful as a reference for programming in Python. (The first " "edition covered Python's now-removed :mod:`regex` module, which won't help " "you much.) Consider checking it out from your library." msgstr "" #: ../Doc/howto/sockets.rst:5 msgid "Socket Programming HOWTO" msgstr "" #: ../Doc/howto/sockets.rst:7 msgid "Gordon McMillan" msgstr "" #: ../Doc/howto/sockets.rst:12 msgid "" "Sockets are used nearly everywhere, but are one of the most severely " "misunderstood technologies around. This is a 10,000 foot overview of " "sockets. It's not really a tutorial - you'll still have work to do in " "getting things operational. It doesn't cover the fine points (and there are " "a lot of them), but I hope it will give you enough background to begin using " "them decently." msgstr "" #: ../Doc/howto/sockets.rst:20 msgid "Sockets" msgstr "Interfaces de connexion (*sockets*)" #: ../Doc/howto/sockets.rst:22 msgid "" "I'm only going to talk about INET (i.e. IPv4) sockets, but they account for " "at least 99% of the sockets in use. And I'll only talk about STREAM (i.e. " "TCP) sockets - unless you really know what you're doing (in which case this " "HOWTO isn't for you!), you'll get better behavior and performance from a " "STREAM socket than anything else. I will try to clear up the mystery of what " "a socket is, as well as some hints on how to work with blocking and non-" "blocking sockets. But I'll start by talking about blocking sockets. You'll " "need to know how they work before dealing with non-blocking sockets." msgstr "" #: ../Doc/howto/sockets.rst:31 msgid "" "Part of the trouble with understanding these things is that \"socket\" can " "mean a number of subtly different things, depending on context. So first, " "let's make a distinction between a \"client\" socket - an endpoint of a " "conversation, and a \"server\" socket, which is more like a switchboard " "operator. The client application (your browser, for example) uses \"client\" " "sockets exclusively; the web server it's talking to uses both \"server\" " "sockets and \"client\" sockets." msgstr "" #: ../Doc/howto/sockets.rst:40 msgid "History" msgstr "" #: ../Doc/howto/sockets.rst:42 msgid "" "Of the various forms of :abbr:`IPC (Inter Process Communication)`, sockets " "are by far the most popular. On any given platform, there are likely to be " "other forms of IPC that are faster, but for cross-platform communication, " "sockets are about the only game in town." msgstr "" #: ../Doc/howto/sockets.rst:47 msgid "" "They were invented in Berkeley as part of the BSD flavor of Unix. They " "spread like wildfire with the Internet. With good reason --- the combination " "of sockets with INET makes talking to arbitrary machines around the world " "unbelievably easy (at least compared to other schemes)." msgstr "" #: ../Doc/howto/sockets.rst:54 msgid "Creating a Socket" msgstr "" #: ../Doc/howto/sockets.rst:56 msgid "" "Roughly speaking, when you clicked on the link that brought you to this " "page, your browser did something like the following::" msgstr "" #: ../Doc/howto/sockets.rst:64 msgid "" "When the ``connect`` completes, the socket ``s`` can be used to send in a " "request for the text of the page. The same socket will read the reply, and " "then be destroyed. That's right, destroyed. Client sockets are normally only " "used for one exchange (or a small set of sequential exchanges)." msgstr "" #: ../Doc/howto/sockets.rst:70 msgid "" "What happens in the web server is a bit more complex. First, the web server " "creates a \"server socket\"::" msgstr "" #: ../Doc/howto/sockets.rst:80 msgid "" "A couple things to notice: we used ``socket.gethostname()`` so that the " "socket would be visible to the outside world. If we had used ``s." "bind(('localhost', 80))`` or ``s.bind(('127.0.0.1', 80))`` we would still " "have a \"server\" socket, but one that was only visible within the same " "machine. ``s.bind(('', 80))`` specifies that the socket is reachable by any " "address the machine happens to have." msgstr "" #: ../Doc/howto/sockets.rst:87 msgid "" "A second thing to note: low number ports are usually reserved for \"well " "known\" services (HTTP, SNMP etc). If you're playing around, use a nice high " "number (4 digits)." msgstr "" #: ../Doc/howto/sockets.rst:91 msgid "" "Finally, the argument to ``listen`` tells the socket library that we want it " "to queue up as many as 5 connect requests (the normal max) before refusing " "outside connections. If the rest of the code is written properly, that " "should be plenty." msgstr "" #: ../Doc/howto/sockets.rst:95 msgid "" "Now that we have a \"server\" socket, listening on port 80, we can enter the " "mainloop of the web server::" msgstr "" #: ../Doc/howto/sockets.rst:106 msgid "" "There's actually 3 general ways in which this loop could work - dispatching " "a thread to handle ``clientsocket``, create a new process to handle " "``clientsocket``, or restructure this app to use non-blocking sockets, and " "multiplex between our \"server\" socket and any active ``clientsocket``\\ s " "using ``select``. More about that later. The important thing to understand " "now is this: this is *all* a \"server\" socket does. It doesn't send any " "data. It doesn't receive any data. It just produces \"client\" sockets. Each " "``clientsocket`` is created in response to some *other* \"client\" socket " "doing a ``connect()`` to the host and port we're bound to. As soon as we've " "created that ``clientsocket``, we go back to listening for more connections. " "The two \"clients\" are free to chat it up - they are using some dynamically " "allocated port which will be recycled when the conversation ends." msgstr "" #: ../Doc/howto/sockets.rst:121 msgid "IPC" msgstr "" #: ../Doc/howto/sockets.rst:123 msgid "" "If you need fast IPC between two processes on one machine, you should look " "into pipes or shared memory. If you do decide to use AF_INET sockets, bind " "the \"server\" socket to ``'localhost'``. On most platforms, this will take " "a shortcut around a couple of layers of network code and be quite a bit " "faster." msgstr "" #: ../Doc/howto/sockets.rst:129 msgid "" "The :mod:`multiprocessing` integrates cross-platform IPC into a higher-level " "API." msgstr "" #: ../Doc/howto/sockets.rst:134 msgid "Using a Socket" msgstr "" #: ../Doc/howto/sockets.rst:136 msgid "" "The first thing to note, is that the web browser's \"client\" socket and the " "web server's \"client\" socket are identical beasts. That is, this is a " "\"peer to peer\" conversation. Or to put it another way, *as the designer, " "you will have to decide what the rules of etiquette are for a conversation*. " "Normally, the ``connect``\\ ing socket starts the conversation, by sending " "in a request, or perhaps a signon. But that's a design decision - it's not a " "rule of sockets." msgstr "" #: ../Doc/howto/sockets.rst:143 msgid "" "Now there are two sets of verbs to use for communication. You can use " "``send`` and ``recv``, or you can transform your client socket into a file-" "like beast and use ``read`` and ``write``. The latter is the way Java " "presents its sockets. I'm not going to talk about it here, except to warn " "you that you need to use ``flush`` on sockets. These are buffered \"files\", " "and a common mistake is to ``write`` something, and then ``read`` for a " "reply. Without a ``flush`` in there, you may wait forever for the reply, " "because the request may still be in your output buffer." msgstr "" #: ../Doc/howto/sockets.rst:152 msgid "" "Now we come to the major stumbling block of sockets - ``send`` and ``recv`` " "operate on the network buffers. They do not necessarily handle all the bytes " "you hand them (or expect from them), because their major focus is handling " "the network buffers. In general, they return when the associated network " "buffers have been filled (``send``) or emptied (``recv``). They then tell " "you how many bytes they handled. It is *your* responsibility to call them " "again until your message has been completely dealt with." msgstr "" #: ../Doc/howto/sockets.rst:160 msgid "" "When a ``recv`` returns 0 bytes, it means the other side has closed (or is " "in the process of closing) the connection. You will not receive any more " "data on this connection. Ever. You may be able to send data successfully; " "I'll talk more about this later." msgstr "" #: ../Doc/howto/sockets.rst:165 msgid "" "A protocol like HTTP uses a socket for only one transfer. The client sends a " "request, then reads a reply. That's it. The socket is discarded. This means " "that a client can detect the end of the reply by receiving 0 bytes." msgstr "" #: ../Doc/howto/sockets.rst:169 msgid "" "But if you plan to reuse your socket for further transfers, you need to " "realize that *there is no* :abbr:`EOT (End of Transfer)` *on a socket.* I " "repeat: if a socket ``send`` or ``recv`` returns after handling 0 bytes, the " "connection has been broken. If the connection has *not* been broken, you " "may wait on a ``recv`` forever, because the socket will *not* tell you that " "there's nothing more to read (for now). Now if you think about that a bit, " "you'll come to realize a fundamental truth of sockets: *messages must either " "be fixed length* (yuck), *or be delimited* (shrug), *or indicate how long " "they are* (much better), *or end by shutting down the connection*. The " "choice is entirely yours, (but some ways are righter than others)." msgstr "" #: ../Doc/howto/sockets.rst:180 msgid "" "Assuming you don't want to end the connection, the simplest solution is a " "fixed length message::" msgstr "" #: ../Doc/howto/sockets.rst:217 msgid "" "The sending code here is usable for almost any messaging scheme - in Python " "you send strings, and you can use ``len()`` to determine its length (even if " "it has embedded ``\\0`` characters). It's mostly the receiving code that " "gets more complex. (And in C, it's not much worse, except you can't use " "``strlen`` if the message has embedded ``\\0``\\ s.)" msgstr "" #: ../Doc/howto/sockets.rst:223 msgid "" "The easiest enhancement is to make the first character of the message an " "indicator of message type, and have the type determine the length. Now you " "have two ``recv``\\ s - the first to get (at least) that first character so " "you can look up the length, and the second in a loop to get the rest. If you " "decide to go the delimited route, you'll be receiving in some arbitrary " "chunk size, (4096 or 8192 is frequently a good match for network buffer " "sizes), and scanning what you've received for a delimiter." msgstr "" #: ../Doc/howto/sockets.rst:231 msgid "" "One complication to be aware of: if your conversational protocol allows " "multiple messages to be sent back to back (without some kind of reply), and " "you pass ``recv`` an arbitrary chunk size, you may end up reading the start " "of a following message. You'll need to put that aside and hold onto it, " "until it's needed." msgstr "" #: ../Doc/howto/sockets.rst:237 msgid "" "Prefixing the message with its length (say, as 5 numeric characters) gets " "more complex, because (believe it or not), you may not get all 5 characters " "in one ``recv``. In playing around, you'll get away with it; but in high " "network loads, your code will very quickly break unless you use two ``recv`` " "loops - the first to determine the length, the second to get the data part " "of the message. Nasty. This is also when you'll discover that ``send`` does " "not always manage to get rid of everything in one pass. And despite having " "read this, you will eventually get bit by it!" msgstr "" #: ../Doc/howto/sockets.rst:246 msgid "" "In the interests of space, building your character, (and preserving my " "competitive position), these enhancements are left as an exercise for the " "reader. Lets move on to cleaning up." msgstr "" #: ../Doc/howto/sockets.rst:252 msgid "Binary Data" msgstr "" #: ../Doc/howto/sockets.rst:254 msgid "" "It is perfectly possible to send binary data over a socket. The major " "problem is that not all machines use the same formats for binary data. For " "example, a Motorola chip will represent a 16 bit integer with the value 1 as " "the two hex bytes 00 01. Intel and DEC, however, are byte-reversed - that " "same 1 is 01 00. Socket libraries have calls for converting 16 and 32 bit " "integers - ``ntohl, htonl, ntohs, htons`` where \"n\" means *network* and \"h" "\" means *host*, \"s\" means *short* and \"l\" means *long*. Where network " "order is host order, these do nothing, but where the machine is byte-" "reversed, these swap the bytes around appropriately." msgstr "" #: ../Doc/howto/sockets.rst:264 msgid "" "In these days of 32 bit machines, the ascii representation of binary data is " "frequently smaller than the binary representation. That's because a " "surprising amount of the time, all those longs have the value 0, or maybe 1. " "The string \"0\" would be two bytes, while binary is four. Of course, this " "doesn't fit well with fixed-length messages. Decisions, decisions." msgstr "" #: ../Doc/howto/sockets.rst:272 msgid "Disconnecting" msgstr "" #: ../Doc/howto/sockets.rst:274 msgid "" "Strictly speaking, you're supposed to use ``shutdown`` on a socket before " "you ``close`` it. The ``shutdown`` is an advisory to the socket at the " "other end. Depending on the argument you pass it, it can mean \"I'm not " "going to send anymore, but I'll still listen\", or \"I'm not listening, good " "riddance!\". Most socket libraries, however, are so used to programmers " "neglecting to use this piece of etiquette that normally a ``close`` is the " "same as ``shutdown(); close()``. So in most situations, an explicit " "``shutdown`` is not needed." msgstr "" #: ../Doc/howto/sockets.rst:282 msgid "" "One way to use ``shutdown`` effectively is in an HTTP-like exchange. The " "client sends a request and then does a ``shutdown(1)``. This tells the " "server \"This client is done sending, but can still receive.\" The server " "can detect \"EOF\" by a receive of 0 bytes. It can assume it has the " "complete request. The server sends a reply. If the ``send`` completes " "successfully then, indeed, the client was still receiving." msgstr "" #: ../Doc/howto/sockets.rst:289 msgid "" "Python takes the automatic shutdown a step further, and says that when a " "socket is garbage collected, it will automatically do a ``close`` if it's " "needed. But relying on this is a very bad habit. If your socket just " "disappears without doing a ``close``, the socket at the other end may hang " "indefinitely, thinking you're just being slow. *Please* ``close`` your " "sockets when you're done." msgstr "" #: ../Doc/howto/sockets.rst:297 msgid "When Sockets Die" msgstr "" #: ../Doc/howto/sockets.rst:299 msgid "" "Probably the worst thing about using blocking sockets is what happens when " "the other side comes down hard (without doing a ``close``). Your socket is " "likely to hang. TCP is a reliable protocol, and it will wait a long, long " "time before giving up on a connection. If you're using threads, the entire " "thread is essentially dead. There's not much you can do about it. As long as " "you aren't doing something dumb, like holding a lock while doing a blocking " "read, the thread isn't really consuming much in the way of resources. Do " "*not* try to kill the thread - part of the reason that threads are more " "efficient than processes is that they avoid the overhead associated with the " "automatic recycling of resources. In other words, if you do manage to kill " "the thread, your whole process is likely to be screwed up." msgstr "" #: ../Doc/howto/sockets.rst:313 msgid "Non-blocking Sockets" msgstr "" #: ../Doc/howto/sockets.rst:315 msgid "" "If you've understood the preceding, you already know most of what you need " "to know about the mechanics of using sockets. You'll still use the same " "calls, in much the same ways. It's just that, if you do it right, your app " "will be almost inside-out." msgstr "" #: ../Doc/howto/sockets.rst:320 msgid "" "In Python, you use ``socket.setblocking(0)`` to make it non-blocking. In C, " "it's more complex, (for one thing, you'll need to choose between the BSD " "flavor ``O_NONBLOCK`` and the almost indistinguishable Posix flavor " "``O_NDELAY``, which is completely different from ``TCP_NODELAY``), but it's " "the exact same idea. You do this after creating the socket, but before using " "it. (Actually, if you're nuts, you can switch back and forth.)" msgstr "" #: ../Doc/howto/sockets.rst:327 msgid "" "The major mechanical difference is that ``send``, ``recv``, ``connect`` and " "``accept`` can return without having done anything. You have (of course) a " "number of choices. You can check return code and error codes and generally " "drive yourself crazy. If you don't believe me, try it sometime. Your app " "will grow large, buggy and suck CPU. So let's skip the brain-dead solutions " "and do it right." msgstr "" #: ../Doc/howto/sockets.rst:334 msgid "Use ``select``." msgstr "" #: ../Doc/howto/sockets.rst:336 msgid "" "In C, coding ``select`` is fairly complex. In Python, it's a piece of cake, " "but it's close enough to the C version that if you understand ``select`` in " "Python, you'll have little trouble with it in C::" msgstr "" #: ../Doc/howto/sockets.rst:347 msgid "" "You pass ``select`` three lists: the first contains all sockets that you " "might want to try reading; the second all the sockets you might want to try " "writing to, and the last (normally left empty) those that you want to check " "for errors. You should note that a socket can go into more than one list. " "The ``select`` call is blocking, but you can give it a timeout. This is " "generally a sensible thing to do - give it a nice long timeout (say a " "minute) unless you have good reason to do otherwise." msgstr "" #: ../Doc/howto/sockets.rst:355 msgid "" "In return, you will get three lists. They contain the sockets that are " "actually readable, writable and in error. Each of these lists is a subset " "(possibly empty) of the corresponding list you passed in." msgstr "" #: ../Doc/howto/sockets.rst:359 msgid "" "If a socket is in the output readable list, you can be as-close-to-certain-" "as-we-ever-get-in-this-business that a ``recv`` on that socket will return " "*something*. Same idea for the writable list. You'll be able to send " "*something*. Maybe not all you want to, but *something* is better than " "nothing. (Actually, any reasonably healthy socket will return as writable - " "it just means outbound network buffer space is available.)" msgstr "" #: ../Doc/howto/sockets.rst:366 msgid "" "If you have a \"server\" socket, put it in the potential_readers list. If it " "comes out in the readable list, your ``accept`` will (almost certainly) " "work. If you have created a new socket to ``connect`` to someone else, put " "it in the potential_writers list. If it shows up in the writable list, you " "have a decent chance that it has connected." msgstr "" #: ../Doc/howto/sockets.rst:372 msgid "" "Actually, ``select`` can be handy even with blocking sockets. It's one way " "of determining whether you will block - the socket returns as readable when " "there's something in the buffers. However, this still doesn't help with the " "problem of determining whether the other end is done, or just busy with " "something else." msgstr "" #: ../Doc/howto/sockets.rst:377 msgid "" "**Portability alert**: On Unix, ``select`` works both with the sockets and " "files. Don't try this on Windows. On Windows, ``select`` works with sockets " "only. Also note that in C, many of the more advanced socket options are done " "differently on Windows. In fact, on Windows I usually use threads (which " "work very, very well) with my sockets." msgstr "" #: ../Doc/howto/sorting.rst:4 msgid "Sorting HOW TO" msgstr "" #: ../Doc/howto/sorting.rst:6 msgid "Andrew Dalke and Raymond Hettinger" msgstr "" #: ../Doc/howto/sorting.rst:7 msgid "0.1" msgstr "" #: ../Doc/howto/sorting.rst:10 msgid "" "Python lists have a built-in :meth:`list.sort` method that modifies the list " "in-place. There is also a :func:`sorted` built-in function that builds a " "new sorted list from an iterable." msgstr "" #: ../Doc/howto/sorting.rst:14 msgid "" "In this document, we explore the various techniques for sorting data using " "Python." msgstr "" #: ../Doc/howto/sorting.rst:18 msgid "Sorting Basics" msgstr "" #: ../Doc/howto/sorting.rst:20 msgid "" "A simple ascending sort is very easy: just call the :func:`sorted` function. " "It returns a new sorted list::" msgstr "" #: ../Doc/howto/sorting.rst:26 msgid "" "You can also use the :meth:`list.sort` method. It modifies the list in-place " "(and returns *None* to avoid confusion). Usually it's less convenient than :" "func:`sorted` - but if you don't need the original list, it's slightly more " "efficient." msgstr "" #: ../Doc/howto/sorting.rst:36 msgid "" "Another difference is that the :meth:`list.sort` method is only defined for " "lists. In contrast, the :func:`sorted` function accepts any iterable." msgstr "" #: ../Doc/howto/sorting.rst:43 msgid "Key Functions" msgstr "" #: ../Doc/howto/sorting.rst:45 msgid "" "Both :meth:`list.sort` and :func:`sorted` have a *key* parameter to specify " "a function to be called on each list element prior to making comparisons." msgstr "" #: ../Doc/howto/sorting.rst:48 msgid "For example, here's a case-insensitive string comparison:" msgstr "" #: ../Doc/howto/sorting.rst:53 msgid "" "The value of the *key* parameter should be a function that takes a single " "argument and returns a key to use for sorting purposes. This technique is " "fast because the key function is called exactly once for each input record." msgstr "" #: ../Doc/howto/sorting.rst:57 msgid "" "A common pattern is to sort complex objects using some of the object's " "indices as keys. For example:" msgstr "" #: ../Doc/howto/sorting.rst:68 msgid "" "The same technique works for objects with named attributes. For example:" msgstr "" #: ../Doc/howto/sorting.rst:87 msgid "Operator Module Functions" msgstr "" #: ../Doc/howto/sorting.rst:89 msgid "" "The key-function patterns shown above are very common, so Python provides " "convenience functions to make accessor functions easier and faster. The :mod:" "`operator` module has :func:`~operator.itemgetter`, :func:`~operator." "attrgetter`, and a :func:`~operator.methodcaller` function." msgstr "" #: ../Doc/howto/sorting.rst:94 msgid "Using those functions, the above examples become simpler and faster:" msgstr "" #: ../Doc/howto/sorting.rst:104 msgid "" "The operator module functions allow multiple levels of sorting. For example, " "to sort by *grade* then by *age*:" msgstr "" #: ../Doc/howto/sorting.rst:114 msgid "Ascending and Descending" msgstr "" #: ../Doc/howto/sorting.rst:116 msgid "" "Both :meth:`list.sort` and :func:`sorted` accept a *reverse* parameter with " "a boolean value. This is used to flag descending sorts. For example, to get " "the student data in reverse *age* order:" msgstr "" #: ../Doc/howto/sorting.rst:127 msgid "Sort Stability and Complex Sorts" msgstr "" #: ../Doc/howto/sorting.rst:129 msgid "" "Sorts are guaranteed to be `stable `_\\. That means that when multiple records have " "the same key, their original order is preserved." msgstr "" #: ../Doc/howto/sorting.rst:137 msgid "" "Notice how the two records for *blue* retain their original order so that " "``('blue', 1)`` is guaranteed to precede ``('blue', 2)``." msgstr "" #: ../Doc/howto/sorting.rst:140 msgid "" "This wonderful property lets you build complex sorts in a series of sorting " "steps. For example, to sort the student data by descending *grade* and then " "ascending *age*, do the *age* sort first and then sort again using *grade*:" msgstr "" #: ../Doc/howto/sorting.rst:148 msgid "" "The `Timsort `_ algorithm used in " "Python does multiple sorts efficiently because it can take advantage of any " "ordering already present in a dataset." msgstr "" #: ../Doc/howto/sorting.rst:153 msgid "The Old Way Using Decorate-Sort-Undecorate" msgstr "" #: ../Doc/howto/sorting.rst:155 msgid "This idiom is called Decorate-Sort-Undecorate after its three steps:" msgstr "" #: ../Doc/howto/sorting.rst:157 msgid "" "First, the initial list is decorated with new values that control the sort " "order." msgstr "" #: ../Doc/howto/sorting.rst:159 msgid "Second, the decorated list is sorted." msgstr "" #: ../Doc/howto/sorting.rst:161 msgid "" "Finally, the decorations are removed, creating a list that contains only the " "initial values in the new order." msgstr "" #: ../Doc/howto/sorting.rst:164 msgid "" "For example, to sort the student data by *grade* using the DSU approach:" msgstr "" #: ../Doc/howto/sorting.rst:171 msgid "" "This idiom works because tuples are compared lexicographically; the first " "items are compared; if they are the same then the second items are compared, " "and so on." msgstr "" #: ../Doc/howto/sorting.rst:175 msgid "" "It is not strictly necessary in all cases to include the index *i* in the " "decorated list, but including it gives two benefits:" msgstr "" #: ../Doc/howto/sorting.rst:178 msgid "" "The sort is stable -- if two items have the same key, their order will be " "preserved in the sorted list." msgstr "" #: ../Doc/howto/sorting.rst:181 msgid "" "The original items do not have to be comparable because the ordering of the " "decorated tuples will be determined by at most the first two items. So for " "example the original list could contain complex numbers which cannot be " "sorted directly." msgstr "" #: ../Doc/howto/sorting.rst:186 msgid "" "Another name for this idiom is `Schwartzian transform `_\\, after Randal L. Schwartz, who " "popularized it among Perl programmers." msgstr "" #: ../Doc/howto/sorting.rst:190 msgid "" "Now that Python sorting provides key-functions, this technique is not often " "needed." msgstr "" #: ../Doc/howto/sorting.rst:194 msgid "The Old Way Using the *cmp* Parameter" msgstr "" #: ../Doc/howto/sorting.rst:196 msgid "" "Many constructs given in this HOWTO assume Python 2.4 or later. Before that, " "there was no :func:`sorted` builtin and :meth:`list.sort` took no keyword " "arguments. Instead, all of the Py2.x versions supported a *cmp* parameter to " "handle user specified comparison functions." msgstr "" #: ../Doc/howto/sorting.rst:201 msgid "" "In Py3.0, the *cmp* parameter was removed entirely (as part of a larger " "effort to simplify and unify the language, eliminating the conflict between " "rich comparisons and the :meth:`__cmp__` magic method)." msgstr "" #: ../Doc/howto/sorting.rst:205 msgid "" "In Py2.x, sort allowed an optional function which can be called for doing " "the comparisons. That function should take two arguments to be compared and " "then return a negative value for less-than, return zero if they are equal, " "or return a positive value for greater-than. For example, we can do:" msgstr "" #: ../Doc/howto/sorting.rst:215 msgid "Or you can reverse the order of comparison with:" msgstr "" #: ../Doc/howto/sorting.rst:222 msgid "" "When porting code from Python 2.x to 3.x, the situation can arise when you " "have the user supplying a comparison function and you need to convert that " "to a key function. The following wrapper makes that easy to do::" msgstr "" #: ../Doc/howto/sorting.rst:245 msgid "To convert to a key function, just wrap the old comparison function:" msgstr "" #: ../Doc/howto/sorting.rst:256 msgid "" "In Python 3.2, the :func:`functools.cmp_to_key` function was added to the :" "mod:`functools` module in the standard library." msgstr "" #: ../Doc/howto/sorting.rst:260 msgid "Odd and Ends" msgstr "" #: ../Doc/howto/sorting.rst:262 msgid "" "For locale aware sorting, use :func:`locale.strxfrm` for a key function or :" "func:`locale.strcoll` for a comparison function." msgstr "" #: ../Doc/howto/sorting.rst:265 msgid "" "The *reverse* parameter still maintains sort stability (so that records with " "equal keys retain the original order). Interestingly, that effect can be " "simulated without the parameter by using the builtin :func:`reversed` " "function twice:" msgstr "" #: ../Doc/howto/sorting.rst:277 msgid "" "The sort routines are guaranteed to use :meth:`__lt__` when making " "comparisons between two objects. So, it is easy to add a standard sort order " "to a class by defining an :meth:`__lt__` method::" msgstr "" #: ../Doc/howto/sorting.rst:285 msgid "" "Key functions need not depend directly on the objects being sorted. A key " "function can also access external resources. For instance, if the student " "grades are stored in a dictionary, they can be used to sort a separate list " "of student names:" msgstr "" #: ../Doc/howto/unicode.rst:5 msgid "Unicode HOWTO" msgstr "" #: ../Doc/howto/unicode.rst:7 msgid "1.12" msgstr "" #: ../Doc/howto/unicode.rst:9 msgid "" "This HOWTO discusses Python support for Unicode, and explains various " "problems that people commonly encounter when trying to work with Unicode." msgstr "" #: ../Doc/howto/unicode.rst:14 msgid "Introduction to Unicode" msgstr "" #: ../Doc/howto/unicode.rst:17 msgid "History of Character Codes" msgstr "" #: ../Doc/howto/unicode.rst:19 msgid "" "In 1968, the American Standard Code for Information Interchange, better " "known by its acronym ASCII, was standardized. ASCII defined numeric codes " "for various characters, with the numeric values running from 0 to 127. For " "example, the lowercase letter 'a' is assigned 97 as its code value." msgstr "" #: ../Doc/howto/unicode.rst:24 msgid "" "ASCII was an American-developed standard, so it only defined unaccented " "characters. There was an 'e', but no 'é' or 'Í'. This meant that languages " "which required accented characters couldn't be faithfully represented in " "ASCII. (Actually the missing accents matter for English, too, which contains " "words such as 'naïve' and 'café', and some publications have house styles " "which require spellings such as 'coöperate'.)" msgstr "" #: ../Doc/howto/unicode.rst:31 msgid "" "For a while people just wrote programs that didn't display accents. In the " "mid-1980s an Apple II BASIC program written by a French speaker might have " "lines like these::" msgstr "" #: ../Doc/howto/unicode.rst:38 msgid "" "Those messages should contain accents (terminée, paramètre, enregistrés) and " "they just look wrong to someone who can read French." msgstr "" #: ../Doc/howto/unicode.rst:41 msgid "" "In the 1980s, almost all personal computers were 8-bit, meaning that bytes " "could hold values ranging from 0 to 255. ASCII codes only went up to 127, " "so some machines assigned values between 128 and 255 to accented " "characters. Different machines had different codes, however, which led to " "problems exchanging files. Eventually various commonly used sets of values " "for the 128--255 range emerged. Some were true standards, defined by the " "International Standards Organization, and some were *de facto* conventions " "that were invented by one company or another and managed to catch on." msgstr "" #: ../Doc/howto/unicode.rst:50 msgid "" "255 characters aren't very many. For example, you can't fit both the " "accented characters used in Western Europe and the Cyrillic alphabet used " "for Russian into the 128--255 range because there are more than 128 such " "characters." msgstr "" #: ../Doc/howto/unicode.rst:54 msgid "" "You could write files using different codes (all your Russian files in a " "coding system called KOI8, all your French files in a different coding " "system called Latin1), but what if you wanted to write a French document " "that quotes some Russian text? In the 1980s people began to want to solve " "this problem, and the Unicode standardization effort began." msgstr "" #: ../Doc/howto/unicode.rst:60 msgid "" "Unicode started out using 16-bit characters instead of 8-bit characters. 16 " "bits means you have 2^16 = 65,536 distinct values available, making it " "possible to represent many different characters from many different " "alphabets; an initial goal was to have Unicode contain the alphabets for " "every single human language. It turns out that even 16 bits isn't enough to " "meet that goal, and the modern Unicode specification uses a wider range of " "codes, 0 through 1,114,111 ( ``0x10FFFF`` in base 16)." msgstr "" #: ../Doc/howto/unicode.rst:68 msgid "" "There's a related ISO standard, ISO 10646. Unicode and ISO 10646 were " "originally separate efforts, but the specifications were merged with the 1.1 " "revision of Unicode." msgstr "" #: ../Doc/howto/unicode.rst:72 msgid "" "(This discussion of Unicode's history is highly simplified. The precise " "historical details aren't necessary for understanding how to use Unicode " "effectively, but if you're curious, consult the Unicode consortium site " "listed in the References or the `Wikipedia entry for Unicode `_ for more information.)" msgstr "" #: ../Doc/howto/unicode.rst:81 msgid "Definitions" msgstr "" #: ../Doc/howto/unicode.rst:83 msgid "" "A **character** is the smallest possible component of a text. 'A', 'B', " "'C', etc., are all different characters. So are 'È' and 'Í'. Characters " "are abstractions, and vary depending on the language or context you're " "talking about. For example, the symbol for ohms (Ω) is usually drawn much " "like the capital letter omega (Ω) in the Greek alphabet (they may even be " "the same in some fonts), but these are two different characters that have " "different meanings." msgstr "" #: ../Doc/howto/unicode.rst:91 msgid "" "The Unicode standard describes how characters are represented by **code " "points**. A code point is an integer value, usually denoted in base 16. In " "the standard, a code point is written using the notation ``U+12CA`` to mean " "the character with value ``0x12ca`` (4,810 decimal). The Unicode standard " "contains a lot of tables listing characters and their corresponding code " "points:" msgstr "" #: ../Doc/howto/unicode.rst:105 msgid "" "Strictly, these definitions imply that it's meaningless to say 'this is " "character ``U+12CA``'. ``U+12CA`` is a code point, which represents some " "particular character; in this case, it represents the character 'ETHIOPIC " "SYLLABLE WI'. In informal contexts, this distinction between code points " "and characters will sometimes be forgotten." msgstr "" #: ../Doc/howto/unicode.rst:111 msgid "" "A character is represented on a screen or on paper by a set of graphical " "elements that's called a **glyph**. The glyph for an uppercase A, for " "example, is two diagonal strokes and a horizontal stroke, though the exact " "details will depend on the font being used. Most Python code doesn't need " "to worry about glyphs; figuring out the correct glyph to display is " "generally the job of a GUI toolkit or a terminal's font renderer." msgstr "" #: ../Doc/howto/unicode.rst:120 msgid "Encodings" msgstr "" #: ../Doc/howto/unicode.rst:122 msgid "" "To summarize the previous section: a Unicode string is a sequence of code " "points, which are numbers from 0 through ``0x10FFFF`` (1,114,111 decimal). " "This sequence needs to be represented as a set of bytes (meaning, values " "from 0 through 255) in memory. The rules for translating a Unicode string " "into a sequence of bytes are called an **encoding**." msgstr "" #: ../Doc/howto/unicode.rst:128 msgid "" "The first encoding you might think of is an array of 32-bit integers. In " "this representation, the string \"Python\" would look like this:" msgstr "" #: ../Doc/howto/unicode.rst:137 msgid "" "This representation is straightforward but using it presents a number of " "problems." msgstr "" #: ../Doc/howto/unicode.rst:140 msgid "It's not portable; different processors order the bytes differently." msgstr "" #: ../Doc/howto/unicode.rst:142 msgid "" "It's very wasteful of space. In most texts, the majority of the code points " "are less than 127, or less than 255, so a lot of space is occupied by " "``0x00`` bytes. The above string takes 24 bytes compared to the 6 bytes " "needed for an ASCII representation. Increased RAM usage doesn't matter too " "much (desktop computers have gigabytes of RAM, and strings aren't usually " "that large), but expanding our usage of disk and network bandwidth by a " "factor of 4 is intolerable." msgstr "" #: ../Doc/howto/unicode.rst:150 msgid "" "It's not compatible with existing C functions such as ``strlen()``, so a new " "family of wide string functions would need to be used." msgstr "" #: ../Doc/howto/unicode.rst:153 msgid "" "Many Internet standards are defined in terms of textual data, and can't " "handle content with embedded zero bytes." msgstr "" #: ../Doc/howto/unicode.rst:156 msgid "" "Generally people don't use this encoding, instead choosing other encodings " "that are more efficient and convenient. UTF-8 is probably the most commonly " "supported encoding; it will be discussed below." msgstr "" #: ../Doc/howto/unicode.rst:160 msgid "" "Encodings don't have to handle every possible Unicode character, and most " "encodings don't. The rules for converting a Unicode string into the ASCII " "encoding, for example, are simple; for each code point:" msgstr "" #: ../Doc/howto/unicode.rst:164 msgid "" "If the code point is < 128, each byte is the same as the value of the code " "point." msgstr "" #: ../Doc/howto/unicode.rst:167 msgid "" "If the code point is 128 or greater, the Unicode string can't be represented " "in this encoding. (Python raises a :exc:`UnicodeEncodeError` exception in " "this case.)" msgstr "" #: ../Doc/howto/unicode.rst:171 msgid "" "Latin-1, also known as ISO-8859-1, is a similar encoding. Unicode code " "points 0--255 are identical to the Latin-1 values, so converting to this " "encoding simply requires converting code points to byte values; if a code " "point larger than 255 is encountered, the string can't be encoded into " "Latin-1." msgstr "" #: ../Doc/howto/unicode.rst:176 msgid "" "Encodings don't have to be simple one-to-one mappings like Latin-1. " "Consider IBM's EBCDIC, which was used on IBM mainframes. Letter values " "weren't in one block: 'a' through 'i' had values from 129 to 137, but 'j' " "through 'r' were 145 through 153. If you wanted to use EBCDIC as an " "encoding, you'd probably use some sort of lookup table to perform the " "conversion, but this is largely an internal detail." msgstr "" #: ../Doc/howto/unicode.rst:183 msgid "" "UTF-8 is one of the most commonly used encodings. UTF stands for \"Unicode " "Transformation Format\", and the '8' means that 8-bit numbers are used in " "the encoding. (There are also a UTF-16 and UTF-32 encodings, but they are " "less frequently used than UTF-8.) UTF-8 uses the following rules:" msgstr "" #: ../Doc/howto/unicode.rst:188 msgid "" "If the code point is < 128, it's represented by the corresponding byte value." msgstr "" #: ../Doc/howto/unicode.rst:189 msgid "" "If the code point is >= 128, it's turned into a sequence of two, three, or " "four bytes, where each byte of the sequence is between 128 and 255." msgstr "" #: ../Doc/howto/unicode.rst:192 msgid "UTF-8 has several convenient properties:" msgstr "" #: ../Doc/howto/unicode.rst:194 msgid "It can handle any Unicode code point." msgstr "" #: ../Doc/howto/unicode.rst:195 msgid "" "A Unicode string is turned into a sequence of bytes containing no embedded " "zero bytes. This avoids byte-ordering issues, and means UTF-8 strings can " "be processed by C functions such as ``strcpy()`` and sent through protocols " "that can't handle zero bytes." msgstr "" #: ../Doc/howto/unicode.rst:199 msgid "A string of ASCII text is also valid UTF-8 text." msgstr "" #: ../Doc/howto/unicode.rst:200 msgid "" "UTF-8 is fairly compact; the majority of commonly used characters can be " "represented with one or two bytes." msgstr "" #: ../Doc/howto/unicode.rst:202 msgid "" "If bytes are corrupted or lost, it's possible to determine the start of the " "next UTF-8-encoded code point and resynchronize. It's also unlikely that " "random 8-bit data will look like valid UTF-8." msgstr "" #: ../Doc/howto/unicode.rst:211 msgid "" "The `Unicode Consortium site `_ has character " "charts, a glossary, and PDF versions of the Unicode specification. Be " "prepared for some difficult reading. `A chronology `_ of the origin and development of Unicode is also available on " "the site." msgstr "" #: ../Doc/howto/unicode.rst:216 msgid "" "To help understand the standard, Jukka Korpela has written `an introductory " "guide `_ to reading the " "Unicode character tables." msgstr "" #: ../Doc/howto/unicode.rst:220 msgid "" "Another `good introductory article `_ was written by Joel Spolsky. If this introduction didn't " "make things clear to you, you should try reading this alternate article " "before continuing." msgstr "" #: ../Doc/howto/unicode.rst:225 msgid "" "Wikipedia entries are often helpful; see the entries for \"`character " "encoding `_\" and `UTF-8 " "`_, for example." msgstr "" #: ../Doc/howto/unicode.rst:231 msgid "Python's Unicode Support" msgstr "" #: ../Doc/howto/unicode.rst:233 msgid "" "Now that you've learned the rudiments of Unicode, we can look at Python's " "Unicode features." msgstr "" #: ../Doc/howto/unicode.rst:237 msgid "The String Type" msgstr "" #: ../Doc/howto/unicode.rst:239 msgid "" "Since Python 3.0, the language features a :class:`str` type that contain " "Unicode characters, meaning any string created using ``\"unicode rocks!\"``, " "``'unicode rocks!'``, or the triple-quoted string syntax is stored as " "Unicode." msgstr "" #: ../Doc/howto/unicode.rst:243 msgid "" "The default encoding for Python source code is UTF-8, so you can simply " "include a Unicode character in a string literal::" msgstr "" #: ../Doc/howto/unicode.rst:253 msgid "" "You can use a different encoding from UTF-8 by putting a specially-formatted " "comment as the first or second line of the source code::" msgstr "" #: ../Doc/howto/unicode.rst:258 msgid "" "Side note: Python 3 also supports using Unicode characters in identifiers::" msgstr "" #: ../Doc/howto/unicode.rst:264 msgid "" "If you can't enter a particular character in your editor or want to keep the " "source code ASCII-only for some reason, you can also use escape sequences in " "string literals. (Depending on your system, you may see the actual capital-" "delta glyph instead of a \\u escape.) ::" msgstr "" #: ../Doc/howto/unicode.rst:276 msgid "" "In addition, one can create a string using the :func:`~bytes.decode` method " "of :class:`bytes`. This method takes an *encoding* argument, such as " "``UTF-8``, and optionally an *errors* argument." msgstr "" #: ../Doc/howto/unicode.rst:280 msgid "" "The *errors* argument specifies the response when the input string can't be " "converted according to the encoding's rules. Legal values for this argument " "are ``'strict'`` (raise a :exc:`UnicodeDecodeError` exception), " "``'replace'`` (use ``U+FFFD``, ``REPLACEMENT CHARACTER``), ``'ignore'`` " "(just leave the character out of the Unicode result), or " "``'backslashreplace'`` (inserts a ``\\xNN`` escape sequence). The following " "examples show the differences::" msgstr "" #: ../Doc/howto/unicode.rst:300 msgid "" "Encodings are specified as strings containing the encoding's name. Python " "3.2 comes with roughly 100 different encodings; see the Python Library " "Reference at :ref:`standard-encodings` for a list. Some encodings have " "multiple names; for example, ``'latin-1'``, ``'iso_8859_1'`` and ``'8859``' " "are all synonyms for the same encoding." msgstr "" #: ../Doc/howto/unicode.rst:306 msgid "" "One-character Unicode strings can also be created with the :func:`chr` built-" "in function, which takes integers and returns a Unicode string of length 1 " "that contains the corresponding code point. The reverse operation is the " "built-in :func:`ord` function that takes a one-character Unicode string and " "returns the code point value::" msgstr "" #: ../Doc/howto/unicode.rst:318 msgid "Converting to Bytes" msgstr "" #: ../Doc/howto/unicode.rst:320 msgid "" "The opposite method of :meth:`bytes.decode` is :meth:`str.encode`, which " "returns a :class:`bytes` representation of the Unicode string, encoded in " "the requested *encoding*." msgstr "" #: ../Doc/howto/unicode.rst:324 msgid "" "The *errors* parameter is the same as the parameter of the :meth:`~bytes." "decode` method but supports a few more possible handlers. As well as " "``'strict'``, ``'ignore'``, and ``'replace'`` (which in this case inserts a " "question mark instead of the unencodable character), there is also " "``'xmlcharrefreplace'`` (inserts an XML character reference), " "``backslashreplace`` (inserts a ``\\uNNNN`` escape sequence) and " "``namereplace`` (inserts a ``\\N{...}`` escape sequence)." msgstr "" #: ../Doc/howto/unicode.rst:332 msgid "The following example shows the different results::" msgstr "" #: ../Doc/howto/unicode.rst:353 msgid "" "The low-level routines for registering and accessing the available encodings " "are found in the :mod:`codecs` module. Implementing new encodings also " "requires understanding the :mod:`codecs` module. However, the encoding and " "decoding functions returned by this module are usually more low-level than " "is comfortable, and writing new encodings is a specialized task, so the " "module won't be covered in this HOWTO." msgstr "" #: ../Doc/howto/unicode.rst:362 msgid "Unicode Literals in Python Source Code" msgstr "" #: ../Doc/howto/unicode.rst:364 msgid "" "In Python source code, specific Unicode code points can be written using the " "``\\u`` escape sequence, which is followed by four hex digits giving the " "code point. The ``\\U`` escape sequence is similar, but expects eight hex " "digits, not four::" msgstr "" #: ../Doc/howto/unicode.rst:376 msgid "" "Using escape sequences for code points greater than 127 is fine in small " "doses, but becomes an annoyance if you're using many accented characters, as " "you would in a program with messages in French or some other accent-using " "language. You can also assemble strings using the :func:`chr` built-in " "function, but this is even more tedious." msgstr "" #: ../Doc/howto/unicode.rst:382 msgid "" "Ideally, you'd want to be able to write literals in your language's natural " "encoding. You could then edit Python source code with your favorite editor " "which would display the accented characters naturally, and have the right " "characters used at runtime." msgstr "" #: ../Doc/howto/unicode.rst:387 msgid "" "Python supports writing source code in UTF-8 by default, but you can use " "almost any encoding if you declare the encoding being used. This is done by " "including a special comment as either the first or second line of the source " "file::" msgstr "" #: ../Doc/howto/unicode.rst:397 msgid "" "The syntax is inspired by Emacs's notation for specifying variables local to " "a file. Emacs supports many different variables, but Python only supports " "'coding'. The ``-*-`` symbols indicate to Emacs that the comment is " "special; they have no significance to Python but are a convention. Python " "looks for ``coding: name`` or ``coding=name`` in the comment." msgstr "" #: ../Doc/howto/unicode.rst:403 msgid "" "If you don't include such a comment, the default encoding used will be UTF-8 " "as already mentioned. See also :pep:`263` for more information." msgstr "" #: ../Doc/howto/unicode.rst:408 msgid "Unicode Properties" msgstr "" #: ../Doc/howto/unicode.rst:410 msgid "" "The Unicode specification includes a database of information about code " "points. For each defined code point, the information includes the " "character's name, its category, the numeric value if applicable (Unicode has " "characters representing the Roman numerals and fractions such as one-third " "and four-fifths). There are also properties related to the code point's use " "in bidirectional text and other display-related properties." msgstr "" #: ../Doc/howto/unicode.rst:417 msgid "" "The following program displays some information about several characters, " "and prints the numeric value of one particular character::" msgstr "" #: ../Doc/howto/unicode.rst:431 msgid "When run, this prints:" msgstr "" #: ../Doc/howto/unicode.rst:442 msgid "" "The category codes are abbreviations describing the nature of the character. " "These are grouped into categories such as \"Letter\", \"Number\", " "\"Punctuation\", or \"Symbol\", which in turn are broken up into " "subcategories. To take the codes from the above output, ``'Ll'`` means " "'Letter, lowercase', ``'No'`` means \"Number, other\", ``'Mn'`` is \"Mark, " "nonspacing\", and ``'So'`` is \"Symbol, other\". See `the General Category " "Values section of the Unicode Character Database documentation `_ for a list of category " "codes." msgstr "" #: ../Doc/howto/unicode.rst:453 msgid "Unicode Regular Expressions" msgstr "" #: ../Doc/howto/unicode.rst:455 msgid "" "The regular expressions supported by the :mod:`re` module can be provided " "either as bytes or strings. Some of the special character sequences such as " "``\\d`` and ``\\w`` have different meanings depending on whether the pattern " "is supplied as bytes or a string. For example, ``\\d`` will match the " "characters ``[0-9]`` in bytes but in strings will match any character that's " "in the ``'Nd'`` category." msgstr "" #: ../Doc/howto/unicode.rst:462 msgid "" "The string in this example has the number 57 written in both Thai and Arabic " "numerals::" msgstr "" #: ../Doc/howto/unicode.rst:472 msgid "" "When executed, ``\\d+`` will match the Thai numerals and print them out. If " "you supply the :const:`re.ASCII` flag to :func:`~re.compile`, ``\\d+`` will " "match the substring \"57\" instead." msgstr "" #: ../Doc/howto/unicode.rst:476 msgid "" "Similarly, ``\\w`` matches a wide variety of Unicode characters but only " "``[a-zA-Z0-9_]`` in bytes or if :const:`re.ASCII` is supplied, and ``\\s`` " "will match either Unicode whitespace characters or ``[ \\t\\n\\r\\f\\v]``." msgstr "" #: ../Doc/howto/unicode.rst:487 msgid "Some good alternative discussions of Python's Unicode support are:" msgstr "" #: ../Doc/howto/unicode.rst:489 msgid "" "`Processing Text Files in Python 3 `_, by Nick Coghlan." msgstr "" #: ../Doc/howto/unicode.rst:490 msgid "" "`Pragmatic Unicode `_, a PyCon " "2012 presentation by Ned Batchelder." msgstr "" #: ../Doc/howto/unicode.rst:492 msgid "" "The :class:`str` type is described in the Python library reference at :ref:" "`textseq`." msgstr "" #: ../Doc/howto/unicode.rst:495 msgid "The documentation for the :mod:`unicodedata` module." msgstr "" #: ../Doc/howto/unicode.rst:497 msgid "The documentation for the :mod:`codecs` module." msgstr "" #: ../Doc/howto/unicode.rst:499 msgid "" "Marc-André Lemburg gave `a presentation titled \"Python and Unicode\" (PDF " "slides) `_ at " "EuroPython 2002. The slides are an excellent overview of the design of " "Python 2's Unicode features (where the Unicode string type is called " "``unicode`` and literals start with ``u``)." msgstr "" #: ../Doc/howto/unicode.rst:507 msgid "Reading and Writing Unicode Data" msgstr "" #: ../Doc/howto/unicode.rst:509 msgid "" "Once you've written some code that works with Unicode data, the next problem " "is input/output. How do you get Unicode strings into your program, and how " "do you convert Unicode into a form suitable for storage or transmission?" msgstr "" #: ../Doc/howto/unicode.rst:513 msgid "" "It's possible that you may not need to do anything depending on your input " "sources and output destinations; you should check whether the libraries used " "in your application support Unicode natively. XML parsers often return " "Unicode data, for example. Many relational databases also support Unicode-" "valued columns and can return Unicode values from an SQL query." msgstr "" #: ../Doc/howto/unicode.rst:519 msgid "" "Unicode data is usually converted to a particular encoding before it gets " "written to disk or sent over a socket. It's possible to do all the work " "yourself: open a file, read an 8-bit bytes object from it, and convert the " "bytes with ``bytes.decode(encoding)``. However, the manual approach is not " "recommended." msgstr "" #: ../Doc/howto/unicode.rst:524 msgid "" "One problem is the multi-byte nature of encodings; one Unicode character can " "be represented by several bytes. If you want to read the file in arbitrary-" "sized chunks (say, 1024 or 4096 bytes), you need to write error-handling " "code to catch the case where only part of the bytes encoding a single " "Unicode character are read at the end of a chunk. One solution would be to " "read the entire file into memory and then perform the decoding, but that " "prevents you from working with files that are extremely large; if you need " "to read a 2 GiB file, you need 2 GiB of RAM. (More, really, since for at " "least a moment you'd need to have both the encoded string and its Unicode " "version in memory.)" msgstr "" #: ../Doc/howto/unicode.rst:534 msgid "" "The solution would be to use the low-level decoding interface to catch the " "case of partial coding sequences. The work of implementing this has already " "been done for you: the built-in :func:`open` function can return a file-like " "object that assumes the file's contents are in a specified encoding and " "accepts Unicode parameters for methods such as :meth:`~io.TextIOBase.read` " "and :meth:`~io.TextIOBase.write`. This works through :func:`open`\\'s " "*encoding* and *errors* parameters which are interpreted just like those in :" "meth:`str.encode` and :meth:`bytes.decode`." msgstr "" #: ../Doc/howto/unicode.rst:543 msgid "Reading Unicode from a file is therefore simple::" msgstr "" #: ../Doc/howto/unicode.rst:549 msgid "" "It's also possible to open files in update mode, allowing both reading and " "writing::" msgstr "" #: ../Doc/howto/unicode.rst:557 msgid "" "The Unicode character ``U+FEFF`` is used as a byte-order mark (BOM), and is " "often written as the first character of a file in order to assist with " "autodetection of the file's byte ordering. Some encodings, such as UTF-16, " "expect a BOM to be present at the start of a file; when such an encoding is " "used, the BOM will be automatically written as the first character and will " "be silently dropped when the file is read. There are variants of these " "encodings, such as 'utf-16-le' and 'utf-16-be' for little-endian and big-" "endian encodings, that specify one particular byte ordering and don't skip " "the BOM." msgstr "" #: ../Doc/howto/unicode.rst:566 msgid "" "In some areas, it is also convention to use a \"BOM\" at the start of UTF-8 " "encoded files; the name is misleading since UTF-8 is not byte-order " "dependent. The mark simply announces that the file is encoded in UTF-8. Use " "the 'utf-8-sig' codec to automatically skip the mark if present for reading " "such files." msgstr "" #: ../Doc/howto/unicode.rst:574 msgid "Unicode filenames" msgstr "" #: ../Doc/howto/unicode.rst:576 msgid "" "Most of the operating systems in common use today support filenames that " "contain arbitrary Unicode characters. Usually this is implemented by " "converting the Unicode string into some encoding that varies depending on " "the system. For example, Mac OS X uses UTF-8 while Windows uses a " "configurable encoding; on Windows, Python uses the name \"mbcs\" to refer to " "whatever the currently configured encoding is. On Unix systems, there will " "only be a filesystem encoding if you've set the ``LANG`` or ``LC_CTYPE`` " "environment variables; if you haven't, the default encoding is UTF-8." msgstr "" #: ../Doc/howto/unicode.rst:585 msgid "" "The :func:`sys.getfilesystemencoding` function returns the encoding to use " "on your current system, in case you want to do the encoding manually, but " "there's not much reason to bother. When opening a file for reading or " "writing, you can usually just provide the Unicode string as the filename, " "and it will be automatically converted to the right encoding for you::" msgstr "" #: ../Doc/howto/unicode.rst:595 msgid "" "Functions in the :mod:`os` module such as :func:`os.stat` will also accept " "Unicode filenames." msgstr "" #: ../Doc/howto/unicode.rst:598 msgid "" "The :func:`os.listdir` function returns filenames and raises an issue: " "should it return the Unicode version of filenames, or should it return bytes " "containing the encoded versions? :func:`os.listdir` will do both, depending " "on whether you provided the directory path as bytes or a Unicode string. If " "you pass a Unicode string as the path, filenames will be decoded using the " "filesystem's encoding and a list of Unicode strings will be returned, while " "passing a byte path will return the filenames as bytes. For example, " "assuming the default filesystem encoding is UTF-8, running the following " "program::" msgstr "" #: ../Doc/howto/unicode.rst:616 msgid "will produce the following output:" msgstr "" #: ../Doc/howto/unicode.rst:624 msgid "" "The first list contains UTF-8-encoded filenames, and the second list " "contains the Unicode versions." msgstr "" #: ../Doc/howto/unicode.rst:627 msgid "" "Note that on most occasions, the Unicode APIs should be used. The bytes " "APIs should only be used on systems where undecodable file names can be " "present, i.e. Unix systems." msgstr "" #: ../Doc/howto/unicode.rst:633 msgid "Tips for Writing Unicode-aware Programs" msgstr "" #: ../Doc/howto/unicode.rst:635 msgid "" "This section provides some suggestions on writing software that deals with " "Unicode." msgstr "" #: ../Doc/howto/unicode.rst:638 msgid "The most important tip is:" msgstr "" #: ../Doc/howto/unicode.rst:640 msgid "" "Software should only work with Unicode strings internally, decoding the " "input data as soon as possible and encoding the output only at the end." msgstr "" #: ../Doc/howto/unicode.rst:643 msgid "" "If you attempt to write processing functions that accept both Unicode and " "byte strings, you will find your program vulnerable to bugs wherever you " "combine the two different kinds of strings. There is no automatic encoding " "or decoding: if you do e.g. ``str + bytes``, a :exc:`TypeError` will be " "raised." msgstr "" #: ../Doc/howto/unicode.rst:648 msgid "" "When using data coming from a web browser or some other untrusted source, a " "common technique is to check for illegal characters in a string before using " "the string in a generated command line or storing it in a database. If " "you're doing this, be careful to check the decoded string, not the encoded " "bytes data; some encodings may have interesting properties, such as not " "being bijective or not being fully ASCII-compatible. This is especially " "true if the input data also specifies the encoding, since the attacker can " "then choose a clever way to hide malicious text in the encoded bytestream." msgstr "" #: ../Doc/howto/unicode.rst:659 msgid "Converting Between File Encodings" msgstr "" #: ../Doc/howto/unicode.rst:661 msgid "" "The :class:`~codecs.StreamRecoder` class can transparently convert between " "encodings, taking a stream that returns data in encoding #1 and behaving " "like a stream returning data in encoding #2." msgstr "" #: ../Doc/howto/unicode.rst:665 msgid "" "For example, if you have an input file *f* that's in Latin-1, you can wrap " "it with a :class:`~codecs.StreamRecoder` to return bytes encoded in UTF-8::" msgstr "" #: ../Doc/howto/unicode.rst:679 msgid "Files in an Unknown Encoding" msgstr "" #: ../Doc/howto/unicode.rst:681 msgid "" "What can you do if you need to make a change to a file, but don't know the " "file's encoding? If you know the encoding is ASCII-compatible and only want " "to examine or modify the ASCII parts, you can open the file with the " "``surrogateescape`` error handler::" msgstr "" #: ../Doc/howto/unicode.rst:695 msgid "" "The ``surrogateescape`` error handler will decode any non-ASCII bytes as " "code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. " "These private code points will then be turned back into the same bytes when " "the ``surrogateescape`` error handler is used when encoding the data and " "writing it back out." msgstr "" #: ../Doc/howto/unicode.rst:705 msgid "" "One section of `Mastering Python 3 Input/Output `_, a PyCon 2010 talk by David " "Beazley, discusses text processing and binary data handling." msgstr "" #: ../Doc/howto/unicode.rst:709 msgid "" "The `PDF slides for Marc-André Lemburg's presentation \"Writing Unicode-" "aware Applications in Python\" `_ discuss questions of " "character encodings as well as how to internationalize and localize an " "application. These slides cover Python 2.x only." msgstr "" #: ../Doc/howto/unicode.rst:715 msgid "" "`The Guts of Unicode in Python `_ is a PyCon 2013 talk by Benjamin Peterson that " "discusses the internal Unicode representation in Python 3.3." msgstr "" #: ../Doc/howto/unicode.rst:722 msgid "Acknowledgements" msgstr "" #: ../Doc/howto/unicode.rst:724 msgid "" "The initial draft of this document was written by Andrew Kuchling. It has " "since been revised further by Alexander Belopolsky, Georg Brandl, Andrew " "Kuchling, and Ezio Melotti." msgstr "" #: ../Doc/howto/unicode.rst:728 msgid "" "Thanks to the following people who have noted errors or offered suggestions " "on this article: Éric Araujo, Nicholas Bastin, Nick Coghlan, Marius " "Gedminas, Kent Johnson, Ken Krugler, Marc-André Lemburg, Martin von Löwis, " "Terry J. Reedy, Chad Whitacre." msgstr "" #: ../Doc/howto/urllib2.rst:5 msgid "HOWTO Fetch Internet Resources Using The urllib Package" msgstr "" #: ../Doc/howto/urllib2.rst:7 msgid "`Michael Foord `_" msgstr "" #: ../Doc/howto/urllib2.rst:11 msgid "" "There is a French translation of an earlier revision of this HOWTO, " "available at `urllib2 - Le Manuel manquant `_." msgstr "" #: ../Doc/howto/urllib2.rst:0 msgid "Related Articles" msgstr "" #: ../Doc/howto/urllib2.rst:22 msgid "" "You may also find useful the following article on fetching web resources " "with Python:" msgstr "" #: ../Doc/howto/urllib2.rst:25 msgid "" "`Basic Authentication `_" msgstr "" #: ../Doc/howto/urllib2.rst:27 msgid "A tutorial on *Basic Authentication*, with examples in Python." msgstr "" #: ../Doc/howto/urllib2.rst:29 msgid "" "**urllib.request** is a Python module for fetching URLs (Uniform Resource " "Locators). It offers a very simple interface, in the form of the *urlopen* " "function. This is capable of fetching URLs using a variety of different " "protocols. It also offers a slightly more complex interface for handling " "common situations - like basic authentication, cookies, proxies and so on. " "These are provided by objects called handlers and openers." msgstr "" #: ../Doc/howto/urllib2.rst:36 msgid "" "urllib.request supports fetching URLs for many \"URL schemes\" (identified " "by the string before the \":\" in URL - for example \"ftp\" is the URL " "scheme of \"ftp://python.org/\") using their associated network protocols (e." "g. FTP, HTTP). This tutorial focuses on the most common case, HTTP." msgstr "" #: ../Doc/howto/urllib2.rst:41 msgid "" "For straightforward situations *urlopen* is very easy to use. But as soon as " "you encounter errors or non-trivial cases when opening HTTP URLs, you will " "need some understanding of the HyperText Transfer Protocol. The most " "comprehensive and authoritative reference to HTTP is :rfc:`2616`. This is a " "technical document and not intended to be easy to read. This HOWTO aims to " "illustrate using *urllib*, with enough detail about HTTP to help you " "through. It is not intended to replace the :mod:`urllib.request` docs, but " "is supplementary to them." msgstr "" #: ../Doc/howto/urllib2.rst:51 msgid "Fetching URLs" msgstr "" #: ../Doc/howto/urllib2.rst:53 msgid "The simplest way to use urllib.request is as follows::" msgstr "" #: ../Doc/howto/urllib2.rst:59 msgid "" "If you wish to retrieve a resource via URL and store it in a temporary " "location, you can do so via the :func:`~urllib.request.urlretrieve` " "function::" msgstr "" #: ../Doc/howto/urllib2.rst:66 msgid "" "Many uses of urllib will be that simple (note that instead of an 'http:' URL " "we could have used a URL starting with 'ftp:', 'file:', etc.). However, " "it's the purpose of this tutorial to explain the more complicated cases, " "concentrating on HTTP." msgstr "" #: ../Doc/howto/urllib2.rst:71 msgid "" "HTTP is based on requests and responses - the client makes requests and " "servers send responses. urllib.request mirrors this with a ``Request`` " "object which represents the HTTP request you are making. In its simplest " "form you create a Request object that specifies the URL you want to fetch. " "Calling ``urlopen`` with this Request object returns a response object for " "the URL requested. This response is a file-like object, which means you can " "for example call ``.read()`` on the response::" msgstr "" #: ../Doc/howto/urllib2.rst:85 msgid "" "Note that urllib.request makes use of the same Request interface to handle " "all URL schemes. For example, you can make an FTP request like so::" msgstr "" #: ../Doc/howto/urllib2.rst:90 msgid "" "In the case of HTTP, there are two extra things that Request objects allow " "you to do: First, you can pass data to be sent to the server. Second, you " "can pass extra information (\"metadata\") *about* the data or the about " "request itself, to the server - this information is sent as HTTP \"headers" "\". Let's look at each of these in turn." msgstr "" #: ../Doc/howto/urllib2.rst:97 msgid "Data" msgstr "" #: ../Doc/howto/urllib2.rst:99 msgid "" "Sometimes you want to send data to a URL (often the URL will refer to a CGI " "(Common Gateway Interface) script or other web application). With HTTP, this " "is often done using what's known as a **POST** request. This is often what " "your browser does when you submit a HTML form that you filled in on the web. " "Not all POSTs have to come from forms: you can use a POST to transmit " "arbitrary data to your own application. In the common case of HTML forms, " "the data needs to be encoded in a standard way, and then passed to the " "Request object as the ``data`` argument. The encoding is done using a " "function from the :mod:`urllib.parse` library. ::" msgstr "" #: ../Doc/howto/urllib2.rst:123 msgid "" "Note that other encodings are sometimes required (e.g. for file upload from " "HTML forms - see `HTML Specification, Form Submission `_ for more details)." msgstr "" #: ../Doc/howto/urllib2.rst:128 msgid "" "If you do not pass the ``data`` argument, urllib uses a **GET** request. One " "way in which GET and POST requests differ is that POST requests often have " "\"side-effects\": they change the state of the system in some way (for " "example by placing an order with the website for a hundredweight of tinned " "spam to be delivered to your door). Though the HTTP standard makes it clear " "that POSTs are intended to *always* cause side-effects, and GET requests " "*never* to cause side-effects, nothing prevents a GET request from having " "side-effects, nor a POST requests from having no side-effects. Data can also " "be passed in an HTTP GET request by encoding it in the URL itself." msgstr "" #: ../Doc/howto/urllib2.rst:138 msgid "This is done as follows::" msgstr "" #: ../Doc/howto/urllib2.rst:153 msgid "" "Notice that the full URL is created by adding a ``?`` to the URL, followed " "by the encoded values." msgstr "" #: ../Doc/howto/urllib2.rst:157 msgid "Headers" msgstr "" #: ../Doc/howto/urllib2.rst:159 msgid "" "We'll discuss here one particular HTTP header, to illustrate how to add " "headers to your HTTP request." msgstr "" #: ../Doc/howto/urllib2.rst:162 msgid "" "Some websites [#]_ dislike being browsed by programs, or send different " "versions to different browsers [#]_. By default urllib identifies itself as " "``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version " "numbers of the Python release, e.g. ``Python-urllib/2.5``), which may " "confuse the site, or just plain not work. The way a browser identifies " "itself is through the ``User-Agent`` header [#]_. When you create a Request " "object you can pass a dictionary of headers in. The following example makes " "the same request as above, but identifies itself as a version of Internet " "Explorer [#]_. ::" msgstr "" #: ../Doc/howto/urllib2.rst:189 msgid "" "The response also has two useful methods. See the section on `info and " "geturl`_ which comes after we have a look at what happens when things go " "wrong." msgstr "" #: ../Doc/howto/urllib2.rst:194 msgid "Handling Exceptions" msgstr "Gestion des exceptions" #: ../Doc/howto/urllib2.rst:196 msgid "" "*urlopen* raises :exc:`URLError` when it cannot handle a response (though as " "usual with Python APIs, built-in exceptions such as :exc:`ValueError`, :exc:" "`TypeError` etc. may also be raised)." msgstr "" #: ../Doc/howto/urllib2.rst:200 msgid "" ":exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific " "case of HTTP URLs." msgstr "" #: ../Doc/howto/urllib2.rst:203 msgid "The exception classes are exported from the :mod:`urllib.error` module." msgstr "" #: ../Doc/howto/urllib2.rst:206 msgid "URLError" msgstr "" #: ../Doc/howto/urllib2.rst:208 msgid "" "Often, URLError is raised because there is no network connection (no route " "to the specified server), or the specified server doesn't exist. In this " "case, the exception raised will have a 'reason' attribute, which is a tuple " "containing an error code and a text error message." msgstr "" #: ../Doc/howto/urllib2.rst:213 ../Doc/howto/urllib2.rst:460 msgid "e.g. ::" msgstr "" #: ../Doc/howto/urllib2.rst:224 msgid "HTTPError" msgstr "" #: ../Doc/howto/urllib2.rst:226 msgid "" "Every HTTP response from the server contains a numeric \"status code\". " "Sometimes the status code indicates that the server is unable to fulfil the " "request. The default handlers will handle some of these responses for you " "(for example, if the response is a \"redirection\" that requests the client " "fetch the document from a different URL, urllib will handle that for you). " "For those it can't handle, urlopen will raise an :exc:`HTTPError`. Typical " "errors include '404' (page not found), '403' (request forbidden), and " "'401' (authentication required)." msgstr "" #: ../Doc/howto/urllib2.rst:234 msgid "See section 10 of RFC 2616 for a reference on all the HTTP error codes." msgstr "" #: ../Doc/howto/urllib2.rst:236 msgid "" "The :exc:`HTTPError` instance raised will have an integer 'code' attribute, " "which corresponds to the error sent by the server." msgstr "" #: ../Doc/howto/urllib2.rst:240 msgid "Error Codes" msgstr "" #: ../Doc/howto/urllib2.rst:242 msgid "" "Because the default handlers handle redirects (codes in the 300 range), and " "codes in the 100-299 range indicate success, you will usually only see error " "codes in the 400-599 range." msgstr "" #: ../Doc/howto/urllib2.rst:246 msgid "" ":attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary " "of response codes in that shows all the response codes used by RFC 2616. The " "dictionary is reproduced here for convenience ::" msgstr "" #: ../Doc/howto/urllib2.rst:318 msgid "" "When an error is raised the server responds by returning an HTTP error code " "*and* an error page. You can use the :exc:`HTTPError` instance as a response " "on the page returned. This means that as well as the code attribute, it also " "has read, geturl, and info, methods as returned by the ``urllib.response`` " "module::" msgstr "" #: ../Doc/howto/urllib2.rst:338 msgid "Wrapping it Up" msgstr "" #: ../Doc/howto/urllib2.rst:340 msgid "" "So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` " "there are two basic approaches. I prefer the second approach." msgstr "" #: ../Doc/howto/urllib2.rst:344 msgid "Number 1" msgstr "" #: ../Doc/howto/urllib2.rst:366 msgid "" "The ``except HTTPError`` *must* come first, otherwise ``except URLError`` " "will *also* catch an :exc:`HTTPError`." msgstr "" #: ../Doc/howto/urllib2.rst:370 msgid "Number 2" msgstr "" #: ../Doc/howto/urllib2.rst:391 msgid "info and geturl" msgstr "" #: ../Doc/howto/urllib2.rst:393 msgid "" "The response returned by urlopen (or the :exc:`HTTPError` instance) has two " "useful methods :meth:`info` and :meth:`geturl` and is defined in the module :" "mod:`urllib.response`.." msgstr "" #: ../Doc/howto/urllib2.rst:397 msgid "" "**geturl** - this returns the real URL of the page fetched. This is useful " "because ``urlopen`` (or the opener object used) may have followed a " "redirect. The URL of the page fetched may not be the same as the URL " "requested." msgstr "" #: ../Doc/howto/urllib2.rst:401 msgid "" "**info** - this returns a dictionary-like object that describes the page " "fetched, particularly the headers sent by the server. It is currently an :" "class:`http.client.HTTPMessage` instance." msgstr "" #: ../Doc/howto/urllib2.rst:405 msgid "" "Typical headers include 'Content-length', 'Content-type', and so on. See the " "`Quick Reference to HTTP Headers `_ for a useful listing of HTTP headers with brief explanations of " "their meaning and use." msgstr "" #: ../Doc/howto/urllib2.rst:412 msgid "Openers and Handlers" msgstr "" #: ../Doc/howto/urllib2.rst:414 msgid "" "When you fetch a URL you use an opener (an instance of the perhaps " "confusingly-named :class:`urllib.request.OpenerDirector`). Normally we have " "been using the default opener - via ``urlopen`` - but you can create custom " "openers. Openers use handlers. All the \"heavy lifting\" is done by the " "handlers. Each handler knows how to open URLs for a particular URL scheme " "(http, ftp, etc.), or how to handle an aspect of URL opening, for example " "HTTP redirections or HTTP cookies." msgstr "" #: ../Doc/howto/urllib2.rst:422 msgid "" "You will want to create openers if you want to fetch URLs with specific " "handlers installed, for example to get an opener that handles cookies, or to " "get an opener that does not handle redirections." msgstr "" #: ../Doc/howto/urllib2.rst:426 msgid "" "To create an opener, instantiate an ``OpenerDirector``, and then call ``." "add_handler(some_handler_instance)`` repeatedly." msgstr "" #: ../Doc/howto/urllib2.rst:429 msgid "" "Alternatively, you can use ``build_opener``, which is a convenience function " "for creating opener objects with a single function call. ``build_opener`` " "adds several handlers by default, but provides a quick way to add more and/" "or override the default handlers." msgstr "" #: ../Doc/howto/urllib2.rst:434 msgid "" "Other sorts of handlers you might want to can handle proxies, " "authentication, and other common but slightly specialised situations." msgstr "" #: ../Doc/howto/urllib2.rst:437 msgid "" "``install_opener`` can be used to make an ``opener`` object the (global) " "default opener. This means that calls to ``urlopen`` will use the opener you " "have installed." msgstr "" #: ../Doc/howto/urllib2.rst:441 msgid "" "Opener objects have an ``open`` method, which can be called directly to " "fetch urls in the same way as the ``urlopen`` function: there's no need to " "call ``install_opener``, except as a convenience." msgstr "" #: ../Doc/howto/urllib2.rst:447 msgid "Basic Authentication" msgstr "" #: ../Doc/howto/urllib2.rst:449 msgid "" "To illustrate creating and installing a handler we will use the " "``HTTPBasicAuthHandler``. For a more detailed discussion of this subject -- " "including an explanation of how Basic Authentication works - see the `Basic " "Authentication Tutorial `_." msgstr "" #: ../Doc/howto/urllib2.rst:455 msgid "" "When authentication is required, the server sends a header (as well as the " "401 error code) requesting authentication. This specifies the " "authentication scheme and a 'realm'. The header looks like: ``WWW-" "Authenticate: SCHEME realm=\"REALM\"``." msgstr "" #: ../Doc/howto/urllib2.rst:465 msgid "" "The client should then retry the request with the appropriate name and " "password for the realm included as a header in the request. This is 'basic " "authentication'. In order to simplify this process we can create an instance " "of ``HTTPBasicAuthHandler`` and an opener to use this handler." msgstr "" #: ../Doc/howto/urllib2.rst:470 msgid "" "The ``HTTPBasicAuthHandler`` uses an object called a password manager to " "handle the mapping of URLs and realms to passwords and usernames. If you " "know what the realm is (from the authentication header sent by the server), " "then you can use a ``HTTPPasswordMgr``. Frequently one doesn't care what the " "realm is. In that case, it is convenient to use " "``HTTPPasswordMgrWithDefaultRealm``. This allows you to specify a default " "username and password for a URL. This will be supplied in the absence of you " "providing an alternative combination for a specific realm. We indicate this " "by providing ``None`` as the realm argument to the ``add_password`` method." msgstr "" #: ../Doc/howto/urllib2.rst:480 msgid "" "The top-level URL is the first URL that requires authentication. URLs " "\"deeper\" than the URL you pass to .add_password() will also match. ::" msgstr "" #: ../Doc/howto/urllib2.rst:505 msgid "" "In the above example we only supplied our ``HTTPBasicAuthHandler`` to " "``build_opener``. By default openers have the handlers for normal situations " "-- ``ProxyHandler`` (if a proxy setting such as an :envvar:`http_proxy` " "environment variable is set), ``UnknownHandler``, ``HTTPHandler``, " "``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``, " "``FileHandler``, ``DataHandler``, ``HTTPErrorProcessor``." msgstr "" #: ../Doc/howto/urllib2.rst:512 msgid "" "``top_level_url`` is in fact *either* a full URL (including the 'http:' " "scheme component and the hostname and optionally the port number) e.g. " "\"http://example.com/\" *or* an \"authority\" (i.e. the hostname, optionally " "including the port number) e.g. \"example.com\" or \"example.com:8080\" (the " "latter example includes a port number). The authority, if present, must NOT " "contain the \"userinfo\" component - for example \"joe:password@example.com" "\" is not correct." msgstr "" #: ../Doc/howto/urllib2.rst:522 msgid "Proxies" msgstr "" #: ../Doc/howto/urllib2.rst:524 msgid "" "**urllib** will auto-detect your proxy settings and use those. This is " "through the ``ProxyHandler``, which is part of the normal handler chain when " "a proxy setting is detected. Normally that's a good thing, but there are " "occasions when it may not be helpful [#]_. One way to do this is to setup " "our own ``ProxyHandler``, with no proxies defined. This is done using " "similar steps to setting up a `Basic Authentication`_ handler: ::" msgstr "" #: ../Doc/howto/urllib2.rst:537 msgid "" "Currently ``urllib.request`` *does not* support fetching of ``https`` " "locations through a proxy. However, this can be enabled by extending urllib." "request as shown in the recipe [#]_." msgstr "" #: ../Doc/howto/urllib2.rst:543 msgid "" "``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see " "the documentation on :func:`~urllib.request.getproxies`." msgstr "" #: ../Doc/howto/urllib2.rst:548 msgid "Sockets and Layers" msgstr "" #: ../Doc/howto/urllib2.rst:550 msgid "" "The Python support for fetching resources from the web is layered. urllib " "uses the :mod:`http.client` library, which in turn uses the socket library." msgstr "" #: ../Doc/howto/urllib2.rst:553 msgid "" "As of Python 2.3 you can specify how long a socket should wait for a " "response before timing out. This can be useful in applications which have to " "fetch web pages. By default the socket module has *no timeout* and can hang. " "Currently, the socket timeout is not exposed at the http.client or urllib." "request levels. However, you can set the default timeout globally for all " "sockets using ::" msgstr "" #: ../Doc/howto/urllib2.rst:576 msgid "Footnotes" msgstr "Notes" #: ../Doc/howto/urllib2.rst:578 msgid "This document was reviewed and revised by John Lee." msgstr "" #: ../Doc/howto/urllib2.rst:580 msgid "Google for example." msgstr "" #: ../Doc/howto/urllib2.rst:581 msgid "" "Browser sniffing is a very bad practise for website design - building sites " "using web standards is much more sensible. Unfortunately a lot of sites " "still send different versions to different browsers." msgstr "" #: ../Doc/howto/urllib2.rst:584 msgid "" "The user agent for MSIE 6 is *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT " "5.1; SV1; .NET CLR 1.1.4322)'*" msgstr "" #: ../Doc/howto/urllib2.rst:586 msgid "" "For details of more HTTP request headers, see `Quick Reference to HTTP " "Headers`_." msgstr "" #: ../Doc/howto/urllib2.rst:588 msgid "" "In my case I have to use a proxy to access the internet at work. If you " "attempt to fetch *localhost* URLs through this proxy it blocks them. IE is " "set to use the proxy, which urllib picks up on. In order to test scripts " "with a localhost server, I have to prevent urllib from using the proxy." msgstr "" #: ../Doc/howto/urllib2.rst:593 msgid "" "urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe `_." msgstr ""