diff --git "a/example/codeql-db/db-python/default/pools/0/pageDump/page-000000002" "b/example/codeql-db/db-python/default/pools/0/pageDump/page-000000002" new file mode 100644--- /dev/null +++ "b/example/codeql-db/db-python/default/pools/0/pageDump/page-000000002" @@ -0,0 +1,28979 @@ +u'Return a list of all the message's header field names. + + These will be sorted in the order they appeared in the original + message, or were added to the message, and may contain duplicates. + Any fields deleted and re-inserted are always appended to the header + list. + 'b'Return a list of all the message's header values. + + These will be sorted in the order they appeared in the original + message, or were added to the message, and may contain duplicates. + Any fields deleted and re-inserted are always appended to the header + list. + 'u'Return a list of all the message's header values. + + These will be sorted in the order they appeared in the original + message, or were added to the message, and may contain duplicates. + Any fields deleted and re-inserted are always appended to the header + list. + 'b'Get all the message's header fields and values. + + These will be sorted in the order they appeared in the original + message, or were added to the message, and may contain duplicates. + Any fields deleted and re-inserted are always appended to the header + list. + 'u'Get all the message's header fields and values. + + These will be sorted in the order they appeared in the original + message, or were added to the message, and may contain duplicates. + Any fields deleted and re-inserted are always appended to the header + list. + 'b'Get a header value. + + Like __getitem__() but return failobj instead of None when the field + is missing. + 'u'Get a header value. + + Like __getitem__() but return failobj instead of None when the field + is missing. + 'b'Store name and value in the model without modification. + + This is an "internal" API, intended only for use by a parser. + 'u'Store name and value in the model without modification. + + This is an "internal" API, intended only for use by a parser. + 'b'Return the (name, value) header pairs without modification. + + This is an "internal" API, intended only for use by a generator. + 'u'Return the (name, value) header pairs without modification. + + This is an "internal" API, intended only for use by a generator. + 'b'Return a list of all the values for the named field. + + These will be sorted in the order they appeared in the original + message, and may contain duplicates. Any fields deleted and + re-inserted are always appended to the header list. + + If no such fields exist, failobj is returned (defaults to None). + 'u'Return a list of all the values for the named field. + + These will be sorted in the order they appeared in the original + message, and may contain duplicates. Any fields deleted and + re-inserted are always appended to the header list. + + If no such fields exist, failobj is returned (defaults to None). + 'b'Extended header setting. + + name is the header field to add. keyword arguments can be used to set + additional parameters for the header field, with underscores converted + to dashes. Normally the parameter will be added as key="value" unless + value is None, in which case only the key will be added. If a + parameter value contains non-ASCII characters it can be specified as a + three-tuple of (charset, language, value), in which case it will be + encoded according to RFC2231 rules. Otherwise it will be encoded using + the utf-8 charset and a language of ''. + + Examples: + + msg.add_header('content-disposition', 'attachment', filename='bud.gif') + msg.add_header('content-disposition', 'attachment', + filename=('utf-8', '', Fußballer.ppt')) + msg.add_header('content-disposition', 'attachment', + filename='Fußballer.ppt')) + 'u'Extended header setting. + + name is the header field to add. keyword arguments can be used to set + additional parameters for the header field, with underscores converted + to dashes. Normally the parameter will be added as key="value" unless + value is None, in which case only the key will be added. If a + parameter value contains non-ASCII characters it can be specified as a + three-tuple of (charset, language, value), in which case it will be + encoded according to RFC2231 rules. Otherwise it will be encoded using + the utf-8 charset and a language of ''. + + Examples: + + msg.add_header('content-disposition', 'attachment', filename='bud.gif') + msg.add_header('content-disposition', 'attachment', + filename=('utf-8', '', Fußballer.ppt')) + msg.add_header('content-disposition', 'attachment', + filename='Fußballer.ppt')) + 'b'Replace a header. + + Replace the first matching header found in the message, retaining + header order and case. If no matching header was found, a KeyError is + raised. + 'u'Replace a header. + + Replace the first matching header found in the message, retaining + header order and case. If no matching header was found, a KeyError is + raised. + 'b'Return the message's content type. + + The returned string is coerced to lower case of the form + `maintype/subtype'. If there was no Content-Type header in the + message, the default type as given by get_default_type() will be + returned. Since according to RFC 2045, messages always have a default + type this will always return a value. + + RFC 2045 defines a message's default type to be text/plain unless it + appears inside a multipart/digest container, in which case it would be + message/rfc822. + 'u'Return the message's content type. + + The returned string is coerced to lower case of the form + `maintype/subtype'. If there was no Content-Type header in the + message, the default type as given by get_default_type() will be + returned. Since according to RFC 2045, messages always have a default + type this will always return a value. + + RFC 2045 defines a message's default type to be text/plain unless it + appears inside a multipart/digest container, in which case it would be + message/rfc822. + 'b'Return the message's main content type. + + This is the `maintype' part of the string returned by + get_content_type(). + 'u'Return the message's main content type. + + This is the `maintype' part of the string returned by + get_content_type(). + 'b'Returns the message's sub-content type. + + This is the `subtype' part of the string returned by + get_content_type(). + 'u'Returns the message's sub-content type. + + This is the `subtype' part of the string returned by + get_content_type(). + 'b'Return the `default' content type. + + Most messages have a default content type of text/plain, except for + messages that are subparts of multipart/digest containers. Such + subparts have a default content type of message/rfc822. + 'u'Return the `default' content type. + + Most messages have a default content type of text/plain, except for + messages that are subparts of multipart/digest containers. Such + subparts have a default content type of message/rfc822. + 'b'Set the `default' content type. + + ctype should be either "text/plain" or "message/rfc822", although this + is not enforced. The default content type is not stored in the + Content-Type header. + 'u'Set the `default' content type. + + ctype should be either "text/plain" or "message/rfc822", although this + is not enforced. The default content type is not stored in the + Content-Type header. + 'b'Return the message's Content-Type parameters, as a list. + + The elements of the returned list are 2-tuples of key/value pairs, as + split on the `=' sign. The left hand side of the `=' is the key, + while the right hand side is the value. If there is no `=' sign in + the parameter the value is the empty string. The value is as + described in the get_param() method. + + Optional failobj is the object to return if there is no Content-Type + header. Optional header is the header to search instead of + Content-Type. If unquote is True, the value is unquoted. + 'u'Return the message's Content-Type parameters, as a list. + + The elements of the returned list are 2-tuples of key/value pairs, as + split on the `=' sign. The left hand side of the `=' is the key, + while the right hand side is the value. If there is no `=' sign in + the parameter the value is the empty string. The value is as + described in the get_param() method. + + Optional failobj is the object to return if there is no Content-Type + header. Optional header is the header to search instead of + Content-Type. If unquote is True, the value is unquoted. + 'b'Return the parameter value if found in the Content-Type header. + + Optional failobj is the object to return if there is no Content-Type + header, or the Content-Type header has no such parameter. Optional + header is the header to search instead of Content-Type. + + Parameter keys are always compared case insensitively. The return + value can either be a string, or a 3-tuple if the parameter was RFC + 2231 encoded. When it's a 3-tuple, the elements of the value are of + the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and + LANGUAGE can be None, in which case you should consider VALUE to be + encoded in the us-ascii charset. You can usually ignore LANGUAGE. + The parameter value (either the returned string, or the VALUE item in + the 3-tuple) is always unquoted, unless unquote is set to False. + + If your application doesn't care whether the parameter was RFC 2231 + encoded, it can turn the return value into a string as follows: + + rawparam = msg.get_param('foo') + param = email.utils.collapse_rfc2231_value(rawparam) + + 'u'Return the parameter value if found in the Content-Type header. + + Optional failobj is the object to return if there is no Content-Type + header, or the Content-Type header has no such parameter. Optional + header is the header to search instead of Content-Type. + + Parameter keys are always compared case insensitively. The return + value can either be a string, or a 3-tuple if the parameter was RFC + 2231 encoded. When it's a 3-tuple, the elements of the value are of + the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and + LANGUAGE can be None, in which case you should consider VALUE to be + encoded in the us-ascii charset. You can usually ignore LANGUAGE. + The parameter value (either the returned string, or the VALUE item in + the 3-tuple) is always unquoted, unless unquote is set to False. + + If your application doesn't care whether the parameter was RFC 2231 + encoded, it can turn the return value into a string as follows: + + rawparam = msg.get_param('foo') + param = email.utils.collapse_rfc2231_value(rawparam) + + 'b'Set a parameter in the Content-Type header. + + If the parameter already exists in the header, its value will be + replaced with the new value. + + If header is Content-Type and has not yet been defined for this + message, it will be set to "text/plain" and the new parameter and + value will be appended as per RFC 2045. + + An alternate header can be specified in the header argument, and all + parameters will be quoted as necessary unless requote is False. + + If charset is specified, the parameter will be encoded according to RFC + 2231. Optional language specifies the RFC 2231 language, defaulting + to the empty string. Both charset and language should be strings. + 'u'Set a parameter in the Content-Type header. + + If the parameter already exists in the header, its value will be + replaced with the new value. + + If header is Content-Type and has not yet been defined for this + message, it will be set to "text/plain" and the new parameter and + value will be appended as per RFC 2045. + + An alternate header can be specified in the header argument, and all + parameters will be quoted as necessary unless requote is False. + + If charset is specified, the parameter will be encoded according to RFC + 2231. Optional language specifies the RFC 2231 language, defaulting + to the empty string. Both charset and language should be strings. + 'b'Remove the given parameter completely from the Content-Type header. + + The header will be re-written in place without the parameter or its + value. All values will be quoted as necessary unless requote is + False. Optional header specifies an alternative to the Content-Type + header. + 'u'Remove the given parameter completely from the Content-Type header. + + The header will be re-written in place without the parameter or its + value. All values will be quoted as necessary unless requote is + False. Optional header specifies an alternative to the Content-Type + header. + 'b'Set the main type and subtype for the Content-Type header. + + type must be a string in the form "maintype/subtype", otherwise a + ValueError is raised. + + This method replaces the Content-Type header, keeping all the + parameters in place. If requote is False, this leaves the existing + header's quoting as is. Otherwise, the parameters will be quoted (the + default). + + An alternative header can be specified in the header argument. When + the Content-Type header is set, we'll always also add a MIME-Version + header. + 'u'Set the main type and subtype for the Content-Type header. + + type must be a string in the form "maintype/subtype", otherwise a + ValueError is raised. + + This method replaces the Content-Type header, keeping all the + parameters in place. If requote is False, this leaves the existing + header's quoting as is. Otherwise, the parameters will be quoted (the + default). + + An alternative header can be specified in the header argument. When + the Content-Type header is set, we'll always also add a MIME-Version + header. + 'b'mime-version'u'mime-version'b'Return the filename associated with the payload if present. + + The filename is extracted from the Content-Disposition header's + `filename' parameter, and it is unquoted. If that header is missing + the `filename' parameter, this method falls back to looking for the + `name' parameter. + 'u'Return the filename associated with the payload if present. + + The filename is extracted from the Content-Disposition header's + `filename' parameter, and it is unquoted. If that header is missing + the `filename' parameter, this method falls back to looking for the + `name' parameter. + 'b'content-disposition'u'content-disposition'b'Return the boundary associated with the payload if present. + + The boundary is extracted from the Content-Type header's `boundary' + parameter, and it is unquoted. + 'u'Return the boundary associated with the payload if present. + + The boundary is extracted from the Content-Type header's `boundary' + parameter, and it is unquoted. + 'b'boundary'u'boundary'b'Set the boundary parameter in Content-Type to 'boundary'. + + This is subtly different than deleting the Content-Type header and + adding a new one with a new boundary parameter via add_header(). The + main difference is that using the set_boundary() method preserves the + order of the Content-Type header in the original message. + + HeaderParseError is raised if the message has no Content-Type header. + 'u'Set the boundary parameter in Content-Type to 'boundary'. + + This is subtly different than deleting the Content-Type header and + adding a new one with a new boundary parameter via add_header(). The + main difference is that using the set_boundary() method preserves the + order of the Content-Type header in the original message. + + HeaderParseError is raised if the message has no Content-Type header. + 'b'No Content-Type header found'u'No Content-Type header found'b'Return the charset parameter of the Content-Type header. + + The returned string is always coerced to lower case. If there is no + Content-Type header, or if that header has no charset parameter, + failobj is returned. + 'u'Return the charset parameter of the Content-Type header. + + The returned string is always coerced to lower case. If there is no + Content-Type header, or if that header has no charset parameter, + failobj is returned. + 'b'Return a list containing the charset(s) used in this message. + + The returned list of items describes the Content-Type headers' + charset parameter for this message and all the subparts in its + payload. + + Each item will either be a string (the value of the charset parameter + in the Content-Type header of that part) or the value of the + 'failobj' parameter (defaults to None), if the part does not have a + main MIME type of "text", or the charset is not defined. + + The list will contain one string for each part of the message, plus + one for the container message (i.e. self), so that a non-multipart + message will still return a list of length 1. + 'u'Return a list containing the charset(s) used in this message. + + The returned list of items describes the Content-Type headers' + charset parameter for this message and all the subparts in its + payload. + + Each item will either be a string (the value of the charset parameter + in the Content-Type header of that part) or the value of the + 'failobj' parameter (defaults to None), if the part does not have a + main MIME type of "text", or the charset is not defined. + + The list will contain one string for each part of the message, plus + one for the container message (i.e. self), so that a non-multipart + message will still return a list of length 1. + 'b'Return the message's content-disposition if it exists, or None. + + The return values can be either 'inline', 'attachment' or None + according to the rfc2183. + 'u'Return the message's content-disposition if it exists, or None. + + The return values can be either 'inline', 'attachment' or None + according to the rfc2183. + 'b'Return the entire formatted message as a string. + + Optional 'unixfrom', when true, means include the Unix From_ envelope + header. maxheaderlen is retained for backward compatibility with the + base Message class, but defaults to None, meaning that the policy value + for max_line_length controls the header maximum length. 'policy' is + passed to the Generator instance used to serialize the message; if it + is not specified the policy associated with the message instance is + used. + 'u'Return the entire formatted message as a string. + + Optional 'unixfrom', when true, means include the Unix From_ envelope + header. maxheaderlen is retained for backward compatibility with the + base Message class, but defaults to None, meaning that the policy value + for max_line_length controls the header maximum length. 'policy' is + passed to the Generator instance used to serialize the message; if it + is not specified the policy associated with the message instance is + used. + 'b'attachment'u'attachment'b'related'u'related'b'content-id'u'content-id'b'plain'u'plain'b'Return best candidate mime part for display as 'body' of message. + + Do a depth first search, starting with self, looking for the first part + matching each of the items in preferencelist, and return the part + corresponding to the first item that has a match, or None if no items + have a match. If 'related' is not included in preferencelist, consider + the root part of any multipart/related encountered as a candidate + match. Ignore parts with 'Content-Disposition: attachment'. + 'u'Return best candidate mime part for display as 'body' of message. + + Do a depth first search, starting with self, looking for the first part + matching each of the items in preferencelist, and return the part + corresponding to the first item that has a match, or None if no items + have a match. If 'related' is not included in preferencelist, consider + the root part of any multipart/related encountered as a candidate + match. Ignore parts with 'Content-Disposition: attachment'. + 'b'alternative'u'alternative'b'Return an iterator over the non-main parts of a multipart. + + Skip the first of each occurrence of text/plain, text/html, + multipart/related, or multipart/alternative in the multipart (unless + they have a 'Content-Disposition: attachment' header) and include all + remaining subparts in the returned iterator. When applied to a + multipart/related, return all parts except the root part. Return an + empty iterator when applied to a multipart/alternative or a + non-multipart. + 'u'Return an iterator over the non-main parts of a multipart. + + Skip the first of each occurrence of text/plain, text/html, + multipart/related, or multipart/alternative in the multipart (unless + they have a 'Content-Disposition: attachment' header) and include all + remaining subparts in the returned iterator. When applied to a + multipart/related, return all parts except the root part. Return an + empty iterator when applied to a multipart/alternative or a + non-multipart. + 'b'Return an iterator over all immediate subparts of a multipart. + + Return an empty iterator for a non-multipart. + 'u'Return an iterator over all immediate subparts of a multipart. + + Return an empty iterator for a non-multipart. + 'b'Cannot convert {} to {}'u'Cannot convert {} to {}'b'content-'u'content-'b'multipart/'u'multipart/'b'mixed'u'mixed'b'make_'u'make_'b'Content-Disposition'u'Content-Disposition'b'inline'u'inline'u'email.message'Guess the MIME type of a file. + +This module defines two useful functions: + +guess_type(url, strict=True) -- guess the MIME type and encoding of a URL. + +guess_extension(type, strict=True) -- guess the extension for a given MIME type. + +It also contains the following, for tuning the behavior: + +Data: + +knownfiles -- list of files to parse +inited -- flag set when init() has been called +suffix_map -- dictionary mapping suffixes to suffixes +encodings_map -- dictionary mapping suffixes to encodings +types_map -- dictionary mapping suffixes to types + +Functions: + +init([files]) -- parse a list of files, default knownfiles (on Windows, the + default values are taken from the registry) +read_mime_types(file) -- parse one file, return a dictionary or None +knownfilesinitedMimeTypesguess_typeguess_all_extensionsguess_extensionadd_typeread_mime_typessuffix_mapencodings_maptypes_mapcommon_types/etc/mime.types/etc/httpd/mime.types/etc/httpd/conf/mime.types/etc/apache/mime.types/etc/apache2/mime.types/usr/local/etc/httpd/conf/mime.types/usr/local/lib/netscape/mime.types/usr/local/etc/mime.types_dbMIME-types datastore. + + This datastore can handle information from mime.types-style files + and supports basic determination of MIME type from a filename or + URL, and can guess a reasonable extension given a MIME type. + _encodings_map_default_suffix_map_defaulttypes_map_inv_types_map_default_common_types_defaultAdd a mapping between a type and an extension. + + When the extension is already known, the new + type will replace the old one. When the type + is already known the extension will be added + to the list of known extensions. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + extsGuess the type of a file which is either a URL or a path-like object. + + Return value is a tuple (type, encoding) where type is None if + the type can't be guessed (no or unknown suffix) or a string + of the form type/subtype, usable for a MIME Content-type + header; and encoding is None for no encoding or the name of + the program used to encode (e.g. compress or gzip). The + mappings are table driven. Encoding suffixes are case + sensitive; type suffixes are first tried case sensitive, then + case insensitive. + + The suffixes .tgz, .taz and .tz (case sensitive!) are all + mapped to '.tar.gz'. (This is table-driven too, using the + dictionary suffix_map.) + + Optional `strict' argument when False adds a bunch of commonly found, + but non-standard types. + schemecommasemiGuess the extensions for a file based on its MIME type. + + Return value is a list of strings giving the possible filename + extensions, including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data stream, + but would be mapped to the MIME type `type' by guess_type(). + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + Guess the extension for a file based on its MIME type. + + Return value is a string giving a filename extension, + including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data + stream, but would be mapped to the MIME type `type' by + guess_type(). If no extension can be guessed for `type', None + is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + + Read a single mime.types-format file, specified by pathname. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + readfp + Read a single mime.types-format file. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + suffread_windows_registry + Load the MIME types database from Windows registry. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + enum_typesmimedbEnumKeyHKEY_CLASSES_ROOThkcrsubkeynamesubkeyQueryValueExContent TypemimetypedatatypeREG_SZGuess the type of a file based on its URL. + + Return value is a tuple (type, encoding) where type is None if the + type can't be guessed (no or unknown suffix) or a string of the + form type/subtype, usable for a MIME Content-type header; and + encoding is None for no encoding or the name of the program used + to encode (e.g. compress or gzip). The mappings are table + driven. Encoding suffixes are case sensitive; type suffixes are + first tried case sensitive, then case insensitive. + + The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped + to ".tar.gz". (This is table-driven too, using the dictionary + suffix_map). + + Optional `strict' argument when false adds a bunch of commonly found, but + non-standard types. + Guess the extensions for a file based on its MIME type. + + Return value is a list of strings giving the possible filename + extensions, including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data + stream, but would be mapped to the MIME type `type' by + guess_type(). If no extension can be guessed for `type', None + is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + Guess the extension for a file based on its MIME type. + + Return value is a string giving a filename extension, including the + leading dot ('.'). The extension is not guaranteed to have been + associated with any particular data stream, but would be mapped to the + MIME type `type' by guess_type(). If no extension can be guessed for + `type', None is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + Add a mapping between a type and an extension. + + When the extension is already known, the new + type will replace the old one. When the type + is already known the extension will be added + to the list of known extensions. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + db_default_mime_types.svg.gz.svgz.tar.gz.tgz.taz.tz.tar.bz2.tbz2.tar.xz.txz.Zbzip2.bz2xz.xzapplication/javascript.js.mjsapplication/json.jsonapplication/manifest+json.webmanifestapplication/msword.doc.dot.wizapplication/octet-stream.bin.dll.o.objapplication/oda.odaapplication/pdf.pdfapplication/pkcs7-mime.p7capplication/postscript.ps.ai.epsapplication/vnd.apple.mpegurl.m3u.m3u8application/vnd.ms-excel.xls.xlbapplication/vnd.ms-powerpoint.ppt.pot.ppa.pps.pwzapplication/wasm.wasmapplication/x-bcpio.bcpioapplication/x-cpio.cpioapplication/x-csh.cshapplication/x-dvi.dviapplication/x-gtar.gtarapplication/x-hdf.hdfapplication/x-hdf5.h5application/x-latex.latexapplication/x-mif.mifapplication/x-netcdf.cdf.ncapplication/x-pkcs12.p12.pfxapplication/x-pn-realaudio.ramapplication/x-python-code.pyoapplication/x-sh.shapplication/x-shar.sharapplication/x-shockwave-flash.swfapplication/x-sv4cpio.sv4cpioapplication/x-sv4crc.sv4crcapplication/x-tar.tarapplication/x-tcl.tclapplication/x-tex.texapplication/x-texinfo.texi.texinfoapplication/x-troff.roff.t.trapplication/x-troff-man.manapplication/x-troff-me.meapplication/x-troff-ms.msapplication/x-ustar.ustarapplication/x-wais-source.srcapplication/xml.xsl.rdf.wsdl.xpdlapplication/zip.zipaudio/basic.au.sndaudio/mpeg.mp3.mp2audio/x-aiff.aif.aifc.aiffaudio/x-pn-realaudio.raaudio/x-wav.wavimage/bmp.bmpimage/gif.gifimage/ief.iefimage/jpeg.jpg.jpe.jpegimage/png.pngimage/svg+xml.svgimage/tiff.tiff.tifimage/vnd.microsoft.icon.icoimage/x-cmu-raster.rasimage/x-ms-bmpimage/x-portable-anymap.pnmimage/x-portable-bitmap.pbmimage/x-portable-graymap.pgmimage/x-portable-pixmap.ppmimage/x-rgb.rgbimage/x-xbitmap.xbmimage/x-xpixmap.xpmimage/x-xwindowdump.xwd.eml.mht.mhtml.nwstext/css.csstext/csv.csvtext/html.html.htm.bat.h.ksh.pltext/richtext.rtxtext/tab-separated-values.tsvtext/x-pythontext/x-setext.etxtext/x-sgml.sgm.sgmltext/x-vcard.vcf.xmlvideo/mp4.mp4video/mpeg.mpeg.m1v.mpa.mpe.mpgvideo/quicktime.mov.qtvideo/webm.webmvideo/x-msvideo.avivideo/x-sgi-movie.movieapplication/rtf.rtfaudio/midi.midi.midimage/jpgimage/pict.pict.pct.pictext/xul.xulUsage: mimetypes.py [options] type + +Options: + --help / -h -- print this message and exit + --lenient / -l -- additionally search of some common, but non-standard + types. + --extension / -e -- guess extension instead of type + +More than one type argument may be given. +USAGEhlelenient-h--help--lenient--extensiongtypeguessI don't know anything about typetype:encoding:# Apache# Apache 1# Apache 2# Apache 1.2# Apache 1.3# dict for (non-strict, strict)# syntax of data URLs:# dataurl := "data:" [ mediatype ] [ ";base64" ] "," data# mediatype := [ type "/" subtype ] *( ";" parameter )# data := *urlchar# parameter := attribute "=" value# type/subtype defaults to "text/plain"# bad data URL# never compressed, so encoding is None# Windows only# Only check file extensions# raises OSError if no 'Content Type' value# so that MimeTypes.__init__() doesn't call us again# Make the DB a global variable now that it is fully initialized# Before adding new types, make sure they are either registered with IANA,# at http://www.iana.org/assignments/media-types# or extensions, i.e. using the x- prefix# If you add to these, please keep them sorted by mime type.# Make sure the entry with the preferred file extension for a particular mime type# appears before any others of the same mimetype.# These are non-standard types, commonly found in the wild. They will# only match if strict=0 flag is given to the API methods.# Please sort these toob'Guess the MIME type of a file. + +This module defines two useful functions: + +guess_type(url, strict=True) -- guess the MIME type and encoding of a URL. + +guess_extension(type, strict=True) -- guess the extension for a given MIME type. + +It also contains the following, for tuning the behavior: + +Data: + +knownfiles -- list of files to parse +inited -- flag set when init() has been called +suffix_map -- dictionary mapping suffixes to suffixes +encodings_map -- dictionary mapping suffixes to encodings +types_map -- dictionary mapping suffixes to types + +Functions: + +init([files]) -- parse a list of files, default knownfiles (on Windows, the + default values are taken from the registry) +read_mime_types(file) -- parse one file, return a dictionary or None +'u'Guess the MIME type of a file. + +This module defines two useful functions: + +guess_type(url, strict=True) -- guess the MIME type and encoding of a URL. + +guess_extension(type, strict=True) -- guess the extension for a given MIME type. + +It also contains the following, for tuning the behavior: + +Data: + +knownfiles -- list of files to parse +inited -- flag set when init() has been called +suffix_map -- dictionary mapping suffixes to suffixes +encodings_map -- dictionary mapping suffixes to encodings +types_map -- dictionary mapping suffixes to types + +Functions: + +init([files]) -- parse a list of files, default knownfiles (on Windows, the + default values are taken from the registry) +read_mime_types(file) -- parse one file, return a dictionary or None +'b'knownfiles'u'knownfiles'b'inited'u'inited'b'MimeTypes'u'MimeTypes'b'guess_type'u'guess_type'b'guess_all_extensions'u'guess_all_extensions'b'guess_extension'u'guess_extension'b'add_type'u'add_type'b'init'u'init'b'read_mime_types'u'read_mime_types'b'suffix_map'u'suffix_map'b'encodings_map'u'encodings_map'b'types_map'u'types_map'b'common_types'u'common_types'b'/etc/mime.types'u'/etc/mime.types'b'/etc/httpd/mime.types'u'/etc/httpd/mime.types'b'/etc/httpd/conf/mime.types'u'/etc/httpd/conf/mime.types'b'/etc/apache/mime.types'u'/etc/apache/mime.types'b'/etc/apache2/mime.types'u'/etc/apache2/mime.types'b'/usr/local/etc/httpd/conf/mime.types'u'/usr/local/etc/httpd/conf/mime.types'b'/usr/local/lib/netscape/mime.types'u'/usr/local/lib/netscape/mime.types'b'/usr/local/etc/mime.types'u'/usr/local/etc/mime.types'b'MIME-types datastore. + + This datastore can handle information from mime.types-style files + and supports basic determination of MIME type from a filename or + URL, and can guess a reasonable extension given a MIME type. + 'u'MIME-types datastore. + + This datastore can handle information from mime.types-style files + and supports basic determination of MIME type from a filename or + URL, and can guess a reasonable extension given a MIME type. + 'b'Add a mapping between a type and an extension. + + When the extension is already known, the new + type will replace the old one. When the type + is already known the extension will be added + to the list of known extensions. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'u'Add a mapping between a type and an extension. + + When the extension is already known, the new + type will replace the old one. When the type + is already known the extension will be added + to the list of known extensions. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'b'Guess the type of a file which is either a URL or a path-like object. + + Return value is a tuple (type, encoding) where type is None if + the type can't be guessed (no or unknown suffix) or a string + of the form type/subtype, usable for a MIME Content-type + header; and encoding is None for no encoding or the name of + the program used to encode (e.g. compress or gzip). The + mappings are table driven. Encoding suffixes are case + sensitive; type suffixes are first tried case sensitive, then + case insensitive. + + The suffixes .tgz, .taz and .tz (case sensitive!) are all + mapped to '.tar.gz'. (This is table-driven too, using the + dictionary suffix_map.) + + Optional `strict' argument when False adds a bunch of commonly found, + but non-standard types. + 'u'Guess the type of a file which is either a URL or a path-like object. + + Return value is a tuple (type, encoding) where type is None if + the type can't be guessed (no or unknown suffix) or a string + of the form type/subtype, usable for a MIME Content-type + header; and encoding is None for no encoding or the name of + the program used to encode (e.g. compress or gzip). The + mappings are table driven. Encoding suffixes are case + sensitive; type suffixes are first tried case sensitive, then + case insensitive. + + The suffixes .tgz, .taz and .tz (case sensitive!) are all + mapped to '.tar.gz'. (This is table-driven too, using the + dictionary suffix_map.) + + Optional `strict' argument when False adds a bunch of commonly found, + but non-standard types. + 'b'Guess the extensions for a file based on its MIME type. + + Return value is a list of strings giving the possible filename + extensions, including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data stream, + but would be mapped to the MIME type `type' by guess_type(). + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'u'Guess the extensions for a file based on its MIME type. + + Return value is a list of strings giving the possible filename + extensions, including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data stream, + but would be mapped to the MIME type `type' by guess_type(). + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'b'Guess the extension for a file based on its MIME type. + + Return value is a string giving a filename extension, + including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data + stream, but would be mapped to the MIME type `type' by + guess_type(). If no extension can be guessed for `type', None + is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'u'Guess the extension for a file based on its MIME type. + + Return value is a string giving a filename extension, + including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data + stream, but would be mapped to the MIME type `type' by + guess_type(). If no extension can be guessed for `type', None + is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'b' + Read a single mime.types-format file, specified by pathname. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'u' + Read a single mime.types-format file, specified by pathname. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'b' + Read a single mime.types-format file. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'u' + Read a single mime.types-format file. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'b' + Load the MIME types database from Windows registry. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'u' + Load the MIME types database from Windows registry. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'b'Content Type'u'Content Type'b'Guess the type of a file based on its URL. + + Return value is a tuple (type, encoding) where type is None if the + type can't be guessed (no or unknown suffix) or a string of the + form type/subtype, usable for a MIME Content-type header; and + encoding is None for no encoding or the name of the program used + to encode (e.g. compress or gzip). The mappings are table + driven. Encoding suffixes are case sensitive; type suffixes are + first tried case sensitive, then case insensitive. + + The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped + to ".tar.gz". (This is table-driven too, using the dictionary + suffix_map). + + Optional `strict' argument when false adds a bunch of commonly found, but + non-standard types. + 'u'Guess the type of a file based on its URL. + + Return value is a tuple (type, encoding) where type is None if the + type can't be guessed (no or unknown suffix) or a string of the + form type/subtype, usable for a MIME Content-type header; and + encoding is None for no encoding or the name of the program used + to encode (e.g. compress or gzip). The mappings are table + driven. Encoding suffixes are case sensitive; type suffixes are + first tried case sensitive, then case insensitive. + + The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped + to ".tar.gz". (This is table-driven too, using the dictionary + suffix_map). + + Optional `strict' argument when false adds a bunch of commonly found, but + non-standard types. + 'b'Guess the extensions for a file based on its MIME type. + + Return value is a list of strings giving the possible filename + extensions, including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data + stream, but would be mapped to the MIME type `type' by + guess_type(). If no extension can be guessed for `type', None + is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'u'Guess the extensions for a file based on its MIME type. + + Return value is a list of strings giving the possible filename + extensions, including the leading dot ('.'). The extension is not + guaranteed to have been associated with any particular data + stream, but would be mapped to the MIME type `type' by + guess_type(). If no extension can be guessed for `type', None + is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'b'Guess the extension for a file based on its MIME type. + + Return value is a string giving a filename extension, including the + leading dot ('.'). The extension is not guaranteed to have been + associated with any particular data stream, but would be mapped to the + MIME type `type' by guess_type(). If no extension can be guessed for + `type', None is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'u'Guess the extension for a file based on its MIME type. + + Return value is a string giving a filename extension, including the + leading dot ('.'). The extension is not guaranteed to have been + associated with any particular data stream, but would be mapped to the + MIME type `type' by guess_type(). If no extension can be guessed for + `type', None is returned. + + Optional `strict' argument when false adds a bunch of commonly found, + but non-standard types. + 'b'Add a mapping between a type and an extension. + + When the extension is already known, the new + type will replace the old one. When the type + is already known the extension will be added + to the list of known extensions. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'u'Add a mapping between a type and an extension. + + When the extension is already known, the new + type will replace the old one. When the type + is already known the extension will be added + to the list of known extensions. + + If strict is true, information will be added to + list of standard types, else to the list of non-standard + types. + 'b'.svg.gz'u'.svg.gz'b'.svgz'u'.svgz'b'.tar.gz'u'.tar.gz'b'.tgz'u'.tgz'b'.taz'u'.taz'b'.tz'u'.tz'b'.tar.bz2'u'.tar.bz2'b'.tbz2'u'.tbz2'b'.tar.xz'u'.tar.xz'b'.txz'u'.txz'b'.Z'u'.Z'b'bzip2'u'bzip2'b'.bz2'u'.bz2'b'xz'u'xz'b'.xz'u'.xz'b'application/javascript'u'application/javascript'b'.js'u'.js'b'.mjs'u'.mjs'b'application/json'u'application/json'b'.json'u'.json'b'application/manifest+json'u'application/manifest+json'b'.webmanifest'u'.webmanifest'b'application/msword'u'application/msword'b'.doc'u'.doc'b'.dot'u'.dot'b'.wiz'u'.wiz'b'application/octet-stream'u'application/octet-stream'b'.bin'u'.bin'b'.dll'u'.dll'b'.o'u'.o'b'.obj'u'.obj'b'application/oda'u'application/oda'b'.oda'u'.oda'b'application/pdf'u'application/pdf'b'.pdf'u'.pdf'b'application/pkcs7-mime'u'application/pkcs7-mime'b'.p7c'u'.p7c'b'application/postscript'u'application/postscript'b'.ps'u'.ps'b'.ai'u'.ai'b'.eps'u'.eps'b'application/vnd.apple.mpegurl'u'application/vnd.apple.mpegurl'b'.m3u'u'.m3u'b'.m3u8'u'.m3u8'b'application/vnd.ms-excel'u'application/vnd.ms-excel'b'.xls'u'.xls'b'.xlb'u'.xlb'b'application/vnd.ms-powerpoint'u'application/vnd.ms-powerpoint'b'.ppt'u'.ppt'b'.pot'u'.pot'b'.ppa'u'.ppa'b'.pps'u'.pps'b'.pwz'u'.pwz'b'application/wasm'u'application/wasm'b'.wasm'u'.wasm'b'application/x-bcpio'u'application/x-bcpio'b'.bcpio'u'.bcpio'b'application/x-cpio'u'application/x-cpio'b'.cpio'u'.cpio'b'application/x-csh'u'application/x-csh'b'.csh'u'.csh'b'application/x-dvi'u'application/x-dvi'b'.dvi'u'.dvi'b'application/x-gtar'u'application/x-gtar'b'.gtar'u'.gtar'b'application/x-hdf'u'application/x-hdf'b'.hdf'u'.hdf'b'application/x-hdf5'u'application/x-hdf5'b'.h5'u'.h5'b'application/x-latex'u'application/x-latex'b'.latex'u'.latex'b'application/x-mif'u'application/x-mif'b'.mif'u'.mif'b'application/x-netcdf'u'application/x-netcdf'b'.cdf'u'.cdf'b'.nc'u'.nc'b'application/x-pkcs12'u'application/x-pkcs12'b'.p12'u'.p12'b'.pfx'u'.pfx'b'application/x-pn-realaudio'u'application/x-pn-realaudio'b'.ram'u'.ram'b'application/x-python-code'u'application/x-python-code'b'.pyo'u'.pyo'b'application/x-sh'u'application/x-sh'b'.sh'u'.sh'b'application/x-shar'u'application/x-shar'b'.shar'u'.shar'b'application/x-shockwave-flash'u'application/x-shockwave-flash'b'.swf'u'.swf'b'application/x-sv4cpio'u'application/x-sv4cpio'b'.sv4cpio'u'.sv4cpio'b'application/x-sv4crc'u'application/x-sv4crc'b'.sv4crc'u'.sv4crc'b'application/x-tar'u'application/x-tar'b'.tar'u'.tar'b'application/x-tcl'u'application/x-tcl'b'.tcl'u'.tcl'b'application/x-tex'u'application/x-tex'b'.tex'u'.tex'b'application/x-texinfo'u'application/x-texinfo'b'.texi'u'.texi'b'.texinfo'u'.texinfo'b'application/x-troff'u'application/x-troff'b'.roff'u'.roff'b'.t'u'.t'b'.tr'u'.tr'b'application/x-troff-man'u'application/x-troff-man'b'.man'u'.man'b'application/x-troff-me'u'application/x-troff-me'b'.me'u'.me'b'application/x-troff-ms'u'application/x-troff-ms'b'.ms'u'.ms'b'application/x-ustar'u'application/x-ustar'b'.ustar'u'.ustar'b'application/x-wais-source'u'application/x-wais-source'b'.src'u'.src'b'application/xml'u'application/xml'b'.xsl'u'.xsl'b'.rdf'u'.rdf'b'.wsdl'u'.wsdl'b'.xpdl'u'.xpdl'b'application/zip'u'application/zip'b'.zip'u'.zip'b'audio/basic'u'audio/basic'b'.au'u'.au'b'.snd'u'.snd'b'audio/mpeg'u'audio/mpeg'b'.mp3'u'.mp3'b'.mp2'u'.mp2'b'audio/x-aiff'u'audio/x-aiff'b'.aif'u'.aif'b'.aifc'u'.aifc'b'.aiff'u'.aiff'b'audio/x-pn-realaudio'u'audio/x-pn-realaudio'b'.ra'u'.ra'b'audio/x-wav'u'audio/x-wav'b'.wav'u'.wav'b'image/bmp'u'image/bmp'b'.bmp'u'.bmp'b'image/gif'u'image/gif'b'.gif'u'.gif'b'image/ief'u'image/ief'b'.ief'u'.ief'b'image/jpeg'u'image/jpeg'b'.jpg'u'.jpg'b'.jpe'u'.jpe'b'.jpeg'u'.jpeg'b'image/png'u'image/png'b'.png'u'.png'b'image/svg+xml'u'image/svg+xml'b'.svg'u'.svg'b'image/tiff'u'image/tiff'b'.tiff'u'.tiff'b'.tif'u'.tif'b'image/vnd.microsoft.icon'u'image/vnd.microsoft.icon'b'.ico'u'.ico'b'image/x-cmu-raster'u'image/x-cmu-raster'b'.ras'u'.ras'b'image/x-ms-bmp'u'image/x-ms-bmp'b'image/x-portable-anymap'u'image/x-portable-anymap'b'.pnm'u'.pnm'b'image/x-portable-bitmap'u'image/x-portable-bitmap'b'.pbm'u'.pbm'b'image/x-portable-graymap'u'image/x-portable-graymap'b'.pgm'u'.pgm'b'image/x-portable-pixmap'u'image/x-portable-pixmap'b'.ppm'u'.ppm'b'image/x-rgb'u'image/x-rgb'b'.rgb'u'.rgb'b'image/x-xbitmap'u'image/x-xbitmap'b'.xbm'u'.xbm'b'image/x-xpixmap'u'image/x-xpixmap'b'.xpm'u'.xpm'b'image/x-xwindowdump'u'image/x-xwindowdump'b'.xwd'u'.xwd'b'.eml'u'.eml'b'.mht'u'.mht'b'.mhtml'u'.mhtml'b'.nws'u'.nws'b'text/css'u'text/css'b'.css'u'.css'b'text/csv'u'text/csv'b'.csv'u'.csv'b'text/html'u'text/html'b'.html'u'.html'b'.htm'u'.htm'b'.bat'u'.bat'b'.h'u'.h'b'.ksh'u'.ksh'b'.pl'u'.pl'b'text/richtext'u'text/richtext'b'.rtx'u'.rtx'b'text/tab-separated-values'u'text/tab-separated-values'b'.tsv'u'.tsv'b'text/x-python'u'text/x-python'b'text/x-setext'u'text/x-setext'b'.etx'u'.etx'b'text/x-sgml'u'text/x-sgml'b'.sgm'u'.sgm'b'.sgml'u'.sgml'b'text/x-vcard'u'text/x-vcard'b'.vcf'u'.vcf'b'.xml'u'.xml'b'video/mp4'u'video/mp4'b'.mp4'u'.mp4'b'video/mpeg'u'video/mpeg'b'.mpeg'u'.mpeg'b'.m1v'u'.m1v'b'.mpa'u'.mpa'b'.mpe'u'.mpe'b'.mpg'u'.mpg'b'video/quicktime'u'video/quicktime'b'.mov'u'.mov'b'.qt'u'.qt'b'video/webm'u'video/webm'b'.webm'u'.webm'b'video/x-msvideo'u'video/x-msvideo'b'.avi'u'.avi'b'video/x-sgi-movie'u'video/x-sgi-movie'b'.movie'u'.movie'b'application/rtf'u'application/rtf'b'.rtf'u'.rtf'b'audio/midi'u'audio/midi'b'.midi'u'.midi'b'.mid'u'.mid'b'image/jpg'u'image/jpg'b'image/pict'u'image/pict'b'.pict'u'.pict'b'.pct'u'.pct'b'.pic'u'.pic'b'text/xul'u'text/xul'b'.xul'u'.xul'b'Usage: mimetypes.py [options] type + +Options: + --help / -h -- print this message and exit + --lenient / -l -- additionally search of some common, but non-standard + types. + --extension / -e -- guess extension instead of type + +More than one type argument may be given. +'u'Usage: mimetypes.py [options] type + +Options: + --help / -h -- print this message and exit + --lenient / -l -- additionally search of some common, but non-standard + types. + --extension / -e -- guess extension instead of type + +More than one type argument may be given. +'b'hle'u'hle'b'lenient'u'lenient'b'extension'u'extension'b'-h'u'-h'b'--help'u'--help'b'--lenient'u'--lenient'b'--extension'u'--extension'b'I don't know anything about type'u'I don't know anything about type'b'type:'u'type:'b'encoding:'u'encoding:'u'mimetypes'An object-oriented interface to .netrc files.shlexNetrcParseErrorException raised on syntax errors in the .netrc file.%s (%s, line %s)default_netrc.netrclexerwordchars!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~commenterssaved_linenoget_tokeninstreamentrynamemacdef +bad toplevel token %raccountpush_tokenmalformed %s entry %s terminated by %sst_uidgetuidgetpwuidfowneruid %s~/.netrc file owner (%s) does not match current user (%s)"~/.netrc file owner (%s) does not match"" current user (%s)"~/.netrc access too permissive: access permissions must restrict access to only the owner"~/.netrc access too permissive: access"" permissions must restrict access to only"" the owner"bad follower token %rReturn a (user, account, password) tuple for given host.Dump the class data in the format of a .netrc file.repmachine + login account password macdef # Module and documentation by Eric S. Raymond, 21 Dec 1998# Look for a machine, default, or macdef top-level keyword# Just skip to end of macdefs# We're looking at start of an entry for a named machine or default.b'An object-oriented interface to .netrc files.'u'An object-oriented interface to .netrc files.'b'netrc'u'netrc'b'NetrcParseError'u'NetrcParseError'b'Exception raised on syntax errors in the .netrc file.'u'Exception raised on syntax errors in the .netrc file.'b'%s (%s, line %s)'u'%s (%s, line %s)'u'~'b'.netrc'u'.netrc'b'!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'u'!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'b'machine'u'machine'b'macdef'u'macdef'b' +'u' +'b'bad toplevel token %r'u'bad toplevel token %r'b'malformed %s entry %s terminated by %s'u'malformed %s entry %s terminated by %s'b'login'u'login'b'account'u'account'b'password'u'password'b'uid %s'u'uid %s'b'~/.netrc file owner (%s) does not match current user (%s)'u'~/.netrc file owner (%s) does not match current user (%s)'b'~/.netrc access too permissive: access permissions must restrict access to only the owner'u'~/.netrc access too permissive: access permissions must restrict access to only the owner'b'bad follower token %r'u'bad follower token %r'b'Return a (user, account, password) tuple for given host.'u'Return a (user, account, password) tuple for given host.'b'Dump the class data in the format of a .netrc file.'u'Dump the class data in the format of a .netrc file.'b'machine 'u'machine 'b' + login 'u' + login 'b' account 'u' account 'b' password 'u' password 'b'macdef 'u'macdef 'An NNTP client class based on: +- RFC 977: Network News Transfer Protocol +- RFC 2980: Common NNTP Extensions +- RFC 3977: Network News Transfer Protocol (version 2) + +Example: + +>>> from nntplib import NNTP +>>> s = NNTP('news') +>>> resp, count, first, last, name = s.group('comp.lang.python') +>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) +Group comp.lang.python has 51 articles, range 5770 to 5821 +>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last)) +>>> resp = s.quit() +>>> + +Here 'resp' is the server response line. +Error responses are turned into exceptions. + +To post an article from a file: +>>> f = open(filename, 'rb') # file containing article, including header +>>> resp = s.post(f) +>>> + +For descriptions of all methods, read the comments in the code below. +Note that all arguments and return values representing article numbers +are strings, not numbers, since they are rarely used for calculations. +_have_sslemail.header_email_decode_headerNNTPNNTPErrorNNTPReplyErrorNNTPPermanentErrorNNTPProtocolErrorNNTPDataErrorBase class for all nntplib exceptionsNo response givenUnexpected [123]xx reply4xx errors5xx errorsResponse does not begin with [1-5]Error in response data119NNTP_PORT563NNTP_SSL_PORT282_LONGRESPmessage-idreferences:bytes:lines_DEFAULT_OVERVIEW_FMT_OVERVIEW_FMT_ALTERNATIVES_CRLFGroupInfoArticleInfomessage_idTakes a unicode string representing a munged header value + and decodes it as a (possibly non-ASCII) readable value._parse_overview_fmtParse a list of string representing the response to LIST OVERVIEW.FMT + and return a list of header/metadata names. + Raises NNTPDataError if the response is not compliant + (cf. RFC 3977, section 8.4).LIST OVERVIEW.FMT response too shortLIST OVERVIEW.FMT redefines default fields_parse_overviewdata_process_funcParse the response to an OVER or XOVER command according to the + overview format `fmt`.n_defaultsoverviewarticle_numberfield_nameis_metadataOVER/XOVER response doesn't include names of additional headers"OVER/XOVER response doesn't include ""names of additional headers"_parse_datetimedate_strtime_strParse a pair of (date, time) strings, and return a datetime object. + If only the date is given, it is assumed to be date and time + concatenated together (e.g. response to the DATE command). + _unparse_datetimelegacyFormat a date or datetime object as a pair of (date, time) strings + in the format required by the NEWNEWS and NEWGROUPS commands. If a + date object is passed, the time is assumed to be midnight (00h00). + + The returned representation depends on the legacy flag: + * if legacy is False (the default): + date has the YYYYMMDD format and time the HHMMSS format + * if legacy is True: + date has the YYMMDD format and time the HHMMSS format. + RFC 3977 compliant servers should understand both formats; therefore, + legacy is only needed when talking to old servers. + 000000{0.hour:02d}{0.minute:02d}{0.second:02d}{0:02d}{1.month:02d}{1.day:02d}{0:04d}{1.month:02d}{1.day:02d}_encrypt_onhostnameWrap a socket in SSL/TLS. Arguments: + - sock: Socket to wrap + - context: SSL context to use for the encrypted connection + Returns: + - sock: New, encrypted socket. + _NNTPBasereadermodeInitialize an instance. Arguments: + - file: file-like object (open for read/write in binary mode) + - host: hostname of the server + - readermode: if true, send 'mode reader' command after + connecting. + - timeout: timeout (in seconds) used for socket connections + + readermode is sometimes necessary if you are connecting to an + NNTP server on the local machine and intend to call + reader-specific commands, such as `group'. If you get + unexpected NNTPPermanentErrors, you might need to set + readermode. + _getresp_capsgetcapabilitiesreadermode_afterauthREADER_setreadermodetls_onauthenticatedis_connectedGet the welcome message from the server + (this is read and squirreled away by __init__()). + If the response code is 200, posting is allowed; + if it 201, posting is not allowed.Get the server capabilities, as read by __init__(). + If the CAPABILITIES command is not supported, an empty dict is + returned.nntp_versionnntp_implementationcapabilitiescapsIMPLEMENTATIONSet the debugging level. Argument 'level' means: + 0: no debugging output (default) + 1: print commands and responses but not body text etc. + 2: also print raw lines read and sent before stripping CR/LF_putlineInternal: send one line to the server, appending CRLF. + The `line` must be a bytes-like object.nntplib.putline_putcmdInternal: send one command to the server (through _putline()). + The `line` must be a unicode string._getlinestrip_crlfInternal: return one line from the server, stripping _CRLF. + Raise EOFError if the connection is closed. + Returns a bytes object.line too longInternal: get a response from the server. + Raise various errors if the response indicates an error. + Returns a unicode string.123_getlongrespInternal: get a response plus following text from the server. + Raise various errors if the response indicates an error. + + Returns a (response, lines) tuple where `response` is a unicode + string and `lines` is a list of bytes objects. + If `file` is a file-like object, it must be open in binary mode. + openedFile. +terminators_shortcmdInternal: send a command and get the response. + Same return value as _getresp()._longcmdInternal: send a command and get the response plus following text. + Same return value as _getlongresp()._longcmdstringInternal: send a command and get the response plus following text. + Same as _longcmd() and _getlongresp(), except that the returned `lines` + are unicode strings rather than bytes objects. + _getoverviewfmtInternal: get the overview format. Queries the server if not + already done, else returns the cached value._cachedoverviewfmtLIST OVERVIEW.FMT_grouplistProcess a CAPABILITIES command. Not supported by all servers. + Return: + - resp: server response if successful + - caps: a dictionary mapping capability names to lists of tokens + (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) + CAPABILITIESnewgroupsProcess a NEWGROUPS command. Arguments: + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of newsgroup names + the date parameter must be a date or datetime object, not '{:40}'"the date parameter must be a date or datetime object, ""not '{:40}'"NEWGROUPS {0} {1}newnewsProcess a NEWNEWS command. Arguments: + - group: group name or '*' + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of message ids + NEWNEWS {0} {1} {2}group_patternProcess a LIST or LIST ACTIVE command. Arguments: + - group_pattern: a pattern indicating which groups to query + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (group, last, first, flag) (strings) + LIST ACTIVE _getdescriptionsreturn_all^(?P[^ ]+)[ ]+(.*)$line_patLIST NEWSGROUPS XGTITLE raw_lineGet a description for a single group. If more than one + group matches ('group' is a pattern), return the first. If no + group matches, return an empty string. + + This elides the response code from the server, since it can + only be '215' or '285' (for xgtitle) anyway. If the response + code is needed, use the 'descriptions' method. + + NOTE: This neither checks for a wildcard in 'group' nor does + it check whether the group actually exists.descriptionsGet descriptions for a range of groups.Process a GROUP command. Argument: + - group: the group name + Returns: + - resp: server response if successful + - count: number of articles + - first: first article number + - last: last article number + - name: the group name + GROUP Process a HELP command. Argument: + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of strings returned by the server in response to the + HELP command + HELP_statparseInternal: parse the response line of a STAT, NEXT, LAST, + ARTICLE, HEAD or BODY command.art_num_statcmdInternal: process a STAT, NEXT or LAST command.message_specProcess a STAT command. Argument: + - message_spec: article number or message id (if not specified, + the current article is selected) + Returns: + - resp: server response if successful + - art_num: the article number + - message_id: the message id + STAT {0}STATProcess a NEXT command. No arguments. Return as for STAT.Process a LAST command. No arguments. Return as for STAT._artcmdInternal: process a HEAD, BODY or ARTICLE command.Process a HEAD command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the headers in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of header lines) + HEAD {0}Process a BODY command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the body in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of body lines) + BODY {0}BODYarticleProcess an ARTICLE command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the article in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of article lines) + ARTICLE {0}ARTICLEslaveProcess a SLAVE command. Returns: + - resp: server response if successful + SLAVExhdrProcess an XHDR command (optional server extension). Arguments: + - hdr: the header type (e.g. 'subject') + - str: an article nr, a message id, or a range nr1-nr2 + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (nr, value) strings + ^([0-9]+) ?(.*) +?XHDR {0} {1}remove_numberxoverProcess an XOVER command (optional server extension) Arguments: + - start: start of range + - end: end of range + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + XOVER {0}-{1}overProcess an OVER command. If the command isn't supported, fall + back to XOVER. Arguments: + - message_spec: + - either a message id, indicating the article to fetch + information about + - or a (start, end) tuple, indicating a range of article numbers; + if end is None, information up to the newest message will be + retrieved + - or None, indicating the current article number must be used + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + + NOTE: the "message id" form isn't supported by XOVER + OVERXOVER {0}-{1}xgtitleProcess an XGTITLE command (optional server extension) Arguments: + - group: group name wildcard (i.e. news.*) + Returns: + - resp: server response if successful + - list: list of (name,title) stringsThe XGTITLE extension is not actively used, use descriptions() instead"The XGTITLE extension is not actively used, ""use descriptions() instead"^([^ ]+)[ ]+(.*)$raw_linesxpathProcess an XPATH command (optional server extension) Arguments: + - id: Message id of article + Returns: + resp: server response if successful + path: directory path to article + The XPATH extension is not actively usedXPATH {0}resp_numProcess the DATE command. + Returns: + - resp: server response if successful + - date: datetime object + DATE_post. +Process a POST command. Arguments: + - data: bytes object, iterable or file containing the article + Returns: + - resp: server response if successfulihaveProcess an IHAVE command. Arguments: + - message_id: message-id of the article + - data: file containing the article + Returns: + - resp: server response if successful + Note that if the server refuses the article an exception is raised.IHAVE {0}Process a QUIT command and close the socket. Returns: + - resp: server response if successfulusenetrcAlready logged in.At least one of `user` and `usenetrc` must be specifiedauthinfo user 381authinfo pass 281mode reader480Process a STARTTLS command. Arguments: + - context: SSL context to use for the encrypted connection + TLS is already enabled.TLS cannot be started after authentication.STARTTLS382rwbTLS failed to start.Initialize an instance. Arguments: + - host: hostname to connect to + - port: port to connect to (default the standard NNTP port) + - user: username to authenticate with + - password: password to use with username + - readermode: if true, send 'mode reader' command after + connecting. + - usenetrc: allow loading username and password from ~/.netrc file + if not specified explicitly + - timeout: timeout (in seconds) used for socket connections + + readermode is sometimes necessary if you are connecting to an + NNTP server on the local machine and intend to call + reader-specific commands, such as `group'. If you get + unexpected NNTPPermanentErrors, you might need to set + readermode. + nntplib.connectNNTP_SSLThis works identically to NNTP.__init__, except for the change + in default port and the `ssl_context` argument for SSL connections. + nntplib built-in demo - display the latest articles in a newsgroup--groupgmane.comp.python.generalgroup to fetch messages from (default: %(default)s)--servernews.gmane.ioNNTP server hostname (default: %(default)s)--portNNTP port number (default: %s / %s)-n--nb-articlesnumber of articles to fetch (default: %(default)s)-S--ssluse NNTP over SSLGrouphasarticles, rangecutlimnb_articlesoverviewsartnumauthor{:7} {:20} {:42} ({})# RFC 977 by Brian Kantor and Phil Lapsley.# xover, xgtitle, xpath, date methods by Kevan Heydon# Incompatible changes from the 2.x nntplib:# - all commands are encoded as UTF-8 data (using the "surrogateescape"# error handler), except for raw message data (POST, IHAVE)# - all responses are decoded as UTF-8 data (using the "surrogateescape"# error handler), except for raw message data (ARTICLE, HEAD, BODY)# - the `file` argument to various methods is keyword-only# - NNTP.date() returns a datetime object# - NNTP.newgroups() and NNTP.newnews() take a datetime (or date) object,# rather than a pair of (date, time) strings.# - NNTP.newgroups() and NNTP.list() return a list of GroupInfo named tuples# - NNTP.descriptions() returns a dict mapping group names to descriptions# - NNTP.xover() returns a list of dicts mapping field names (header or metadata)# to field values; each dict representing a message overview.# - NNTP.article(), NNTP.head() and NNTP.body() return a (response, ArticleInfo)# tuple.# - the "internal" methods have been marked private (they now start with# an underscore)# Other changes from the 2.x/3.1 nntplib:# - automatic querying of capabilities at connect# - New method NNTP.getcapabilities()# - New method NNTP.over()# - New helper function decode_header()# - NNTP.post() and NNTP.ihave() accept file objects, bytes-like objects and# arbitrary iterables yielding lines.# - An extensive test suite :-)# - return structured data (GroupInfo etc.) everywhere# - support HDR# Imports# maximal line length when calling readline(). This is to prevent# reading arbitrary length lines. RFC 3977 limits NNTP line length to# 512 characters, including CRLF. We have selected 2048 just to be on# the safe side.# Exceptions raised when an error or invalid response is received# Standard port used by NNTP servers# Response numbers that are followed by additional text (e.g. article)# HELP# CAPABILITIES# LISTGROUP (also not multi-line with GROUP)# LIST# ARTICLE# HEAD, XHDR# BODY# OVER, XOVER# HDR# NEWNEWS# NEWGROUPS# XGTITLE# Default decoded value for LIST OVERVIEW.FMT if not supported# Alternative names allowed in LIST OVERVIEW.FMT response# Helper function(s)# Metadata name (e.g. ":bytes")# Header name (e.g. "Subject:" or "Xref:full")# Should we do something with the suffix?# XXX should we raise an error? Some servers might not# support LIST OVERVIEW.FMT and still return additional# headers.# Non-default header names are included in full in the response# (unless the field is totally empty)# RFC 3977 doesn't say how to interpret 2-char years. Assume that# there are no dates before 1970 on Usenet.# Generate a default SSL context if none was passed.# The classes themselves# UTF-8 is the character set for all NNTP commands and responses: they# are automatically encoded (when sending) and decoded (and receiving)# by this class.# However, some multi-line data blocks can contain arbitrary bytes (for# example, latin-1 or utf-16 data in the body of a message). Commands# taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message# data will therefore only accept and produce bytes objects.# Furthermore, since there could be non-compliant servers out there,# we use 'surrogateescape' as the error handler for fault tolerance# and easy round-tripping. This could be useful for some applications# (e.g. NNTP gateways).# Inquire about capabilities (RFC 3977).# 'MODE READER' is sometimes necessary to enable 'reader' mode.# However, the order in which 'MODE READER' and 'AUTHINFO' need to# arrive differs between some NNTP servers. If _setreadermode() fails# with an authorization failed error, it will set this to True;# the login() routine will interpret that as a request to try again# after performing its normal function.# Enable only if we're not already in READER mode anyway.# Capabilities might have changed after MODE READER# RFC 4642 2.2.2: Both the client and the server MUST know if there is# a TLS session active. A client MUST NOT attempt to start a TLS# session if a TLS session is already active.# Log in and encryption setup order is left to subclasses.# Server doesn't support capabilities# The server can advertise several supported versions,# choose the highest.# If a string was passed then open a file with that name# XXX lines = None instead?# If this method created the file, then it must close it# Not supported by server?# Parse lines into "group last first flag"# Try the more std (acc. to RFC2980) LIST NEWSGROUPS first# Now the deprecated XGTITLE. This either raises an error# or succeeds with the same output structure as LIST# NEWSGROUPS.# Nothing found# Raises a specific exception if posting is not allowed# We don't use _putline() because:# - we don't want additional CRLF if the file or iterable is already# in the right format# - we don't want a spurious flush() after each line is written# If no login/password was specified but netrc was requested,# try to get them from ~/.netrc# Presume that if .netrc has an entry, NNRP authentication is required.# Perform NNTP authentication if needed.# Capabilities might have changed after login# Attempt to send mode reader if it was requested after login.# Only do so if we're not in reader mode already.# Error 5xx, probably 'not implemented'# Need authorization before 'mode reader'# Per RFC 4642, STARTTLS MUST NOT be sent after authentication or if# a TLS session already exists.# Capabilities may change after TLS starts up, so ask for them# again.# Test retrieval when run as a script.b'An NNTP client class based on: +- RFC 977: Network News Transfer Protocol +- RFC 2980: Common NNTP Extensions +- RFC 3977: Network News Transfer Protocol (version 2) + +Example: + +>>> from nntplib import NNTP +>>> s = NNTP('news') +>>> resp, count, first, last, name = s.group('comp.lang.python') +>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) +Group comp.lang.python has 51 articles, range 5770 to 5821 +>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last)) +>>> resp = s.quit() +>>> + +Here 'resp' is the server response line. +Error responses are turned into exceptions. + +To post an article from a file: +>>> f = open(filename, 'rb') # file containing article, including header +>>> resp = s.post(f) +>>> + +For descriptions of all methods, read the comments in the code below. +Note that all arguments and return values representing article numbers +are strings, not numbers, since they are rarely used for calculations. +'u'An NNTP client class based on: +- RFC 977: Network News Transfer Protocol +- RFC 2980: Common NNTP Extensions +- RFC 3977: Network News Transfer Protocol (version 2) + +Example: + +>>> from nntplib import NNTP +>>> s = NNTP('news') +>>> resp, count, first, last, name = s.group('comp.lang.python') +>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) +Group comp.lang.python has 51 articles, range 5770 to 5821 +>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last)) +>>> resp = s.quit() +>>> + +Here 'resp' is the server response line. +Error responses are turned into exceptions. + +To post an article from a file: +>>> f = open(filename, 'rb') # file containing article, including header +>>> resp = s.post(f) +>>> + +For descriptions of all methods, read the comments in the code below. +Note that all arguments and return values representing article numbers +are strings, not numbers, since they are rarely used for calculations. +'b'NNTP'u'NNTP'b'NNTPError'u'NNTPError'b'NNTPReplyError'u'NNTPReplyError'b'NNTPTemporaryError'u'NNTPTemporaryError'b'NNTPPermanentError'u'NNTPPermanentError'b'NNTPProtocolError'u'NNTPProtocolError'b'NNTPDataError'u'NNTPDataError'b'Base class for all nntplib exceptions'u'Base class for all nntplib exceptions'b'No response given'u'No response given'b'Unexpected [123]xx reply'u'Unexpected [123]xx reply'b'4xx errors'u'4xx errors'b'5xx errors'u'5xx errors'b'Response does not begin with [1-5]'u'Response does not begin with [1-5]'b'Error in response data'u'Error in response data'b'100'u'100'b'101'u'101'b'211'u'211'b'215'u'215'b'220'u'220'b'221'u'221'b'222'u'222'b'224'u'224'b'230'u'230'b'282'u'282'b'subject'u'subject'b'date'u'date'b'message-id'u'message-id'b'references'u'references'b':bytes'u':bytes'b':lines'u':lines'b'bytes'u'bytes'b'lines'u'lines'b'GroupInfo'u'GroupInfo'b'flag'u'flag'b'ArticleInfo'u'ArticleInfo'b'number'u'number'b'message_id'u'message_id'b'Takes a unicode string representing a munged header value + and decodes it as a (possibly non-ASCII) readable value.'u'Takes a unicode string representing a munged header value + and decodes it as a (possibly non-ASCII) readable value.'b'Parse a list of string representing the response to LIST OVERVIEW.FMT + and return a list of header/metadata names. + Raises NNTPDataError if the response is not compliant + (cf. RFC 3977, section 8.4).'u'Parse a list of string representing the response to LIST OVERVIEW.FMT + and return a list of header/metadata names. + Raises NNTPDataError if the response is not compliant + (cf. RFC 3977, section 8.4).'b'LIST OVERVIEW.FMT response too short'u'LIST OVERVIEW.FMT response too short'b'LIST OVERVIEW.FMT redefines default fields'u'LIST OVERVIEW.FMT redefines default fields'b'Parse the response to an OVER or XOVER command according to the + overview format `fmt`.'u'Parse the response to an OVER or XOVER command according to the + overview format `fmt`.'b'OVER/XOVER response doesn't include names of additional headers'u'OVER/XOVER response doesn't include names of additional headers'b'Parse a pair of (date, time) strings, and return a datetime object. + If only the date is given, it is assumed to be date and time + concatenated together (e.g. response to the DATE command). + 'u'Parse a pair of (date, time) strings, and return a datetime object. + If only the date is given, it is assumed to be date and time + concatenated together (e.g. response to the DATE command). + 'b'Format a date or datetime object as a pair of (date, time) strings + in the format required by the NEWNEWS and NEWGROUPS commands. If a + date object is passed, the time is assumed to be midnight (00h00). + + The returned representation depends on the legacy flag: + * if legacy is False (the default): + date has the YYYYMMDD format and time the HHMMSS format + * if legacy is True: + date has the YYMMDD format and time the HHMMSS format. + RFC 3977 compliant servers should understand both formats; therefore, + legacy is only needed when talking to old servers. + 'u'Format a date or datetime object as a pair of (date, time) strings + in the format required by the NEWNEWS and NEWGROUPS commands. If a + date object is passed, the time is assumed to be midnight (00h00). + + The returned representation depends on the legacy flag: + * if legacy is False (the default): + date has the YYYYMMDD format and time the HHMMSS format + * if legacy is True: + date has the YYMMDD format and time the HHMMSS format. + RFC 3977 compliant servers should understand both formats; therefore, + legacy is only needed when talking to old servers. + 'b'000000'u'000000'b'{0.hour:02d}{0.minute:02d}{0.second:02d}'u'{0.hour:02d}{0.minute:02d}{0.second:02d}'b'{0:02d}{1.month:02d}{1.day:02d}'u'{0:02d}{1.month:02d}{1.day:02d}'b'{0:04d}{1.month:02d}{1.day:02d}'u'{0:04d}{1.month:02d}{1.day:02d}'b'Wrap a socket in SSL/TLS. Arguments: + - sock: Socket to wrap + - context: SSL context to use for the encrypted connection + Returns: + - sock: New, encrypted socket. + 'u'Wrap a socket in SSL/TLS. Arguments: + - sock: Socket to wrap + - context: SSL context to use for the encrypted connection + Returns: + - sock: New, encrypted socket. + 'b'Initialize an instance. Arguments: + - file: file-like object (open for read/write in binary mode) + - host: hostname of the server + - readermode: if true, send 'mode reader' command after + connecting. + - timeout: timeout (in seconds) used for socket connections + + readermode is sometimes necessary if you are connecting to an + NNTP server on the local machine and intend to call + reader-specific commands, such as `group'. If you get + unexpected NNTPPermanentErrors, you might need to set + readermode. + 'u'Initialize an instance. Arguments: + - file: file-like object (open for read/write in binary mode) + - host: hostname of the server + - readermode: if true, send 'mode reader' command after + connecting. + - timeout: timeout (in seconds) used for socket connections + + readermode is sometimes necessary if you are connecting to an + NNTP server on the local machine and intend to call + reader-specific commands, such as `group'. If you get + unexpected NNTPPermanentErrors, you might need to set + readermode. + 'b'READER'u'READER'b'Get the welcome message from the server + (this is read and squirreled away by __init__()). + If the response code is 200, posting is allowed; + if it 201, posting is not allowed.'u'Get the welcome message from the server + (this is read and squirreled away by __init__()). + If the response code is 200, posting is allowed; + if it 201, posting is not allowed.'b'Get the server capabilities, as read by __init__(). + If the CAPABILITIES command is not supported, an empty dict is + returned.'u'Get the server capabilities, as read by __init__(). + If the CAPABILITIES command is not supported, an empty dict is + returned.'b'IMPLEMENTATION'u'IMPLEMENTATION'b'Set the debugging level. Argument 'level' means: + 0: no debugging output (default) + 1: print commands and responses but not body text etc. + 2: also print raw lines read and sent before stripping CR/LF'u'Set the debugging level. Argument 'level' means: + 0: no debugging output (default) + 1: print commands and responses but not body text etc. + 2: also print raw lines read and sent before stripping CR/LF'b'Internal: send one line to the server, appending CRLF. + The `line` must be a bytes-like object.'u'Internal: send one line to the server, appending CRLF. + The `line` must be a bytes-like object.'b'nntplib.putline'u'nntplib.putline'b'Internal: send one command to the server (through _putline()). + The `line` must be a unicode string.'u'Internal: send one command to the server (through _putline()). + The `line` must be a unicode string.'b'Internal: return one line from the server, stripping _CRLF. + Raise EOFError if the connection is closed. + Returns a bytes object.'u'Internal: return one line from the server, stripping _CRLF. + Raise EOFError if the connection is closed. + Returns a bytes object.'b'line too long'u'line too long'b'Internal: get a response from the server. + Raise various errors if the response indicates an error. + Returns a unicode string.'u'Internal: get a response from the server. + Raise various errors if the response indicates an error. + Returns a unicode string.'b'123'u'123'b'Internal: get a response plus following text from the server. + Raise various errors if the response indicates an error. + + Returns a (response, lines) tuple where `response` is a unicode + string and `lines` is a list of bytes objects. + If `file` is a file-like object, it must be open in binary mode. + 'u'Internal: get a response plus following text from the server. + Raise various errors if the response indicates an error. + + Returns a (response, lines) tuple where `response` is a unicode + string and `lines` is a list of bytes objects. + If `file` is a file-like object, it must be open in binary mode. + 'b'. +'b'Internal: send a command and get the response. + Same return value as _getresp().'u'Internal: send a command and get the response. + Same return value as _getresp().'b'Internal: send a command and get the response plus following text. + Same return value as _getlongresp().'u'Internal: send a command and get the response plus following text. + Same return value as _getlongresp().'b'Internal: send a command and get the response plus following text. + Same as _longcmd() and _getlongresp(), except that the returned `lines` + are unicode strings rather than bytes objects. + 'u'Internal: send a command and get the response plus following text. + Same as _longcmd() and _getlongresp(), except that the returned `lines` + are unicode strings rather than bytes objects. + 'b'Internal: get the overview format. Queries the server if not + already done, else returns the cached value.'u'Internal: get the overview format. Queries the server if not + already done, else returns the cached value.'b'LIST OVERVIEW.FMT'u'LIST OVERVIEW.FMT'b'Process a CAPABILITIES command. Not supported by all servers. + Return: + - resp: server response if successful + - caps: a dictionary mapping capability names to lists of tokens + (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) + 'u'Process a CAPABILITIES command. Not supported by all servers. + Return: + - resp: server response if successful + - caps: a dictionary mapping capability names to lists of tokens + (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) + 'b'CAPABILITIES'u'CAPABILITIES'b'Process a NEWGROUPS command. Arguments: + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of newsgroup names + 'u'Process a NEWGROUPS command. Arguments: + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of newsgroup names + 'b'the date parameter must be a date or datetime object, not '{:40}''u'the date parameter must be a date or datetime object, not '{:40}''b'NEWGROUPS {0} {1}'u'NEWGROUPS {0} {1}'b'Process a NEWNEWS command. Arguments: + - group: group name or '*' + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of message ids + 'u'Process a NEWNEWS command. Arguments: + - group: group name or '*' + - date: a date or datetime object + Return: + - resp: server response if successful + - list: list of message ids + 'b'NEWNEWS {0} {1} {2}'u'NEWNEWS {0} {1} {2}'b'Process a LIST or LIST ACTIVE command. Arguments: + - group_pattern: a pattern indicating which groups to query + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (group, last, first, flag) (strings) + 'u'Process a LIST or LIST ACTIVE command. Arguments: + - group_pattern: a pattern indicating which groups to query + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (group, last, first, flag) (strings) + 'b'LIST ACTIVE 'u'LIST ACTIVE 'b'^(?P[^ ]+)[ ]+(.*)$'u'^(?P[^ ]+)[ ]+(.*)$'b'LIST NEWSGROUPS 'u'LIST NEWSGROUPS 'b'XGTITLE 'u'XGTITLE 'b'Get a description for a single group. If more than one + group matches ('group' is a pattern), return the first. If no + group matches, return an empty string. + + This elides the response code from the server, since it can + only be '215' or '285' (for xgtitle) anyway. If the response + code is needed, use the 'descriptions' method. + + NOTE: This neither checks for a wildcard in 'group' nor does + it check whether the group actually exists.'u'Get a description for a single group. If more than one + group matches ('group' is a pattern), return the first. If no + group matches, return an empty string. + + This elides the response code from the server, since it can + only be '215' or '285' (for xgtitle) anyway. If the response + code is needed, use the 'descriptions' method. + + NOTE: This neither checks for a wildcard in 'group' nor does + it check whether the group actually exists.'b'Get descriptions for a range of groups.'u'Get descriptions for a range of groups.'b'Process a GROUP command. Argument: + - group: the group name + Returns: + - resp: server response if successful + - count: number of articles + - first: first article number + - last: last article number + - name: the group name + 'u'Process a GROUP command. Argument: + - group: the group name + Returns: + - resp: server response if successful + - count: number of articles + - first: first article number + - last: last article number + - name: the group name + 'b'GROUP 'u'GROUP 'b'Process a HELP command. Argument: + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of strings returned by the server in response to the + HELP command + 'u'Process a HELP command. Argument: + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of strings returned by the server in response to the + HELP command + 'b'HELP'u'HELP'b'Internal: parse the response line of a STAT, NEXT, LAST, + ARTICLE, HEAD or BODY command.'u'Internal: parse the response line of a STAT, NEXT, LAST, + ARTICLE, HEAD or BODY command.'b'Internal: process a STAT, NEXT or LAST command.'u'Internal: process a STAT, NEXT or LAST command.'b'Process a STAT command. Argument: + - message_spec: article number or message id (if not specified, + the current article is selected) + Returns: + - resp: server response if successful + - art_num: the article number + - message_id: the message id + 'u'Process a STAT command. Argument: + - message_spec: article number or message id (if not specified, + the current article is selected) + Returns: + - resp: server response if successful + - art_num: the article number + - message_id: the message id + 'b'STAT {0}'u'STAT {0}'b'STAT'u'STAT'b'Process a NEXT command. No arguments. Return as for STAT.'u'Process a NEXT command. No arguments. Return as for STAT.'b'NEXT'u'NEXT'b'Process a LAST command. No arguments. Return as for STAT.'u'Process a LAST command. No arguments. Return as for STAT.'b'LAST'u'LAST'b'Internal: process a HEAD, BODY or ARTICLE command.'u'Internal: process a HEAD, BODY or ARTICLE command.'b'Process a HEAD command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the headers in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of header lines) + 'u'Process a HEAD command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the headers in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of header lines) + 'b'HEAD {0}'u'HEAD {0}'b'Process a BODY command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the body in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of body lines) + 'u'Process a BODY command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the body in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of body lines) + 'b'BODY {0}'u'BODY {0}'b'BODY'u'BODY'b'Process an ARTICLE command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the article in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of article lines) + 'u'Process an ARTICLE command. Argument: + - message_spec: article number or message id + - file: filename string or file object to store the article in + Returns: + - resp: server response if successful + - ArticleInfo: (article number, message id, list of article lines) + 'b'ARTICLE {0}'u'ARTICLE {0}'b'ARTICLE'u'ARTICLE'b'Process a SLAVE command. Returns: + - resp: server response if successful + 'u'Process a SLAVE command. Returns: + - resp: server response if successful + 'b'SLAVE'u'SLAVE'b'Process an XHDR command (optional server extension). Arguments: + - hdr: the header type (e.g. 'subject') + - str: an article nr, a message id, or a range nr1-nr2 + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (nr, value) strings + 'u'Process an XHDR command (optional server extension). Arguments: + - hdr: the header type (e.g. 'subject') + - str: an article nr, a message id, or a range nr1-nr2 + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of (nr, value) strings + 'b'^([0-9]+) ?(.*) +?'u'^([0-9]+) ?(.*) +?'b'XHDR {0} {1}'u'XHDR {0} {1}'b'Process an XOVER command (optional server extension) Arguments: + - start: start of range + - end: end of range + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + 'u'Process an XOVER command (optional server extension) Arguments: + - start: start of range + - end: end of range + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + 'b'XOVER {0}-{1}'u'XOVER {0}-{1}'b'Process an OVER command. If the command isn't supported, fall + back to XOVER. Arguments: + - message_spec: + - either a message id, indicating the article to fetch + information about + - or a (start, end) tuple, indicating a range of article numbers; + if end is None, information up to the newest message will be + retrieved + - or None, indicating the current article number must be used + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + + NOTE: the "message id" form isn't supported by XOVER + 'u'Process an OVER command. If the command isn't supported, fall + back to XOVER. Arguments: + - message_spec: + - either a message id, indicating the article to fetch + information about + - or a (start, end) tuple, indicating a range of article numbers; + if end is None, information up to the newest message will be + retrieved + - or None, indicating the current article number must be used + - file: Filename string or file object to store the result in + Returns: + - resp: server response if successful + - list: list of dicts containing the response fields + + NOTE: the "message id" form isn't supported by XOVER + 'b'OVER'u'OVER'b'XOVER'u'XOVER'b' {0}-{1}'u' {0}-{1}'b'Process an XGTITLE command (optional server extension) Arguments: + - group: group name wildcard (i.e. news.*) + Returns: + - resp: server response if successful + - list: list of (name,title) strings'u'Process an XGTITLE command (optional server extension) Arguments: + - group: group name wildcard (i.e. news.*) + Returns: + - resp: server response if successful + - list: list of (name,title) strings'b'The XGTITLE extension is not actively used, use descriptions() instead'u'The XGTITLE extension is not actively used, use descriptions() instead'b'^([^ ]+)[ ]+(.*)$'u'^([^ ]+)[ ]+(.*)$'b'Process an XPATH command (optional server extension) Arguments: + - id: Message id of article + Returns: + resp: server response if successful + path: directory path to article + 'u'Process an XPATH command (optional server extension) Arguments: + - id: Message id of article + Returns: + resp: server response if successful + path: directory path to article + 'b'The XPATH extension is not actively used'u'The XPATH extension is not actively used'b'XPATH {0}'u'XPATH {0}'b'223'u'223'b'Process the DATE command. + Returns: + - resp: server response if successful + - date: datetime object + 'u'Process the DATE command. + Returns: + - resp: server response if successful + - date: datetime object + 'b'DATE'u'DATE'b'111'u'111'b'. +'b'Process a POST command. Arguments: + - data: bytes object, iterable or file containing the article + Returns: + - resp: server response if successful'u'Process a POST command. Arguments: + - data: bytes object, iterable or file containing the article + Returns: + - resp: server response if successful'b'Process an IHAVE command. Arguments: + - message_id: message-id of the article + - data: file containing the article + Returns: + - resp: server response if successful + Note that if the server refuses the article an exception is raised.'u'Process an IHAVE command. Arguments: + - message_id: message-id of the article + - data: file containing the article + Returns: + - resp: server response if successful + Note that if the server refuses the article an exception is raised.'b'IHAVE {0}'u'IHAVE {0}'b'Process a QUIT command and close the socket. Returns: + - resp: server response if successful'u'Process a QUIT command and close the socket. Returns: + - resp: server response if successful'b'Already logged in.'u'Already logged in.'b'At least one of `user` and `usenetrc` must be specified'u'At least one of `user` and `usenetrc` must be specified'b'authinfo user 'u'authinfo user 'b'381'u'381'b'authinfo pass 'u'authinfo pass 'b'281'u'281'b'mode reader'u'mode reader'b'480'u'480'b'Process a STARTTLS command. Arguments: + - context: SSL context to use for the encrypted connection + 'u'Process a STARTTLS command. Arguments: + - context: SSL context to use for the encrypted connection + 'b'TLS is already enabled.'u'TLS is already enabled.'b'TLS cannot be started after authentication.'u'TLS cannot be started after authentication.'b'STARTTLS'u'STARTTLS'b'382'u'382'b'rwb'u'rwb'b'TLS failed to start.'u'TLS failed to start.'b'Initialize an instance. Arguments: + - host: hostname to connect to + - port: port to connect to (default the standard NNTP port) + - user: username to authenticate with + - password: password to use with username + - readermode: if true, send 'mode reader' command after + connecting. + - usenetrc: allow loading username and password from ~/.netrc file + if not specified explicitly + - timeout: timeout (in seconds) used for socket connections + + readermode is sometimes necessary if you are connecting to an + NNTP server on the local machine and intend to call + reader-specific commands, such as `group'. If you get + unexpected NNTPPermanentErrors, you might need to set + readermode. + 'u'Initialize an instance. Arguments: + - host: hostname to connect to + - port: port to connect to (default the standard NNTP port) + - user: username to authenticate with + - password: password to use with username + - readermode: if true, send 'mode reader' command after + connecting. + - usenetrc: allow loading username and password from ~/.netrc file + if not specified explicitly + - timeout: timeout (in seconds) used for socket connections + + readermode is sometimes necessary if you are connecting to an + NNTP server on the local machine and intend to call + reader-specific commands, such as `group'. If you get + unexpected NNTPPermanentErrors, you might need to set + readermode. + 'b'nntplib.connect'u'nntplib.connect'b'This works identically to NNTP.__init__, except for the change + in default port and the `ssl_context` argument for SSL connections. + 'u'This works identically to NNTP.__init__, except for the change + in default port and the `ssl_context` argument for SSL connections. + 'b'NNTP_SSL'u'NNTP_SSL'b' nntplib built-in demo - display the latest articles in a newsgroup'u' nntplib built-in demo - display the latest articles in a newsgroup'b'--group'u'--group'b'gmane.comp.python.general'u'gmane.comp.python.general'b'group to fetch messages from (default: %(default)s)'u'group to fetch messages from (default: %(default)s)'b'--server'u'--server'b'news.gmane.io'u'news.gmane.io'b'NNTP server hostname (default: %(default)s)'u'NNTP server hostname (default: %(default)s)'b'--port'u'--port'b'NNTP port number (default: %s / %s)'u'NNTP port number (default: %s / %s)'b'-n'u'-n'b'--nb-articles'u'--nb-articles'b'number of articles to fetch (default: %(default)s)'u'number of articles to fetch (default: %(default)s)'b'-S'u'-S'b'--ssl'u'--ssl'b'use NNTP over SSL'u'use NNTP over SSL'b'Group'u'Group'b'has'u'has'b'articles, range'u'articles, range'b'{:7} {:20} {:42} ({})'u'{:7} {:20} {:42} ({})'u'nntplib'Common pathname manipulations, WindowsNT/95 version. + +Instead of importing this module directly, import os and refer to this +module as os.path. +.;C:\bindefpathnuldevnullgenericpathismountexpandvarssupports_unicode_filenamescommonpath_get_bothseps\/Normalize case of pathname. + + Makes all characters lowercase and all slashes into backslashes.Test whether a path is absolute\\?\colonresult_driveresult_pathp_drivep_pathSplit a pathname into drive/UNC sharepoint and relative path specifiers. + Returns a 2-tuple (drive_or_unc, path); either part may be empty. + + If you assign + result = splitdrive(p) + It is always true that: + result[0] + result[1] == p + + If the path contained a drive letter, drive_or_unc will contain everything + up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir") + + If the path contained a UNC path, the drive_or_unc will contain the host name + and share up to but not including the fourth directory separator character. + e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir") + + Paths cannot contain both a drive letter and a UNC path. + + normpSplit a pathname. + + Return tuple (head, tail) where tail is everything after the final slash. + Either part may be empty.Returns the final component of a pathnameReturns the directory component of a pathnameTest whether a path is a symbolic link. + This will always return false for Windows prior to 6.0. + Test whether a path exists. Returns True for broken symbolic links_getvolumepathnameTest whether a path is a mount point (a drive root, the root of a + share, or a mounted volume)Expand ~ and ~user constructs. + + If user or $HOME is unknown, do nothing.USERPROFILEuserhomeHOMEPATHHOMEDRIVEExpand shell variables of the forms $var, ${var} and %var%. + + Unknown variables are left unchanged._-varcharsbracerbracedollarenvironbpathlenNormalize path, eliminating double slashes, etc.\\.\special_prefixescomps_abspath_fallbackReturn the absolute version of a path as a fallback function in case + `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for + more. + + getcwdbReturn the absolute version of a path._getfinalpathname_nt_readlink_readlink_deep439043924393allowed_winerrorold_path_getfinalpathname_nonstrict19201921new_path\\?\UNC\unc_prefixnew_unc_prefix\\.\NULhad_prefixinitial_winerrorspathReturn a relative version of a pathno path specifiedstart_abspath_absstart_drivestart_restpath_drivepath_restpath is on mount %r, start on mount %rstart_listpath_liste1e2rel_listGiven a sequence of path names, returns the longest common sub-path.commonpath() arg is an empty sequencedrivesplitssplit_pathsCan't mix absolute and relative pathsPaths don't have the same drivecommon_isdir# Module 'ntpath' -- common operations on WinNT/Win95 pathnames# strings representing various path-related bits and pieces# These are primarily for export; internally, they are hardcoded.# Should be set before imports for resolving cyclic dependency.# Normalize the case of a pathname and map slashes to backslashes.# Other normalizations (such as optimizing '../' away) are not done# (this is done by normpath).# Return whether a path is absolute.# Trivial in Posix, harder on Windows.# For Windows it is absolute if it starts with a slash or backslash (current# volume), or if a pathname after the volume-letter-and-colon or UNC-resource# starts with a slash or backslash.# Paths beginning with \\?\ are always absolute, but do not# necessarily contain a drive.# Join two (or more) paths.#23780: Ensure compatible data type even if p is null.# Second path is absolute# Different drives => ignore the first path entirely# Same drive in different case# Second path is relative to the first## add separator between UNC and non-absolute path# Split a path in a drive specification (a drive letter followed by a# colon) and the path specification.# It is always true that drivespec + pathspec == p# is a UNC path:# vvvvvvvvvvvvvvvvvvvv drive letter or UNC path# \\machine\mountpoint\directory\etc\...# directory ^^^^^^^^^^^^^^^# a UNC path can't have two slashes in a row# (after the initial two)# Split a path in head (everything up to the last '/') and tail (the# rest). After the trailing '/' is stripped, the invariant# join(head, tail) == p holds.# The resulting head won't end in '/' unless it is the root.# set i to index beyond p's last slash# now tail has no slashes# remove trailing slashes from head, unless it's all slashes# Return the tail (basename) part of a path.# Return the head (dirname) part of a path.# Is a path a symbolic link?# This will always return false on systems where os.lstat doesn't exist.# Being true for dangling symbolic links is also useful.# Is a path a mount point?# Any drive letter root (eg c:\)# Any share UNC (eg \\server\share)# Any volume mounted on a filesystem folder# No one method detects all three situations. Historically we've lexically# detected drive letter roots and share UNCs. The canonical approach to# detecting mounted volumes (querying the reparse tag) fails for the most# common case: drive letter roots. The alternative which uses GetVolumePathName# fails if the drive letter is the result of a SUBST.# Expand paths beginning with '~' or '~user'.# '~' means $HOME; '~user' means that user's home directory.# If the path doesn't begin with '~', or if the user or $HOME is unknown,# the path is returned unchanged (leaving error reporting to whatever# function is called with the expanded path as argument).# See also module 'glob' for expansion of *, ? and [...] in pathnames.# (A function should also be defined to do full *sh-style environment# variable expansion.)#~user# Expand paths containing shell variable substitutions.# The following rules apply:# - no expansion within single quotes# - '$$' is translated into '$'# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%# - ${varname} is accepted.# - $varname is accepted.# - %varname% is accepted.# - varnames can be made out of letters, digits and the characters '_-'# (though is not verified in the ${varname} and %varname% cases)# XXX With COMMAND.COM you can use any characters in a variable name,# XXX except '^|<>='.# no expansion within single quotes# variable or '%'# variable or '$$'# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.# Previously, this function also truncated pathnames to 8+3 format,# but as this module is called "ntpath", that's obviously wrong!# in the case of paths with these prefixes:# \\.\ -> device names# \\?\ -> literal paths# do not do any normalization, but return the path# unchanged apart from the call to os.fspath()# collapse initial backslashes# If the path is now empty, substitute '.'# Return an absolute path.# not running on Windows - mock up something sensible# use native Windows method on Windows# realpath is a no-op on systems without _getfinalpathname support.# These error codes indicate that we should stop reading links and# return the path we currently have.# 1: ERROR_INVALID_FUNCTION# 2: ERROR_FILE_NOT_FOUND# 3: ERROR_DIRECTORY_NOT_FOUND# 5: ERROR_ACCESS_DENIED# 21: ERROR_NOT_READY (implies drive with no media)# 32: ERROR_SHARING_VIOLATION (probably an NTFS paging file)# 50: ERROR_NOT_SUPPORTED (implies no support for reparse points)# 67: ERROR_BAD_NET_NAME (implies remote server unavailable)# 87: ERROR_INVALID_PARAMETER# 4390: ERROR_NOT_A_REPARSE_POINT# 4392: ERROR_INVALID_REPARSE_DATA# 4393: ERROR_REPARSE_TAG_INVALID# Links may be relative, so resolve them against their# own location# If it's something other than a symlink, we don't know# what it's actually going to be resolved against, so# just return the old path.# Stop on reparse points that are not symlinks# These error codes indicate that we should stop resolving the path# and return the value we currently have.# 50: ERROR_NOT_SUPPORTED# 123: ERROR_INVALID_NAME# 1920: ERROR_CANT_ACCESS_FILE# 1921: ERROR_CANT_RESOLVE_FILENAME (implies unfollowable symlink)# Non-strict algorithm is to find as much of the target directory# as we can and join the rest.# The OS could not resolve this path fully, so we attempt# to follow the link ourselves. If we succeed, join the tail# and return.# If we fail to readlink(), let's keep traversing# TODO (bpo-38186): Request the real file name from the directory# entry using FindFirstFileW. For now, we will return the path# as best we have it# bpo-38081: Special case for realpath(b'nul')# bpo-38081: Special case for realpath('nul')# The path returned by _getfinalpathname will always start with \\?\ -# strip off that prefix unless it was already provided on the original# path.# For UNC paths, the prefix will actually be \\?\UNC\# Handle that case as well.# Ensure that the non-prefixed path resolves to the same path# If the path does not exist and originally did not exist, then# strip the prefix anyway.# Win9x family and earlier have no Unicode filename support.# Work out how much of the filepath is shared by start and path.# Return the longest common sub-path of the sequence of paths given as input.# The function is case-insensitive and 'separator-insensitive', i.e. if the# only difference between two paths is the use of '\' versus '/' as separator,# they are deemed to be equal.# However, the returned path will have the standard '\' separator (even if the# given paths had the alternative '/' separator) and will have the case of the# first path given in the sequence. Additionally, any trailing separator is# stripped from the returned path.# Check that all drive letters or UNC paths match. The check is made only# now otherwise type errors for mixing strings and bytes would not be# caught.# The genericpath.isdir implementation uses os.stat and checks the mode# attribute to tell whether or not the path is a directory.# This is overkill on Windows - just pass the path to GetFileAttributes# and check the attribute from there.# Use genericpath.isdir as imported above.b'Common pathname manipulations, WindowsNT/95 version. + +Instead of importing this module directly, import os and refer to this +module as os.path. +'u'Common pathname manipulations, WindowsNT/95 version. + +Instead of importing this module directly, import os and refer to this +module as os.path. +'b'.;C:\bin'u'.;C:\bin'b'nul'u'nul'b'normcase'u'normcase'b'isabs'u'isabs'b'join'u'join'b'splitdrive'u'splitdrive'b'split'u'split'b'splitext'u'splitext'b'basename'u'basename'b'dirname'u'dirname'b'islink'u'islink'b'lexists'u'lexists'b'ismount'u'ismount'b'expanduser'u'expanduser'b'expandvars'u'expandvars'b'normpath'u'normpath'b'abspath'u'abspath'b'curdir'u'curdir'b'pardir'u'pardir'b'pathsep'u'pathsep'b'defpath'u'defpath'b'altsep'u'altsep'b'extsep'u'extsep'b'devnull'u'devnull'b'realpath'u'realpath'b'supports_unicode_filenames'u'supports_unicode_filenames'b'relpath'u'relpath'b'commonpath'u'commonpath'b'\/'u'\/'b'Normalize case of pathname. + + Makes all characters lowercase and all slashes into backslashes.'u'Normalize case of pathname. + + Makes all characters lowercase and all slashes into backslashes.'b'Test whether a path is absolute'u'Test whether a path is absolute'b'\\?\'u'\\?\'b'Split a pathname into drive/UNC sharepoint and relative path specifiers. + Returns a 2-tuple (drive_or_unc, path); either part may be empty. + + If you assign + result = splitdrive(p) + It is always true that: + result[0] + result[1] == p + + If the path contained a drive letter, drive_or_unc will contain everything + up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir") + + If the path contained a UNC path, the drive_or_unc will contain the host name + and share up to but not including the fourth directory separator character. + e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir") + + Paths cannot contain both a drive letter and a UNC path. + + 'u'Split a pathname into drive/UNC sharepoint and relative path specifiers. + Returns a 2-tuple (drive_or_unc, path); either part may be empty. + + If you assign + result = splitdrive(p) + It is always true that: + result[0] + result[1] == p + + If the path contained a drive letter, drive_or_unc will contain everything + up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir") + + If the path contained a UNC path, the drive_or_unc will contain the host name + and share up to but not including the fourth directory separator character. + e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir") + + Paths cannot contain both a drive letter and a UNC path. + + 'b'Split a pathname. + + Return tuple (head, tail) where tail is everything after the final slash. + Either part may be empty.'u'Split a pathname. + + Return tuple (head, tail) where tail is everything after the final slash. + Either part may be empty.'b'Returns the final component of a pathname'u'Returns the final component of a pathname'b'Returns the directory component of a pathname'u'Returns the directory component of a pathname'b'Test whether a path is a symbolic link. + This will always return false for Windows prior to 6.0. + 'u'Test whether a path is a symbolic link. + This will always return false for Windows prior to 6.0. + 'b'Test whether a path exists. Returns True for broken symbolic links'u'Test whether a path exists. Returns True for broken symbolic links'b'Test whether a path is a mount point (a drive root, the root of a + share, or a mounted volume)'u'Test whether a path is a mount point (a drive root, the root of a + share, or a mounted volume)'b'Expand ~ and ~user constructs. + + If user or $HOME is unknown, do nothing.'u'Expand ~ and ~user constructs. + + If user or $HOME is unknown, do nothing.'b'USERPROFILE'u'USERPROFILE'b'HOMEPATH'u'HOMEPATH'b'HOMEDRIVE'u'HOMEDRIVE'b'Expand shell variables of the forms $var, ${var} and %var%. + + Unknown variables are left unchanged.'u'Expand shell variables of the forms $var, ${var} and %var%. + + Unknown variables are left unchanged.'b'_-'u'_-'b'environb'u'environb'b'Normalize path, eliminating double slashes, etc.'u'Normalize path, eliminating double slashes, etc.'b'\\.\'u'\\.\'b'Return the absolute version of a path as a fallback function in case + `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for + more. + + 'u'Return the absolute version of a path as a fallback function in case + `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for + more. + + 'b'Return the absolute version of a path.'u'Return the absolute version of a path.'b'\\?\UNC\'b'\\.\NUL'u'\\?\UNC\'u'\\.\NUL'b'getwindowsversion'u'getwindowsversion'b'Return a relative version of a path'u'Return a relative version of a path'b'no path specified'u'no path specified'b'path is on mount %r, start on mount %r'u'path is on mount %r, start on mount %r'b'Given a sequence of path names, returns the longest common sub-path.'u'Given a sequence of path names, returns the longest common sub-path.'b'commonpath() arg is an empty sequence'u'commonpath() arg is an empty sequence'b'Can't mix absolute and relative paths'u'Can't mix absolute and relative paths'b'Paths don't have the same drive'u'Paths don't have the same drive'u'ntpath'Convert a NT pathname to a file URL and vice versa. + +This module only exists to provide OS-specific code +for urllib.requests, thus do not use directly. +OS-specific conversion from a relative URL of the 'file' scheme + to a file system path; not recommended for general use.////componentsBad URL: OS-specific conversion from a file system path to a relative URL + of the 'file' scheme; not recommended for general use.UNC\Bad path: ///# Testing is done through test_urllib.# e.g.# ///C|/foo/bar/spam.foo# and# ///C:/foo/bar/spam.foo# become# C:\foo\bar\spam.foo# Windows itself uses ":" even in URLs.# No drive specifier, just convert slashes# path is something like ////host/path/on/remote/host# convert this to \\host\path\on\remote\host# (notice halving of slashes at the start of the path)# make sure not to convert quoted slashes :-)# Issue #11474 - handing url such as |c/|# becomes# First, clean up some special forms. We are going to sacrifice# the additional information anyway# No drive specifier, just convert slashes and quote the name# path is something like \\host\path\on\remote\host# convert this to ////host/path/on/remote/host# (notice doubling of slashes at the start of the path)b'Convert a NT pathname to a file URL and vice versa. + +This module only exists to provide OS-specific code +for urllib.requests, thus do not use directly. +'u'Convert a NT pathname to a file URL and vice versa. + +This module only exists to provide OS-specific code +for urllib.requests, thus do not use directly. +'b'OS-specific conversion from a relative URL of the 'file' scheme + to a file system path; not recommended for general use.'u'OS-specific conversion from a relative URL of the 'file' scheme + to a file system path; not recommended for general use.'b'////'u'////'b'Bad URL: 'u'Bad URL: 'b'OS-specific conversion from a file system path to a relative URL + of the 'file' scheme; not recommended for general use.'u'OS-specific conversion from a file system path to a relative URL + of the 'file' scheme; not recommended for general use.'b'UNC\'u'UNC\'b'Bad path: 'u'Bad path: 'b'///'u'///'u'nturl2path'Abstract Base Classes (ABCs) for numbers, according to PEP 3141. + +TODO: Fill out more detailed documentation on the operators.RealIntegralAll numbers inherit from this class. + + If you just want to check if an argument x is a number, without + caring what kind, use isinstance(x, Number). + Complex defines the operations that work on the builtin complex type. + + In short, those are: a conversion to complex, .real, .imag, +, -, + *, /, abs(), .conjugate, ==, and !=. + + If it is given heterogeneous arguments, and doesn't have special + knowledge about them, it should fall back to the builtin complex + type as described below. + Return a builtin complex instance. Called for complex(self).True if self != 0. Called for bool(self).Retrieve the real component of this number. + + This should subclass Real. + Retrieve the imaginary component of this number. + + This should subclass Real. + self + otherother + self-self+selfself - otherother - selfself * otherother * selfself / other: Should promote to float when necessary.other / selfself**exponent; should promote to float or complex when necessary.base ** selfReturns the Real distance from 0. Called for abs(self).(x+y*i).conjugate() returns (x-y*i).self == otherTo Complex, Real adds the operations that work on real numbers. + + In short, those are: a conversion to float, trunc(), divmod, + %, <, <=, >, and >=. + + Real also provides defaults for the derived operations. + Any Real can be converted to a native float object. + + Called for float(self).trunc(self): Truncates self to an Integral. + + Returns an Integral i such that: + * i>0 iff self>0; + * abs(i) <= abs(self); + * for any Integral j satisfying the first two conditions, + abs(i) >= abs(j) [i.e. i has "maximal" abs among those]. + i.e. "truncate towards 0". + Finds the greatest Integral <= self.Finds the least Integral >= self.ndigitsRounds self to ndigits decimal places, defaulting to 0. + + If ndigits is omitted or None, returns an Integral, otherwise + returns a Real. Rounds half toward even. + divmod(self, other): The pair (self // other, self % other). + + Sometimes this can be computed faster than the pair of + operations. + divmod(other, self): The pair (self // other, self % other). + + Sometimes this can be computed faster than the pair of + operations. + self // other: The floor() of self/other.other // self: The floor() of other/self.self % otherother % selfself < other + + < on Reals defines a total ordering, except perhaps for NaN.self <= othercomplex(self) == complex(float(self), 0)Real numbers are their real component.Real numbers have no imaginary component.Conjugate is a no-op for Reals..numerator and .denominator should be in lowest terms.float(self) = self.numerator / self.denominator + + It's important that this conversion use the integer's "true" + division rather than casting one side to float before dividing + so that ratios of huge integers convert without overflowing. + + Integral adds a conversion to int and the bit-string operations.int(self)Called whenever an index is needed, such as in slicingself ** exponent % modulus, but maybe faster. + + Accept the modulus argument if you want to support the + 3-argument version of pow(). Raise a TypeError if exponent < 0 + or any argument isn't Integral. Otherwise, just implement the + 2-argument version described in Complex. + self << otherother << selfself >> otherother >> selfself & otherother & selfself ^ otherother ^ selfself | otherother | self~selffloat(self) == float(int(self))Integers are their own numerators.Integers have a denominator of 1.# Concrete numeric types must provide their own hash implementation## Notes on Decimal## ----------------## Decimal has all of the methods specified by the Real abc, but it should## not be registered as a Real because decimals do not interoperate with## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But,## abstract reals are expected to interoperate (i.e. R1 + R2 should be## expected to work if R1 and R2 are both Reals).# Concrete implementations of Complex abstract methods.# Concrete implementation of Real's conversion to float.# Concrete implementations of Rational and Real abstract methods.b'Abstract Base Classes (ABCs) for numbers, according to PEP 3141. + +TODO: Fill out more detailed documentation on the operators.'u'Abstract Base Classes (ABCs) for numbers, according to PEP 3141. + +TODO: Fill out more detailed documentation on the operators.'b'Number'u'Number'b'Complex'u'Complex'b'Real'u'Real'b'Rational'u'Rational'b'Integral'u'Integral'b'All numbers inherit from this class. + + If you just want to check if an argument x is a number, without + caring what kind, use isinstance(x, Number). + 'u'All numbers inherit from this class. + + If you just want to check if an argument x is a number, without + caring what kind, use isinstance(x, Number). + 'b'Complex defines the operations that work on the builtin complex type. + + In short, those are: a conversion to complex, .real, .imag, +, -, + *, /, abs(), .conjugate, ==, and !=. + + If it is given heterogeneous arguments, and doesn't have special + knowledge about them, it should fall back to the builtin complex + type as described below. + 'u'Complex defines the operations that work on the builtin complex type. + + In short, those are: a conversion to complex, .real, .imag, +, -, + *, /, abs(), .conjugate, ==, and !=. + + If it is given heterogeneous arguments, and doesn't have special + knowledge about them, it should fall back to the builtin complex + type as described below. + 'b'Return a builtin complex instance. Called for complex(self).'u'Return a builtin complex instance. Called for complex(self).'b'True if self != 0. Called for bool(self).'u'True if self != 0. Called for bool(self).'b'Retrieve the real component of this number. + + This should subclass Real. + 'u'Retrieve the real component of this number. + + This should subclass Real. + 'b'Retrieve the imaginary component of this number. + + This should subclass Real. + 'u'Retrieve the imaginary component of this number. + + This should subclass Real. + 'b'self + other'u'self + other'b'other + self'u'other + self'b'-self'u'-self'b'+self'u'+self'b'self - other'u'self - other'b'other - self'u'other - self'b'self * other'u'self * other'b'other * self'u'other * self'b'self / other: Should promote to float when necessary.'u'self / other: Should promote to float when necessary.'b'other / self'u'other / self'b'self**exponent; should promote to float or complex when necessary.'u'self**exponent; should promote to float or complex when necessary.'b'base ** self'u'base ** self'b'Returns the Real distance from 0. Called for abs(self).'u'Returns the Real distance from 0. Called for abs(self).'b'(x+y*i).conjugate() returns (x-y*i).'u'(x+y*i).conjugate() returns (x-y*i).'b'self == other'u'self == other'b'To Complex, Real adds the operations that work on real numbers. + + In short, those are: a conversion to float, trunc(), divmod, + %, <, <=, >, and >=. + + Real also provides defaults for the derived operations. + 'u'To Complex, Real adds the operations that work on real numbers. + + In short, those are: a conversion to float, trunc(), divmod, + %, <, <=, >, and >=. + + Real also provides defaults for the derived operations. + 'b'Any Real can be converted to a native float object. + + Called for float(self).'u'Any Real can be converted to a native float object. + + Called for float(self).'b'trunc(self): Truncates self to an Integral. + + Returns an Integral i such that: + * i>0 iff self>0; + * abs(i) <= abs(self); + * for any Integral j satisfying the first two conditions, + abs(i) >= abs(j) [i.e. i has "maximal" abs among those]. + i.e. "truncate towards 0". + 'u'trunc(self): Truncates self to an Integral. + + Returns an Integral i such that: + * i>0 iff self>0; + * abs(i) <= abs(self); + * for any Integral j satisfying the first two conditions, + abs(i) >= abs(j) [i.e. i has "maximal" abs among those]. + i.e. "truncate towards 0". + 'b'Finds the greatest Integral <= self.'u'Finds the greatest Integral <= self.'b'Finds the least Integral >= self.'u'Finds the least Integral >= self.'b'Rounds self to ndigits decimal places, defaulting to 0. + + If ndigits is omitted or None, returns an Integral, otherwise + returns a Real. Rounds half toward even. + 'u'Rounds self to ndigits decimal places, defaulting to 0. + + If ndigits is omitted or None, returns an Integral, otherwise + returns a Real. Rounds half toward even. + 'b'divmod(self, other): The pair (self // other, self % other). + + Sometimes this can be computed faster than the pair of + operations. + 'u'divmod(self, other): The pair (self // other, self % other). + + Sometimes this can be computed faster than the pair of + operations. + 'b'divmod(other, self): The pair (self // other, self % other). + + Sometimes this can be computed faster than the pair of + operations. + 'u'divmod(other, self): The pair (self // other, self % other). + + Sometimes this can be computed faster than the pair of + operations. + 'b'self // other: The floor() of self/other.'u'self // other: The floor() of self/other.'b'other // self: The floor() of other/self.'u'other // self: The floor() of other/self.'b'self % other'u'self % other'b'other % self'u'other % self'b'self < other + + < on Reals defines a total ordering, except perhaps for NaN.'u'self < other + + < on Reals defines a total ordering, except perhaps for NaN.'b'self <= other'u'self <= other'b'complex(self) == complex(float(self), 0)'u'complex(self) == complex(float(self), 0)'b'Real numbers are their real component.'u'Real numbers are their real component.'b'Real numbers have no imaginary component.'u'Real numbers have no imaginary component.'b'Conjugate is a no-op for Reals.'u'Conjugate is a no-op for Reals.'b'.numerator and .denominator should be in lowest terms.'u'.numerator and .denominator should be in lowest terms.'b'float(self) = self.numerator / self.denominator + + It's important that this conversion use the integer's "true" + division rather than casting one side to float before dividing + so that ratios of huge integers convert without overflowing. + + 'u'float(self) = self.numerator / self.denominator + + It's important that this conversion use the integer's "true" + division rather than casting one side to float before dividing + so that ratios of huge integers convert without overflowing. + + 'b'Integral adds a conversion to int and the bit-string operations.'u'Integral adds a conversion to int and the bit-string operations.'b'int(self)'u'int(self)'b'Called whenever an index is needed, such as in slicing'u'Called whenever an index is needed, such as in slicing'b'self ** exponent % modulus, but maybe faster. + + Accept the modulus argument if you want to support the + 3-argument version of pow(). Raise a TypeError if exponent < 0 + or any argument isn't Integral. Otherwise, just implement the + 2-argument version described in Complex. + 'u'self ** exponent % modulus, but maybe faster. + + Accept the modulus argument if you want to support the + 3-argument version of pow(). Raise a TypeError if exponent < 0 + or any argument isn't Integral. Otherwise, just implement the + 2-argument version described in Complex. + 'b'self << other'u'self << other'b'other << self'u'other << self'b'self >> other'u'self >> other'b'other >> self'u'other >> self'b'self & other'u'self & other'b'other & self'u'other & self'b'self ^ other'u'self ^ other'b'other ^ self'u'other ^ self'b'self | other'u'self | other'b'other | self'u'other | self'b'~self'u'~self'b'float(self) == float(int(self))'u'float(self) == float(int(self))'b'Integers are their own numerators.'u'Integers are their own numerators.'b'Integers have a denominator of 1.'u'Integers have a denominator of 1.'u'numbers' +opcode module - potentially shared between dis and other modules which +operate on bytecodes (e.g. peephole optimizers). +hasnargsnot inis notexception matchBAD<%r>def_opname_opjrel_opjabs_opPOP_TOPROT_TWOROT_THREEDUP_TOPDUP_TOP_TWOROT_FOURNOPUNARY_POSITIVEUNARY_NEGATIVEUNARY_NOTUNARY_INVERTBINARY_MATRIX_MULTIPLYINPLACE_MATRIX_MULTIPLYBINARY_POWERBINARY_MULTIPLYBINARY_MODULOBINARY_ADDBINARY_SUBTRACTBINARY_SUBSCRBINARY_FLOOR_DIVIDEBINARY_TRUE_DIVIDEINPLACE_FLOOR_DIVIDEINPLACE_TRUE_DIVIDEGET_AITERGET_ANEXTBEFORE_ASYNC_WITHBEGIN_FINALLYEND_ASYNC_FORINPLACE_ADDINPLACE_SUBTRACTINPLACE_MULTIPLYINPLACE_MODULOSTORE_SUBSCRDELETE_SUBSCRBINARY_LSHIFTBINARY_RSHIFTBINARY_ANDBINARY_XORBINARY_ORINPLACE_POWERGET_ITERGET_YIELD_FROM_ITERPRINT_EXPRLOAD_BUILD_CLASSYIELD_FROMGET_AWAITABLEINPLACE_LSHIFTINPLACE_RSHIFTINPLACE_ANDINPLACE_XORINPLACE_ORWITH_CLEANUP_STARTWITH_CLEANUP_FINISHRETURN_VALUEIMPORT_STARSETUP_ANNOTATIONSYIELD_VALUEPOP_BLOCKEND_FINALLYPOP_EXCEPTSTORE_NAMEDELETE_NAMEUNPACK_SEQUENCEFOR_ITERUNPACK_EXSTORE_ATTRDELETE_ATTRSTORE_GLOBALDELETE_GLOBALLOAD_CONSTLOAD_NAMEBUILD_TUPLEBUILD_LISTBUILD_SETBUILD_MAPLOAD_ATTR106COMPARE_OP107IMPORT_NAMEIMPORT_FROM109JUMP_FORWARDJUMP_IF_FALSE_OR_POPJUMP_IF_TRUE_OR_POPJUMP_ABSOLUTEPOP_JUMP_IF_FALSEPOP_JUMP_IF_TRUELOAD_GLOBAL116SETUP_FINALLY122LOAD_FAST124STORE_FASTDELETE_FAST126RAISE_VARARGSCALL_FUNCTIONBUILD_SLICELOAD_CLOSURELOAD_DEREFSTORE_DEREFDELETE_DEREFCALL_FUNCTION_KWCALL_FUNCTION_EXSETUP_WITHLIST_APPENDSET_ADDMAP_ADDLOAD_CLASSDEREFBUILD_LIST_UNPACKBUILD_MAP_UNPACKBUILD_MAP_UNPACK_WITH_CALLBUILD_TUPLE_UNPACKBUILD_SET_UNPACKSETUP_ASYNC_WITHBUILD_CONST_KEY_MAPBUILD_STRINGBUILD_TUPLE_UNPACK_WITH_CALLLOAD_METHODCALL_METHODCALL_FINALLYPOP_FINALLY# It's a chicken-and-egg I'm afraid:# We're imported before _opcode's made.# With exception unheeded# (stack_effect is not needed)# Both our chickens and eggs are allayed.# --Larry Hastings, 2013/11/23# unused# Instruction opcodes for compiled code# Blank lines correspond to available opcodes# Opcodes from here have an argument:# Index in name list# ""# Number of tuple items# Index in const list# Number of list items# Number of set items# Number of dict entries# Comparison operator# Number of bytes to skip# Target byte offset from beginning of code# Distance to target address# Local variable number# Number of raise arguments (1, 2, or 3)# #args# Flags# Number of items# #args + #kwargsb' +opcode module - potentially shared between dis and other modules which +operate on bytecodes (e.g. peephole optimizers). +'u' +opcode module - potentially shared between dis and other modules which +operate on bytecodes (e.g. peephole optimizers). +'b'cmp_op'u'cmp_op'b'hasconst'u'hasconst'b'hasname'u'hasname'b'hasjrel'u'hasjrel'b'hasjabs'u'hasjabs'b'haslocal'u'haslocal'b'hascompare'u'hascompare'b'hasfree'u'hasfree'b'opname'u'opname'b'opmap'u'opmap'b'HAVE_ARGUMENT'u'HAVE_ARGUMENT'b'EXTENDED_ARG'u'EXTENDED_ARG'b'hasnargs'u'hasnargs'b'stack_effect'u'stack_effect'b'not in'u'not in'b'is not'u'is not'b'exception match'u'exception match'b'BAD'u'BAD'b'<%r>'u'<%r>'b'POP_TOP'u'POP_TOP'b'ROT_TWO'u'ROT_TWO'b'ROT_THREE'u'ROT_THREE'b'DUP_TOP'u'DUP_TOP'b'DUP_TOP_TWO'u'DUP_TOP_TWO'b'ROT_FOUR'u'ROT_FOUR'b'NOP'u'NOP'b'UNARY_POSITIVE'u'UNARY_POSITIVE'b'UNARY_NEGATIVE'u'UNARY_NEGATIVE'b'UNARY_NOT'u'UNARY_NOT'b'UNARY_INVERT'u'UNARY_INVERT'b'BINARY_MATRIX_MULTIPLY'u'BINARY_MATRIX_MULTIPLY'b'INPLACE_MATRIX_MULTIPLY'u'INPLACE_MATRIX_MULTIPLY'b'BINARY_POWER'u'BINARY_POWER'b'BINARY_MULTIPLY'u'BINARY_MULTIPLY'b'BINARY_MODULO'u'BINARY_MODULO'b'BINARY_ADD'u'BINARY_ADD'b'BINARY_SUBTRACT'u'BINARY_SUBTRACT'b'BINARY_SUBSCR'u'BINARY_SUBSCR'b'BINARY_FLOOR_DIVIDE'u'BINARY_FLOOR_DIVIDE'b'BINARY_TRUE_DIVIDE'u'BINARY_TRUE_DIVIDE'b'INPLACE_FLOOR_DIVIDE'u'INPLACE_FLOOR_DIVIDE'b'INPLACE_TRUE_DIVIDE'u'INPLACE_TRUE_DIVIDE'b'GET_AITER'u'GET_AITER'b'GET_ANEXT'u'GET_ANEXT'b'BEFORE_ASYNC_WITH'u'BEFORE_ASYNC_WITH'b'BEGIN_FINALLY'u'BEGIN_FINALLY'b'END_ASYNC_FOR'u'END_ASYNC_FOR'b'INPLACE_ADD'u'INPLACE_ADD'b'INPLACE_SUBTRACT'u'INPLACE_SUBTRACT'b'INPLACE_MULTIPLY'u'INPLACE_MULTIPLY'b'INPLACE_MODULO'u'INPLACE_MODULO'b'STORE_SUBSCR'u'STORE_SUBSCR'b'DELETE_SUBSCR'u'DELETE_SUBSCR'b'BINARY_LSHIFT'u'BINARY_LSHIFT'b'BINARY_RSHIFT'u'BINARY_RSHIFT'b'BINARY_AND'u'BINARY_AND'b'BINARY_XOR'u'BINARY_XOR'b'BINARY_OR'u'BINARY_OR'b'INPLACE_POWER'u'INPLACE_POWER'b'GET_ITER'u'GET_ITER'b'GET_YIELD_FROM_ITER'u'GET_YIELD_FROM_ITER'b'PRINT_EXPR'u'PRINT_EXPR'b'LOAD_BUILD_CLASS'u'LOAD_BUILD_CLASS'b'YIELD_FROM'u'YIELD_FROM'b'GET_AWAITABLE'u'GET_AWAITABLE'b'INPLACE_LSHIFT'u'INPLACE_LSHIFT'b'INPLACE_RSHIFT'u'INPLACE_RSHIFT'b'INPLACE_AND'u'INPLACE_AND'b'INPLACE_XOR'u'INPLACE_XOR'b'INPLACE_OR'u'INPLACE_OR'b'WITH_CLEANUP_START'u'WITH_CLEANUP_START'b'WITH_CLEANUP_FINISH'u'WITH_CLEANUP_FINISH'b'RETURN_VALUE'u'RETURN_VALUE'b'IMPORT_STAR'u'IMPORT_STAR'b'SETUP_ANNOTATIONS'u'SETUP_ANNOTATIONS'b'YIELD_VALUE'u'YIELD_VALUE'b'POP_BLOCK'u'POP_BLOCK'b'END_FINALLY'u'END_FINALLY'b'POP_EXCEPT'u'POP_EXCEPT'b'STORE_NAME'u'STORE_NAME'b'DELETE_NAME'u'DELETE_NAME'b'UNPACK_SEQUENCE'u'UNPACK_SEQUENCE'b'FOR_ITER'u'FOR_ITER'b'UNPACK_EX'u'UNPACK_EX'b'STORE_ATTR'u'STORE_ATTR'b'DELETE_ATTR'u'DELETE_ATTR'b'STORE_GLOBAL'u'STORE_GLOBAL'b'DELETE_GLOBAL'u'DELETE_GLOBAL'b'LOAD_CONST'u'LOAD_CONST'b'LOAD_NAME'u'LOAD_NAME'b'BUILD_TUPLE'u'BUILD_TUPLE'b'BUILD_LIST'u'BUILD_LIST'b'BUILD_SET'u'BUILD_SET'b'BUILD_MAP'u'BUILD_MAP'b'LOAD_ATTR'u'LOAD_ATTR'b'COMPARE_OP'u'COMPARE_OP'b'IMPORT_NAME'u'IMPORT_NAME'b'IMPORT_FROM'u'IMPORT_FROM'b'JUMP_FORWARD'u'JUMP_FORWARD'b'JUMP_IF_FALSE_OR_POP'u'JUMP_IF_FALSE_OR_POP'b'JUMP_IF_TRUE_OR_POP'u'JUMP_IF_TRUE_OR_POP'b'JUMP_ABSOLUTE'u'JUMP_ABSOLUTE'b'POP_JUMP_IF_FALSE'u'POP_JUMP_IF_FALSE'b'POP_JUMP_IF_TRUE'u'POP_JUMP_IF_TRUE'b'LOAD_GLOBAL'u'LOAD_GLOBAL'b'SETUP_FINALLY'u'SETUP_FINALLY'b'LOAD_FAST'u'LOAD_FAST'b'STORE_FAST'u'STORE_FAST'b'DELETE_FAST'u'DELETE_FAST'b'RAISE_VARARGS'u'RAISE_VARARGS'b'CALL_FUNCTION'u'CALL_FUNCTION'b'BUILD_SLICE'u'BUILD_SLICE'b'LOAD_CLOSURE'u'LOAD_CLOSURE'b'LOAD_DEREF'u'LOAD_DEREF'b'STORE_DEREF'u'STORE_DEREF'b'DELETE_DEREF'u'DELETE_DEREF'b'CALL_FUNCTION_KW'u'CALL_FUNCTION_KW'b'CALL_FUNCTION_EX'u'CALL_FUNCTION_EX'b'SETUP_WITH'u'SETUP_WITH'b'LIST_APPEND'u'LIST_APPEND'b'SET_ADD'u'SET_ADD'b'MAP_ADD'u'MAP_ADD'b'LOAD_CLASSDEREF'u'LOAD_CLASSDEREF'b'BUILD_LIST_UNPACK'u'BUILD_LIST_UNPACK'b'BUILD_MAP_UNPACK'u'BUILD_MAP_UNPACK'b'BUILD_MAP_UNPACK_WITH_CALL'u'BUILD_MAP_UNPACK_WITH_CALL'b'BUILD_TUPLE_UNPACK'u'BUILD_TUPLE_UNPACK'b'BUILD_SET_UNPACK'u'BUILD_SET_UNPACK'b'SETUP_ASYNC_WITH'u'SETUP_ASYNC_WITH'b'BUILD_CONST_KEY_MAP'u'BUILD_CONST_KEY_MAP'b'BUILD_STRING'u'BUILD_STRING'b'BUILD_TUPLE_UNPACK_WITH_CALL'u'BUILD_TUPLE_UNPACK_WITH_CALL'b'LOAD_METHOD'u'LOAD_METHOD'b'CALL_METHOD'u'CALL_METHOD'b'CALL_FINALLY'u'CALL_FINALLY'b'POP_FINALLY'u'POP_FINALLY'u'opcode' +Operator Interface + +This module exports a set of functions corresponding to the intrinsic +operators of Python. For example, operator.add(x, y) is equivalent +to the expression x+y. The function names are those used for special +methods; variants without leading and trailing '__' are also provided +for convenience. + +This is the pure Python implementation of the module. +_absSame as a < b.Same as a <= b.Same as a == b.Same as a != b.Same as a >= b.Same as a > b.Same as not a.Return True if a is true, False otherwise.Same as a is b.Same as a is not b.Same as abs(a).Same as a + b.Same as a & b.Same as a // b.Same as a.__index__().Same as ~a.Same as a << b.Same as a % b.Same as a * b.Same as a @ b.Same as -a.Same as a | b.Same as +a.Same as a ** b.Same as a >> b.Same as a - b.Same as a / b.Same as a ^ b.Same as a + b, for a and b sequences.'%s' object can't be concatenatedSame as b in a (note reversed operands).Return the number of times b occurs in a.Same as del a[b].Same as a[b].Return the first index of b in a.sequence.index(x): x not in sequenceSame as a[b] = c. + Return an estimate of the number of items in obj. + This is useful for presizing containers when building from an iterable. + + If the object supports len(), the result will be exact. Otherwise, it may + over- or under-estimate by an arbitrary amount. The result will be an + integer >= 0. + '%s' object cannot be interpreted as an integerhint__length_hint__ must be integer, not %s__length_hint__() should return >= 0 + Return a callable object that fetches the given attribute(s) from its operand. + After f = attrgetter('name'), the call f(r) returns r.name. + After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date). + After h = attrgetter('name.first', 'name.last'), the call h(r) returns + (r.name.first, r.name.last). + _attrsattribute name must be a stringgetters + Return a callable object that fetches the given item(s) from its operand. + After f = itemgetter(2), the call f(r) returns r[2]. + After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]) + _items + Return a callable object that calls the given method on its operand. + After f = methodcaller('name'), the call f(r) returns r.name(). + After g = methodcaller('name', 'date', foo=1), the call g(r) returns + r.name('date', foo=1). + _kwargsmethod name must be a stringSame as a += b.Same as a &= b.Same as a += b, for a and b sequences.Same as a //= b.Same as a <<= b.Same as a %= b.Same as a *= b.Same as a @= b.Same as a |= b.Same as a **= b.Same as a >>= b.Same as a -= b.Same as a /= b.Same as a ^= b.__not____inv____concat____iconcat__# Comparison Operations *******************************************************## Logical Operations **********************************************************## Mathematical/Bitwise Operations *********************************************## Sequence Operations *********************************************************## Generalized Lookup Objects **************************************************## In-place Operations *********************************************************## All of these "__func__ = func" assignments have to happen after importing# from _operator to make sure they're set to the right functionb' +Operator Interface + +This module exports a set of functions corresponding to the intrinsic +operators of Python. For example, operator.add(x, y) is equivalent +to the expression x+y. The function names are those used for special +methods; variants without leading and trailing '__' are also provided +for convenience. + +This is the pure Python implementation of the module. +'u' +Operator Interface + +This module exports a set of functions corresponding to the intrinsic +operators of Python. For example, operator.add(x, y) is equivalent +to the expression x+y. The function names are those used for special +methods; variants without leading and trailing '__' are also provided +for convenience. + +This is the pure Python implementation of the module. +'b'abs'u'abs'b'and_'u'and_'b'attrgetter'u'attrgetter'b'concat'u'concat'b'contains'u'contains'b'countOf'u'countOf'b'delitem'u'delitem'b'eq'u'eq'b'floordiv'u'floordiv'b'getitem'u'getitem'b'iadd'u'iadd'b'iand'u'iand'b'iconcat'u'iconcat'b'ifloordiv'u'ifloordiv'b'ilshift'u'ilshift'b'imatmul'u'imatmul'b'imod'u'imod'b'imul'u'imul'b'indexOf'u'indexOf'b'inv'u'inv'b'invert'u'invert'b'ior'u'ior'b'ipow'u'ipow'b'irshift'u'irshift'b'is_'u'is_'b'is_not'u'is_not'b'isub'u'isub'b'itemgetter'u'itemgetter'b'itruediv'u'itruediv'b'ixor'u'ixor'b'length_hint'u'length_hint'b'lshift'u'lshift'b'matmul'u'matmul'b'methodcaller'u'methodcaller'b'mod'u'mod'b'mul'u'mul'b'neg'u'neg'b'not_'u'not_'b'or_'u'or_'b'pos'u'pos'b'pow'u'pow'b'rshift'u'rshift'b'setitem'u'setitem'b'truediv'u'truediv'b'truth'u'truth'b'xor'u'xor'b'Same as a < b.'u'Same as a < b.'b'Same as a <= b.'u'Same as a <= b.'b'Same as a == b.'u'Same as a == b.'b'Same as a != b.'u'Same as a != b.'b'Same as a >= b.'u'Same as a >= b.'b'Same as a > b.'u'Same as a > b.'b'Same as not a.'u'Same as not a.'b'Return True if a is true, False otherwise.'u'Return True if a is true, False otherwise.'b'Same as a is b.'u'Same as a is b.'b'Same as a is not b.'u'Same as a is not b.'b'Same as abs(a).'u'Same as abs(a).'b'Same as a + b.'u'Same as a + b.'b'Same as a & b.'u'Same as a & b.'b'Same as a // b.'u'Same as a // b.'b'Same as a.__index__().'u'Same as a.__index__().'b'Same as ~a.'u'Same as ~a.'b'Same as a << b.'u'Same as a << b.'b'Same as a % b.'u'Same as a % b.'b'Same as a * b.'u'Same as a * b.'b'Same as a @ b.'u'Same as a @ b.'b'Same as -a.'u'Same as -a.'b'Same as a | b.'u'Same as a | b.'b'Same as +a.'u'Same as +a.'b'Same as a ** b.'u'Same as a ** b.'b'Same as a >> b.'u'Same as a >> b.'b'Same as a - b.'u'Same as a - b.'b'Same as a / b.'u'Same as a / b.'b'Same as a ^ b.'u'Same as a ^ b.'b'Same as a + b, for a and b sequences.'u'Same as a + b, for a and b sequences.'b'__getitem__'u'__getitem__'b''%s' object can't be concatenated'u''%s' object can't be concatenated'b'Same as b in a (note reversed operands).'u'Same as b in a (note reversed operands).'b'Return the number of times b occurs in a.'u'Return the number of times b occurs in a.'b'Same as del a[b].'u'Same as del a[b].'b'Same as a[b].'u'Same as a[b].'b'Return the first index of b in a.'u'Return the first index of b in a.'b'sequence.index(x): x not in sequence'u'sequence.index(x): x not in sequence'b'Same as a[b] = c.'u'Same as a[b] = c.'b' + Return an estimate of the number of items in obj. + This is useful for presizing containers when building from an iterable. + + If the object supports len(), the result will be exact. Otherwise, it may + over- or under-estimate by an arbitrary amount. The result will be an + integer >= 0. + 'u' + Return an estimate of the number of items in obj. + This is useful for presizing containers when building from an iterable. + + If the object supports len(), the result will be exact. Otherwise, it may + over- or under-estimate by an arbitrary amount. The result will be an + integer >= 0. + 'b''%s' object cannot be interpreted as an integer'u''%s' object cannot be interpreted as an integer'b'__length_hint__ must be integer, not %s'u'__length_hint__ must be integer, not %s'b'__length_hint__() should return >= 0'u'__length_hint__() should return >= 0'b' + Return a callable object that fetches the given attribute(s) from its operand. + After f = attrgetter('name'), the call f(r) returns r.name. + After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date). + After h = attrgetter('name.first', 'name.last'), the call h(r) returns + (r.name.first, r.name.last). + 'u' + Return a callable object that fetches the given attribute(s) from its operand. + After f = attrgetter('name'), the call f(r) returns r.name. + After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date). + After h = attrgetter('name.first', 'name.last'), the call h(r) returns + (r.name.first, r.name.last). + 'b'_attrs'u'_attrs'b'_call'u'_call'b'attribute name must be a string'u'attribute name must be a string'b' + Return a callable object that fetches the given item(s) from its operand. + After f = itemgetter(2), the call f(r) returns r[2]. + After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]) + 'u' + Return a callable object that fetches the given item(s) from its operand. + After f = itemgetter(2), the call f(r) returns r[2]. + After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]) + 'b'_items'u'_items'b' + Return a callable object that calls the given method on its operand. + After f = methodcaller('name'), the call f(r) returns r.name(). + After g = methodcaller('name', 'date', foo=1), the call g(r) returns + r.name('date', foo=1). + 'u' + Return a callable object that calls the given method on its operand. + After f = methodcaller('name'), the call f(r) returns r.name(). + After g = methodcaller('name', 'date', foo=1), the call g(r) returns + r.name('date', foo=1). + 'b'_kwargs'u'_kwargs'b'method name must be a string'u'method name must be a string'b'Same as a += b.'u'Same as a += b.'b'Same as a &= b.'u'Same as a &= b.'b'Same as a += b, for a and b sequences.'u'Same as a += b, for a and b sequences.'b'Same as a //= b.'u'Same as a //= b.'b'Same as a <<= b.'u'Same as a <<= b.'b'Same as a %= b.'u'Same as a %= b.'b'Same as a *= b.'u'Same as a *= b.'b'Same as a @= b.'u'Same as a @= b.'b'Same as a |= b.'u'Same as a |= b.'b'Same as a **= b.'u'Same as a **= b.'b'Same as a >>= b.'u'Same as a >>= b.'b'Same as a -= b.'u'Same as a -= b.'b'Same as a /= b.'u'Same as a /= b.'b'Same as a ^= b.'u'Same as a ^= b.'u'operator'A powerful, extensible, and easy-to-use option parser. + +By Greg Ward + +Originally distributed as Optik. + +For support, use the optik-users@lists.sourceforge.net mailing list +(http://lists.sourceforge.net/lists/listinfo/optik-users). + +Simple usage example: + + from optparse import OptionParser + + parser = OptionParser() + parser.add_option("-f", "--file", dest="filename", + help="write report to FILE", metavar="FILE") + parser.add_option("-q", "--quiet", + action="store_false", dest="verbose", default=True, + help="don't print status messages to stdout") + + (options, args) = parser.parse_args() +1.5.3Optionmake_optionSUPPRESS_HELPSUPPRESS_USAGEValuesOptionContainerOptionGroupOptionParserIndentedHelpFormatterTitledHelpFormatterOptParseErrorOptionErrorOptionConflictErrorOptionValueErrorBadOptionErrorcheck_choice +Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved. +Copyright (c) 2002-2006 Python Software Foundation. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the author nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +__copyright__<%s at 0x%x: %s>singular + Raised if an Option instance is created with invalid or + inconsistent arguments. + option_idoption %s: %s + Raised if conflicting options are added to an OptionParser. + + Raised if an invalid option value is encountered on the command + line. + + Raised if an invalid option is seen on the command line. + opt_strno such option: %sAmbiguousOptionError + Raised if an ambiguous option is seen on the command line. + ambiguous option: %s (%s?) + Abstract base class for formatting option help. OptionParser + instances should use one of the HelpFormatter subclasses for + formatting help; by default IndentedHelpFormatter is used. + + Instance attributes: + parser : OptionParser + the controlling OptionParser instance + indent_increment : int + the number of columns to indent per nesting level + max_help_position : int + the maximum starting column for option help text + help_position : int + the calculated starting column for option help text; + initially the same as the maximum + width : int + total number of columns for output (pass None to constructor for + this value to be taken from the $COLUMNS environment variable) + level : int + current indentation level + current_indent : int + current indentation level (in columns) + help_width : int + number of columns available for option help text (calculated) + default_tag : str + text to replace with each option's default value, "%default" + by default. Set to false value to disable default value expansion. + option_strings : { Option : str } + maps Option instances to the snippet of help text explaining + the syntax of that option, e.g. "-h, --help" or + "-fFILE, --file=FILE" + _short_opt_fmt : str + format string controlling how short options with values are + printed in help text. Must be either "%s%s" ("-fFILE") or + "%s %s" ("-f FILE"), because those are the two syntaxes that + Optik supports. + _long_opt_fmt : str + similar but for long options; must be either "%s %s" ("--file FILE") + or "%s=%s" ("--file=FILE"). + NO_DEFAULT_VALUEshort_firstCOLUMNS%defaultdefault_tag_short_opt_fmt_long_opt_fmtset_parserset_short_opt_delimiterdeliminvalid metavar delimiter for short options: %rset_long_opt_delimiterinvalid metavar delimiter for long options: %rdedentsubclasses must implementformat_heading + Format a paragraph of free-form text for inclusion in the + help output at the current indentation level. + format_descriptionformat_epilogexpand_defaultdefault_valueNO_DEFAULTformat_optionstore_option_stringsmax_lenoption_listformat_option_stringsoption_groupsReturn a comma-separated list of option strings & metavariables.takes_valuesopt_short_optslopt_long_optsFormat help with indented section bodies. + Usage: %s +Format help with underlined section headers. + %s %s +Usage%s +%s +=-_parse_num0b_parse_intintegerfloating-point_builtin_cvtcheck_builtincvtoption %s: invalid %s value: %roption %s: invalid choice: %r (choose from %s)DEFAULT + Instance attributes: + _short_opts : [string] + _long_opts : [string] + + action : string + type : string + dest : string + default : any + nargs : int + const : any + choices : [string] + callback : function + callback_args : (any*) + callback_kwargs : { string : any } + help : string + metavar : string + callback_argscallback_kwargsATTRSACTIONSSTORE_ACTIONSTYPED_ACTIONSALWAYS_TYPED_ACTIONSCONST_ACTIONSTYPESTYPE_CHECKERCHECK_METHODS_check_opt_strings_set_opt_strings_set_attrsat least one option string must be suppliedinvalid option string %r: must be at least two characters long"invalid option string %r: ""must be at least two characters long"invalid short option string %r: must be of the form -x, (x any non-dash char)"invalid short option string %r: ""must be of the form -x, (x any non-dash char)"invalid long option string %r: must start with --, followed by non-dash"invalid long option string %r: ""must start with --, followed by non-dash"invalid keyword arguments: %s_check_actioninvalid action: %r_check_typeinvalid option type: %rmust not supply a type for action %r_check_choicemust supply a list of choices for type 'choice'choices must be a list of strings ('%s' supplied)must not supply choices for type %r_check_dest_check_const'const' must not be supplied for action %r_check_nargs'nargs' must not be supplied for action %rcallback not callable: %rcallback_args, if supplied, must be a tuple: not %rcallback_kwargs, if supplied, must be a dict: not %rcallback supplied (%r) for non-callback optioncallback_args supplied for non-callback optioncallback_kwargs supplied for non-callback optionget_opt_stringcheck_valueconvert_valueensure_valueprint_versionunknown action %r_update_careful + Update the option values from an arbitrary dictionary, but only + use keys from dict that already have a corresponding attribute + in self. Any keys in dict without a corresponding attribute + are silently ignored. + dval_update_loose + Update the option values from an arbitrary dictionary, + using all keys from the dictionary regardless of whether + they have a corresponding attribute in self or not. + _updatecarefullooseinvalid update mode: %rread_moduleread_file + Abstract base class. + + Class attributes: + standard_option_list : [Option] + list of standard options that will be accepted by all instances + of this parser class (intended to be overridden by subclasses). + + Instance attributes: + option_list : [Option] + the list of Option objects contained by this OptionContainer + _short_opt : { string : Option } + dictionary mapping short option strings, eg. "-f" or "-X", + to the Option instances that implement them. If an Option + has multiple short option strings, it will appear in this + dictionary multiple times. [1] + _long_opt : { string : Option } + dictionary mapping long option strings, eg. "--file" or + "--exclude", to the Option instances that implement them. + Again, a given Option can occur multiple times in this + dictionary. [1] + defaults : { string : any } + dictionary mapping option destination names to default + values for each destination [1] + + [1] These mappings are common to (shared by) all components of the + controlling OptionParser, where they are initially created. + + option_class_create_option_listset_conflict_handlerset_description_create_option_mappings_short_opt_long_opt_share_option_mappingsresolveinvalid conflict_resolution value %rget_descriptionsee OptionParser.destroy().conflict_optsconflicting option string(s): %sc_optionadd_option(Option) + add_option(opt_str, ..., kwarg=val, ...) + not an Option instance: %rinvalid argumentsadd_optionsget_optionremove_optionno such option %rformat_option_helpset_title + Class attributes: + standard_option_list : [Option] + list of standard options that will be accepted by all instances + of this parser class (intended to be overridden by subclasses). + + Instance attributes: + usage : string + a usage string for your program. Before it is displayed + to the user, "%prog" will be expanded to the name of + your program (self.prog or os.path.basename(sys.argv[0])). + prog : string + the name of the current program (to override + os.path.basename(sys.argv[0])). + description : string + A paragraph of text giving a brief overview of your program. + optparse reformats this paragraph to fit the current terminal + width and prints it when the user requests help (after usage, + but before the list of options). + epilog : string + paragraph of help text to print after option help + + option_groups : [OptionGroup] + list of option groups in this parser (option groups are + irrelevant for parsing the command-line, but very useful + for generating help) + + allow_interspersed_args : bool = true + if true, positional arguments may be interspersed with options. + Assuming -a and -b each take a single argument, the command-line + -ablah foo bar -bboo baz + will be interpreted the same as + -ablah -bboo -- foo bar baz + If this flag were false, that command line would be interpreted as + -ablah -- foo bar -bboo baz + -- ie. we stop processing options as soon as we see the first + non-option argument. (This is the tradition followed by + Python's getopt module, Perl's Getopt::Std, and other argument- + parsing libraries, but it is generally annoying to users.) + + process_default_values : bool = true + if true, option default values are processed similarly to option + values from the command line: that is, they are passed to the + type-checking function for the option's type (as long as the + default value is a string). (This really only matters if you + have defined custom types; see SF bug #955889.) Set it to false + to restore the behaviour of Optik 1.4.1 and earlier. + + rargs : [string] + the argument list currently being parsed. Only set when + parse_args() is active, and continually trimmed down as + we consume arguments. Mainly there for the benefit of + callback options. + largs : [string] + the list of leftover arguments that we have skipped while + parsing options. If allow_interspersed_args is false, this + list is always empty. + values : Values + the set of option values currently being accumulated. Only + set when parse_args() is active. Also mainly for callbacks. + + Because of the 'rargs', 'largs', and 'values' attributes, + OptionParser is not thread-safe. If, for some perverse reason, you + need to parse command-line arguments simultaneously in different + threads, use different OptionParser instances. + + standard_option_listadd_help_optionset_usageallow_interspersed_argsprocess_default_values_populate_option_list_init_parsing_state + Declare that you are done with this OptionParser. This cleans up + reference cycles so the OptionParser (and all objects referenced by + it) can be garbage-collected promptly. After calling destroy(), the + OptionParser is unusable. + _add_help_option_add_version_option--versionrargslargs%prog [options]enable_interspersed_argsSet parsing to not stop on the first non-option, allowing + interspersing switches with command arguments. This is the + default behavior. See also disable_interspersed_args() and the + class documentation description of the attribute + allow_interspersed_args.disable_interspersed_argsSet parsing to stop on the first non-option. Use this if + you have a command processor which runs another command that + has options of its own and you want to make sure these options + don't get confused. + set_process_default_valuesset_default_get_all_optionsget_default_valuesadd_option_groupnot an OptionGroup instance: %rinvalid OptionGroup (wrong parser)get_option_group + parse_args(args : [string] = sys.argv[1:], + values : Values = None) + -> (values : Values, args : [string]) + + Parse the command-line options found in 'args' (default: + sys.argv[1:]). Any errors result in a call to 'error()', which + by default prints the usage message to stderr and calls + sys.exit() with an error message. On success returns a pair + (values, args) where 'values' is a Values instance (with all + your option values) and 'args' is the list of arguments left + over after parsing options. + _process_argscheck_values + check_values(values : Values, args : [string]) + -> (values : Values, args : [string]) + + Check that the supplied option values and leftover arguments are + valid. Returns the option values and leftover arguments + (possibly adjusted, possibly completely new -- whatever you + like). Default implementation just returns the passed-in + values; subclasses may override as desired. + _process_args(largs : [string], + rargs : [string], + values : Values) + + Process command-line arguments and populate 'values', consuming + options and arguments from 'rargs'. If 'allow_interspersed_args' is + false, stop at the first non-option argument. If true, accumulate any + interspersed non-option arguments in 'largs'. + _process_long_opt_process_short_opts_match_long_opt_match_long_opt(opt : string) -> string + + Determine which long option string 'opt' matches, ie. which one + it is an unambiguous abbreviation for. Raises BadOptionError if + 'opt' doesn't unambiguously match any long option string. + _match_abbrevnext_arghad_explicit_value%(option)s option requires %(number)d argument%(option)s option requires %(number)d arguments%s option does not take a valueget_prog_nameexpand_prog_name%progerror(msg : string) + + Print a usage message incorporating 'msg' to stderr and exit. + If you override this in a subclass, it should not return -- it + should either exit or raise an exception. + %s: error: %s +get_usageprint_usage(file : file = stdout) + + Print the usage message for the current program (self.usage) to + 'file' (default stdout). Any occurrence of the string "%prog" in + self.usage is replaced with the name of the current program + (basename of sys.argv[0]). Does nothing if self.usage is empty + or not defined. + print_version(file : file = stdout) + + Print the version message for this program (self.version) to + 'file' (default stdout). As with print_usage(), any occurrence + of "%prog" in self.version is replaced by the current program's + name. Does nothing if self.version is empty or undefined. + Optionsprint_help(file : file = stdout) + + Print an extended help message, listing all options and any + help text provided with them, to 'file' (default stdout). + wordmap_match_abbrev(s : string, wordmap : {string : Option}) -> string + + Return the string key in 'wordmap' for which 's' is an unambiguous + abbreviation. If 's' is found to be ambiguous or doesn't match any of + 'words', raise BadOptionError. + # This file was generated from:# Id: option_parser.py 527 2006-07-23 15:21:30Z greg# Id: option.py 522 2006-06-11 16:22:03Z gward# Id: help.py 527 2006-07-23 15:21:30Z greg# Id: errors.py 509 2006-04-20 00:58:24Z gward# computed later# The help for each option consists of two parts:# * the opt strings and metavars# eg. ("-x", or "-fFILENAME, --file=FILENAME")# * the user-supplied help string# eg. ("turn on expert mode", "read data from FILENAME")# If possible, we write both of these on the same line:# -x turn on expert mode# But if the opt string list is too long, we put the help# string on a second line, indented to the same column it would# start in if it fit on the first line.# -fFILENAME, --file=FILENAME# read data from FILENAME# start help on same line as opts# hexadecimal# binary# have to remove "0b" prefix# octal# decimal# Not supplying a default is different from a default of None,# so we need an explicit "not supplied" value.# The list of instance attributes that may be set through# keyword args to the constructor.# The set of actions allowed by option parsers. Explicitly listed# here so the constructor can validate its arguments.# The set of actions that involve storing a value somewhere;# also listed just for constructor argument validation. (If# the action is one of these, there must be a destination.)# The set of actions for which it makes sense to supply a value# type, ie. which may consume an argument from the command line.# The set of actions which *require* a value type, ie. that# always consume an argument from the command line.# The set of actions which take a 'const' attribute.# The set of known types for option parsers. Again, listed here for# constructor argument validation.# Dictionary of argument checking functions, which convert and# validate option arguments according to the option type.# Signature of checking functions is:# check(option : Option, opt : string, value : string) -> any# where# option is the Option instance calling the checker# opt is the actual option seen on the command-line# (eg. "-a", "--file")# value is the option argument seen on the command-line# The return value should be in the appropriate Python type# for option.type -- eg. an integer if option.type == "int".# If no checker is defined for a type, arguments will be# unchecked and remain strings.# CHECK_METHODS is a list of unbound method objects; they are called# by the constructor, in order, after all attributes are# initialized. The list is created and filled in later, after all# the methods are actually defined. (I just put it here because I# like to define and document all class attributes in the same# place.) Subclasses that add another _check_*() method should# define their own CHECK_METHODS list that adds their check method# to those from this class.# -- Constructor/initialization methods ----------------------------# Set _short_opts, _long_opts attrs from 'opts' tuple.# Have to be set now, in case no option strings are supplied.# Set all other attrs (action, type, etc.) from 'attrs' dict# Check all the attributes we just set. There are lots of# complicated interdependencies, but luckily they can be farmed# out to the _check_*() methods listed in CHECK_METHODS -- which# could be handy for subclasses! The one thing these all share# is that they raise OptionError if they discover a problem.# Filter out None because early versions of Optik had exactly# one short option and one long option, either of which# could be None.# -- Constructor validation methods --------------------------------# The "choices" attribute implies "choice" type.# No type given? "string" is the most sensible default.# Allow type objects or builtin type conversion functions# (int, str, etc.) as an alternative to their names.# No destination given, and we need one for this action. The# self.type check is for callbacks that take a value.# Glean a destination from the first long option string,# or from the first short option string if no long options.# eg. "--foo-bar" -> "foo_bar"# -- Processing methods --------------------------------------------# First, convert the value(s) to the right type. Howl if any# value(s) are bogus.# And then take whatever action is expected of us.# This is a separate method to make life easier for# subclasses to add new actions.# class Option# Initialize the option list and related data structures.# This method must be provided by subclasses, and it must# initialize at least the following instance attributes:# option_list, _short_opt, _long_opt, defaults.# For use by OptionParser constructor -- create the main# option mappings used by this OptionParser and all# OptionGroups that it owns.# single letter -> Option instance# long option -> Option instance# maps option dest -> default value# For use by OptionGroup constructor -- use shared option# mappings from the OptionParser that owns this OptionGroup.# -- Option-adding methods -----------------------------------------# option has a dest, we need a default# -- Option query/removal methods ----------------------------------# -- Help-formatting methods ---------------------------------------# Populate the option list; initial sources are the# standard_option_list class attribute, the 'option_list'# argument, and (if applicable) the _add_version_option() and# _add_help_option() methods.# -- Private methods -----------------------------------------------# (used by our or OptionContainer's constructor)# These are set in parse_args() for the convenience of callbacks.# -- Simple modifier methods ---------------------------------------# For backwards compatibility with Optik 1.3 and earlier.# Old, pre-Optik 1.5 behaviour.# -- OptionGroup methods -------------------------------------------# XXX lots of overlap with OptionContainer.add_option()# -- Option-parsing methods ----------------------------------------# don't modify caller's list# Store the halves of the argument list as attributes for the# convenience of callbacks:# rargs# the rest of the command-line (the "r" stands for# "remaining" or "right-hand")# largs# the leftover arguments -- ie. what's left after removing# options and their arguments (the "l" stands for "leftover"# or "left-hand")# We handle bare "--" explicitly, and bare "-" is handled by the# standard arg handler since the short arg case ensures that the# len of the opt string is greater than 1.# process a single long option (possibly with value(s))# process a cluster of short options (possibly with# value(s) for the last one only)# stop now, leave this arg in rargs# Say this is the original argument list:# [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]# ^# (we are about to process arg(i)).# Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of# [arg0, ..., arg(i-1)] (any options and their arguments will have# been removed from largs).# The while loop will usually consume 1 or more arguments per pass.# If it consumes 1 (eg. arg is an option that takes no arguments),# then after _process_arg() is done the situation is:# largs = subset of [arg0, ..., arg(i)]# rargs = [arg(i+1), ..., arg(N-1)]# If allow_interspersed_args is false, largs will always be# *empty* -- still a subset of [arg0, ..., arg(i-1)], but# not a very interesting subset!# Value explicitly attached to arg? Pretend it's the next# we have consumed a character# Any characters left in arg? Pretend they're the# next arg, and stop consuming characters of arg.# option doesn't take a value# -- Feedback methods ----------------------------------------------# Drop the last "\n", or the header if no options or option groups:# class OptionParser# Isolate all words with s as a prefix.# No exact match, so there had better be just one possibility.# More than one possible completion: ambiguous prefix.# Some day, there might be many Option classes. As of Optik 1.3, the# preferred way to instantiate Options is indirectly, via make_option(),# which will become a factory function when there are many Option# classes.b'A powerful, extensible, and easy-to-use option parser. + +By Greg Ward + +Originally distributed as Optik. + +For support, use the optik-users@lists.sourceforge.net mailing list +(http://lists.sourceforge.net/lists/listinfo/optik-users). + +Simple usage example: + + from optparse import OptionParser + + parser = OptionParser() + parser.add_option("-f", "--file", dest="filename", + help="write report to FILE", metavar="FILE") + parser.add_option("-q", "--quiet", + action="store_false", dest="verbose", default=True, + help="don't print status messages to stdout") + + (options, args) = parser.parse_args() +'u'A powerful, extensible, and easy-to-use option parser. + +By Greg Ward + +Originally distributed as Optik. + +For support, use the optik-users@lists.sourceforge.net mailing list +(http://lists.sourceforge.net/lists/listinfo/optik-users). + +Simple usage example: + + from optparse import OptionParser + + parser = OptionParser() + parser.add_option("-f", "--file", dest="filename", + help="write report to FILE", metavar="FILE") + parser.add_option("-q", "--quiet", + action="store_false", dest="verbose", default=True, + help="don't print status messages to stdout") + + (options, args) = parser.parse_args() +'b'1.5.3'u'1.5.3'b'Option'u'Option'b'make_option'u'make_option'b'SUPPRESS_HELP'u'SUPPRESS_HELP'b'SUPPRESS_USAGE'u'SUPPRESS_USAGE'b'Values'u'Values'b'OptionContainer'u'OptionContainer'b'OptionGroup'u'OptionGroup'b'OptionParser'u'OptionParser'b'IndentedHelpFormatter'u'IndentedHelpFormatter'b'TitledHelpFormatter'u'TitledHelpFormatter'b'OptParseError'u'OptParseError'b'OptionError'u'OptionError'b'OptionConflictError'u'OptionConflictError'b'OptionValueError'u'OptionValueError'b'BadOptionError'u'BadOptionError'b'check_choice'u'check_choice'b' +Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved. +Copyright (c) 2002-2006 Python Software Foundation. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the author nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +'u' +Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved. +Copyright (c) 2002-2006 Python Software Foundation. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the author nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +'b'<%s at 0x%x: %s>'u'<%s at 0x%x: %s>'b' + Raised if an Option instance is created with invalid or + inconsistent arguments. + 'u' + Raised if an Option instance is created with invalid or + inconsistent arguments. + 'b'option %s: %s'u'option %s: %s'b' + Raised if conflicting options are added to an OptionParser. + 'u' + Raised if conflicting options are added to an OptionParser. + 'b' + Raised if an invalid option value is encountered on the command + line. + 'u' + Raised if an invalid option value is encountered on the command + line. + 'b' + Raised if an invalid option is seen on the command line. + 'u' + Raised if an invalid option is seen on the command line. + 'b'no such option: %s'u'no such option: %s'b' + Raised if an ambiguous option is seen on the command line. + 'u' + Raised if an ambiguous option is seen on the command line. + 'b'ambiguous option: %s (%s?)'u'ambiguous option: %s (%s?)'b' + Abstract base class for formatting option help. OptionParser + instances should use one of the HelpFormatter subclasses for + formatting help; by default IndentedHelpFormatter is used. + + Instance attributes: + parser : OptionParser + the controlling OptionParser instance + indent_increment : int + the number of columns to indent per nesting level + max_help_position : int + the maximum starting column for option help text + help_position : int + the calculated starting column for option help text; + initially the same as the maximum + width : int + total number of columns for output (pass None to constructor for + this value to be taken from the $COLUMNS environment variable) + level : int + current indentation level + current_indent : int + current indentation level (in columns) + help_width : int + number of columns available for option help text (calculated) + default_tag : str + text to replace with each option's default value, "%default" + by default. Set to false value to disable default value expansion. + option_strings : { Option : str } + maps Option instances to the snippet of help text explaining + the syntax of that option, e.g. "-h, --help" or + "-fFILE, --file=FILE" + _short_opt_fmt : str + format string controlling how short options with values are + printed in help text. Must be either "%s%s" ("-fFILE") or + "%s %s" ("-f FILE"), because those are the two syntaxes that + Optik supports. + _long_opt_fmt : str + similar but for long options; must be either "%s %s" ("--file FILE") + or "%s=%s" ("--file=FILE"). + 'u' + Abstract base class for formatting option help. OptionParser + instances should use one of the HelpFormatter subclasses for + formatting help; by default IndentedHelpFormatter is used. + + Instance attributes: + parser : OptionParser + the controlling OptionParser instance + indent_increment : int + the number of columns to indent per nesting level + max_help_position : int + the maximum starting column for option help text + help_position : int + the calculated starting column for option help text; + initially the same as the maximum + width : int + total number of columns for output (pass None to constructor for + this value to be taken from the $COLUMNS environment variable) + level : int + current indentation level + current_indent : int + current indentation level (in columns) + help_width : int + number of columns available for option help text (calculated) + default_tag : str + text to replace with each option's default value, "%default" + by default. Set to false value to disable default value expansion. + option_strings : { Option : str } + maps Option instances to the snippet of help text explaining + the syntax of that option, e.g. "-h, --help" or + "-fFILE, --file=FILE" + _short_opt_fmt : str + format string controlling how short options with values are + printed in help text. Must be either "%s%s" ("-fFILE") or + "%s %s" ("-f FILE"), because those are the two syntaxes that + Optik supports. + _long_opt_fmt : str + similar but for long options; must be either "%s %s" ("--file FILE") + or "%s=%s" ("--file=FILE"). + 'b'COLUMNS'u'COLUMNS'b'%default'u'%default'b'invalid metavar delimiter for short options: %r'u'invalid metavar delimiter for short options: %r'b'invalid metavar delimiter for long options: %r'u'invalid metavar delimiter for long options: %r'b'subclasses must implement'u'subclasses must implement'b' + Format a paragraph of free-form text for inclusion in the + help output at the current indentation level. + 'u' + Format a paragraph of free-form text for inclusion in the + help output at the current indentation level. + 'b'Return a comma-separated list of option strings & metavariables.'u'Return a comma-separated list of option strings & metavariables.'b'Format help with indented section bodies. + 'u'Format help with indented section bodies. + 'b'Usage: %s +'u'Usage: %s +'b'Format help with underlined section headers. + 'u'Format help with underlined section headers. + 'b'%s %s +'u'%s %s +'b'Usage'u'Usage'b'%s +%s +'u'%s +%s +'b'=-'u'=-'b'0b'u'0b'b'integer'u'integer'b'floating-point'u'floating-point'b'complex'u'complex'b'option %s: invalid %s value: %r'u'option %s: invalid %s value: %r'b'option %s: invalid choice: %r (choose from %s)'u'option %s: invalid choice: %r (choose from %s)'b'NO'u'NO'b'DEFAULT'u'DEFAULT'b' + Instance attributes: + _short_opts : [string] + _long_opts : [string] + + action : string + type : string + dest : string + default : any + nargs : int + const : any + choices : [string] + callback : function + callback_args : (any*) + callback_kwargs : { string : any } + help : string + metavar : string + 'u' + Instance attributes: + _short_opts : [string] + _long_opts : [string] + + action : string + type : string + dest : string + default : any + nargs : int + const : any + choices : [string] + callback : function + callback_args : (any*) + callback_kwargs : { string : any } + help : string + metavar : string + 'b'callback_args'u'callback_args'b'callback_kwargs'u'callback_kwargs'b'choice'u'choice'b'at least one option string must be supplied'u'at least one option string must be supplied'b'invalid option string %r: must be at least two characters long'u'invalid option string %r: must be at least two characters long'b'invalid short option string %r: must be of the form -x, (x any non-dash char)'u'invalid short option string %r: must be of the form -x, (x any non-dash char)'b'invalid long option string %r: must start with --, followed by non-dash'u'invalid long option string %r: must start with --, followed by non-dash'b'invalid keyword arguments: %s'u'invalid keyword arguments: %s'b'invalid action: %r'u'invalid action: %r'b'invalid option type: %r'u'invalid option type: %r'b'must not supply a type for action %r'u'must not supply a type for action %r'b'must supply a list of choices for type 'choice''u'must supply a list of choices for type 'choice''b'choices must be a list of strings ('%s' supplied)'u'choices must be a list of strings ('%s' supplied)'b'must not supply choices for type %r'u'must not supply choices for type %r'b''const' must not be supplied for action %r'u''const' must not be supplied for action %r'b''nargs' must not be supplied for action %r'u''nargs' must not be supplied for action %r'b'callback not callable: %r'u'callback not callable: %r'b'callback_args, if supplied, must be a tuple: not %r'u'callback_args, if supplied, must be a tuple: not %r'b'callback_kwargs, if supplied, must be a dict: not %r'u'callback_kwargs, if supplied, must be a dict: not %r'b'callback supplied (%r) for non-callback option'u'callback supplied (%r) for non-callback option'b'callback_args supplied for non-callback option'u'callback_args supplied for non-callback option'b'callback_kwargs supplied for non-callback option'u'callback_kwargs supplied for non-callback option'b'unknown action %r'u'unknown action %r'b'USAGE'u'USAGE'b' + Update the option values from an arbitrary dictionary, but only + use keys from dict that already have a corresponding attribute + in self. Any keys in dict without a corresponding attribute + are silently ignored. + 'u' + Update the option values from an arbitrary dictionary, but only + use keys from dict that already have a corresponding attribute + in self. Any keys in dict without a corresponding attribute + are silently ignored. + 'b' + Update the option values from an arbitrary dictionary, + using all keys from the dictionary regardless of whether + they have a corresponding attribute in self or not. + 'u' + Update the option values from an arbitrary dictionary, + using all keys from the dictionary regardless of whether + they have a corresponding attribute in self or not. + 'b'careful'u'careful'b'loose'u'loose'b'invalid update mode: %r'u'invalid update mode: %r'b' + Abstract base class. + + Class attributes: + standard_option_list : [Option] + list of standard options that will be accepted by all instances + of this parser class (intended to be overridden by subclasses). + + Instance attributes: + option_list : [Option] + the list of Option objects contained by this OptionContainer + _short_opt : { string : Option } + dictionary mapping short option strings, eg. "-f" or "-X", + to the Option instances that implement them. If an Option + has multiple short option strings, it will appear in this + dictionary multiple times. [1] + _long_opt : { string : Option } + dictionary mapping long option strings, eg. "--file" or + "--exclude", to the Option instances that implement them. + Again, a given Option can occur multiple times in this + dictionary. [1] + defaults : { string : any } + dictionary mapping option destination names to default + values for each destination [1] + + [1] These mappings are common to (shared by) all components of the + controlling OptionParser, where they are initially created. + + 'u' + Abstract base class. + + Class attributes: + standard_option_list : [Option] + list of standard options that will be accepted by all instances + of this parser class (intended to be overridden by subclasses). + + Instance attributes: + option_list : [Option] + the list of Option objects contained by this OptionContainer + _short_opt : { string : Option } + dictionary mapping short option strings, eg. "-f" or "-X", + to the Option instances that implement them. If an Option + has multiple short option strings, it will appear in this + dictionary multiple times. [1] + _long_opt : { string : Option } + dictionary mapping long option strings, eg. "--file" or + "--exclude", to the Option instances that implement them. + Again, a given Option can occur multiple times in this + dictionary. [1] + defaults : { string : any } + dictionary mapping option destination names to default + values for each destination [1] + + [1] These mappings are common to (shared by) all components of the + controlling OptionParser, where they are initially created. + + 'b'resolve'u'resolve'b'invalid conflict_resolution value %r'u'invalid conflict_resolution value %r'b'see OptionParser.destroy().'u'see OptionParser.destroy().'b'conflicting option string(s): %s'u'conflicting option string(s): %s'b'add_option(Option) + add_option(opt_str, ..., kwarg=val, ...) + 'u'add_option(Option) + add_option(opt_str, ..., kwarg=val, ...) + 'b'not an Option instance: %r'u'not an Option instance: %r'b'invalid arguments'u'invalid arguments'b'no such option %r'u'no such option %r'b' + Class attributes: + standard_option_list : [Option] + list of standard options that will be accepted by all instances + of this parser class (intended to be overridden by subclasses). + + Instance attributes: + usage : string + a usage string for your program. Before it is displayed + to the user, "%prog" will be expanded to the name of + your program (self.prog or os.path.basename(sys.argv[0])). + prog : string + the name of the current program (to override + os.path.basename(sys.argv[0])). + description : string + A paragraph of text giving a brief overview of your program. + optparse reformats this paragraph to fit the current terminal + width and prints it when the user requests help (after usage, + but before the list of options). + epilog : string + paragraph of help text to print after option help + + option_groups : [OptionGroup] + list of option groups in this parser (option groups are + irrelevant for parsing the command-line, but very useful + for generating help) + + allow_interspersed_args : bool = true + if true, positional arguments may be interspersed with options. + Assuming -a and -b each take a single argument, the command-line + -ablah foo bar -bboo baz + will be interpreted the same as + -ablah -bboo -- foo bar baz + If this flag were false, that command line would be interpreted as + -ablah -- foo bar -bboo baz + -- ie. we stop processing options as soon as we see the first + non-option argument. (This is the tradition followed by + Python's getopt module, Perl's Getopt::Std, and other argument- + parsing libraries, but it is generally annoying to users.) + + process_default_values : bool = true + if true, option default values are processed similarly to option + values from the command line: that is, they are passed to the + type-checking function for the option's type (as long as the + default value is a string). (This really only matters if you + have defined custom types; see SF bug #955889.) Set it to false + to restore the behaviour of Optik 1.4.1 and earlier. + + rargs : [string] + the argument list currently being parsed. Only set when + parse_args() is active, and continually trimmed down as + we consume arguments. Mainly there for the benefit of + callback options. + largs : [string] + the list of leftover arguments that we have skipped while + parsing options. If allow_interspersed_args is false, this + list is always empty. + values : Values + the set of option values currently being accumulated. Only + set when parse_args() is active. Also mainly for callbacks. + + Because of the 'rargs', 'largs', and 'values' attributes, + OptionParser is not thread-safe. If, for some perverse reason, you + need to parse command-line arguments simultaneously in different + threads, use different OptionParser instances. + + 'u' + Class attributes: + standard_option_list : [Option] + list of standard options that will be accepted by all instances + of this parser class (intended to be overridden by subclasses). + + Instance attributes: + usage : string + a usage string for your program. Before it is displayed + to the user, "%prog" will be expanded to the name of + your program (self.prog or os.path.basename(sys.argv[0])). + prog : string + the name of the current program (to override + os.path.basename(sys.argv[0])). + description : string + A paragraph of text giving a brief overview of your program. + optparse reformats this paragraph to fit the current terminal + width and prints it when the user requests help (after usage, + but before the list of options). + epilog : string + paragraph of help text to print after option help + + option_groups : [OptionGroup] + list of option groups in this parser (option groups are + irrelevant for parsing the command-line, but very useful + for generating help) + + allow_interspersed_args : bool = true + if true, positional arguments may be interspersed with options. + Assuming -a and -b each take a single argument, the command-line + -ablah foo bar -bboo baz + will be interpreted the same as + -ablah -bboo -- foo bar baz + If this flag were false, that command line would be interpreted as + -ablah -- foo bar -bboo baz + -- ie. we stop processing options as soon as we see the first + non-option argument. (This is the tradition followed by + Python's getopt module, Perl's Getopt::Std, and other argument- + parsing libraries, but it is generally annoying to users.) + + process_default_values : bool = true + if true, option default values are processed similarly to option + values from the command line: that is, they are passed to the + type-checking function for the option's type (as long as the + default value is a string). (This really only matters if you + have defined custom types; see SF bug #955889.) Set it to false + to restore the behaviour of Optik 1.4.1 and earlier. + + rargs : [string] + the argument list currently being parsed. Only set when + parse_args() is active, and continually trimmed down as + we consume arguments. Mainly there for the benefit of + callback options. + largs : [string] + the list of leftover arguments that we have skipped while + parsing options. If allow_interspersed_args is false, this + list is always empty. + values : Values + the set of option values currently being accumulated. Only + set when parse_args() is active. Also mainly for callbacks. + + Because of the 'rargs', 'largs', and 'values' attributes, + OptionParser is not thread-safe. If, for some perverse reason, you + need to parse command-line arguments simultaneously in different + threads, use different OptionParser instances. + + 'b' + Declare that you are done with this OptionParser. This cleans up + reference cycles so the OptionParser (and all objects referenced by + it) can be garbage-collected promptly. After calling destroy(), the + OptionParser is unusable. + 'u' + Declare that you are done with this OptionParser. This cleans up + reference cycles so the OptionParser (and all objects referenced by + it) can be garbage-collected promptly. After calling destroy(), the + OptionParser is unusable. + 'b'--version'u'--version'b'%prog [options]'u'%prog [options]'b'Set parsing to not stop on the first non-option, allowing + interspersing switches with command arguments. This is the + default behavior. See also disable_interspersed_args() and the + class documentation description of the attribute + allow_interspersed_args.'u'Set parsing to not stop on the first non-option, allowing + interspersing switches with command arguments. This is the + default behavior. See also disable_interspersed_args() and the + class documentation description of the attribute + allow_interspersed_args.'b'Set parsing to stop on the first non-option. Use this if + you have a command processor which runs another command that + has options of its own and you want to make sure these options + don't get confused. + 'u'Set parsing to stop on the first non-option. Use this if + you have a command processor which runs another command that + has options of its own and you want to make sure these options + don't get confused. + 'b'not an OptionGroup instance: %r'u'not an OptionGroup instance: %r'b'invalid OptionGroup (wrong parser)'u'invalid OptionGroup (wrong parser)'b' + parse_args(args : [string] = sys.argv[1:], + values : Values = None) + -> (values : Values, args : [string]) + + Parse the command-line options found in 'args' (default: + sys.argv[1:]). Any errors result in a call to 'error()', which + by default prints the usage message to stderr and calls + sys.exit() with an error message. On success returns a pair + (values, args) where 'values' is a Values instance (with all + your option values) and 'args' is the list of arguments left + over after parsing options. + 'u' + parse_args(args : [string] = sys.argv[1:], + values : Values = None) + -> (values : Values, args : [string]) + + Parse the command-line options found in 'args' (default: + sys.argv[1:]). Any errors result in a call to 'error()', which + by default prints the usage message to stderr and calls + sys.exit() with an error message. On success returns a pair + (values, args) where 'values' is a Values instance (with all + your option values) and 'args' is the list of arguments left + over after parsing options. + 'b' + check_values(values : Values, args : [string]) + -> (values : Values, args : [string]) + + Check that the supplied option values and leftover arguments are + valid. Returns the option values and leftover arguments + (possibly adjusted, possibly completely new -- whatever you + like). Default implementation just returns the passed-in + values; subclasses may override as desired. + 'u' + check_values(values : Values, args : [string]) + -> (values : Values, args : [string]) + + Check that the supplied option values and leftover arguments are + valid. Returns the option values and leftover arguments + (possibly adjusted, possibly completely new -- whatever you + like). Default implementation just returns the passed-in + values; subclasses may override as desired. + 'b'_process_args(largs : [string], + rargs : [string], + values : Values) + + Process command-line arguments and populate 'values', consuming + options and arguments from 'rargs'. If 'allow_interspersed_args' is + false, stop at the first non-option argument. If true, accumulate any + interspersed non-option arguments in 'largs'. + 'u'_process_args(largs : [string], + rargs : [string], + values : Values) + + Process command-line arguments and populate 'values', consuming + options and arguments from 'rargs'. If 'allow_interspersed_args' is + false, stop at the first non-option argument. If true, accumulate any + interspersed non-option arguments in 'largs'. + 'b'_match_long_opt(opt : string) -> string + + Determine which long option string 'opt' matches, ie. which one + it is an unambiguous abbreviation for. Raises BadOptionError if + 'opt' doesn't unambiguously match any long option string. + 'u'_match_long_opt(opt : string) -> string + + Determine which long option string 'opt' matches, ie. which one + it is an unambiguous abbreviation for. Raises BadOptionError if + 'opt' doesn't unambiguously match any long option string. + 'b'%(option)s option requires %(number)d argument'u'%(option)s option requires %(number)d argument'b'%(option)s option requires %(number)d arguments'u'%(option)s option requires %(number)d arguments'b'%s option does not take a value'u'%s option does not take a value'b'%prog'u'%prog'b'error(msg : string) + + Print a usage message incorporating 'msg' to stderr and exit. + If you override this in a subclass, it should not return -- it + should either exit or raise an exception. + 'u'error(msg : string) + + Print a usage message incorporating 'msg' to stderr and exit. + If you override this in a subclass, it should not return -- it + should either exit or raise an exception. + 'b'%s: error: %s +'u'%s: error: %s +'b'print_usage(file : file = stdout) + + Print the usage message for the current program (self.usage) to + 'file' (default stdout). Any occurrence of the string "%prog" in + self.usage is replaced with the name of the current program + (basename of sys.argv[0]). Does nothing if self.usage is empty + or not defined. + 'u'print_usage(file : file = stdout) + + Print the usage message for the current program (self.usage) to + 'file' (default stdout). Any occurrence of the string "%prog" in + self.usage is replaced with the name of the current program + (basename of sys.argv[0]). Does nothing if self.usage is empty + or not defined. + 'b'print_version(file : file = stdout) + + Print the version message for this program (self.version) to + 'file' (default stdout). As with print_usage(), any occurrence + of "%prog" in self.version is replaced by the current program's + name. Does nothing if self.version is empty or undefined. + 'u'print_version(file : file = stdout) + + Print the version message for this program (self.version) to + 'file' (default stdout). As with print_usage(), any occurrence + of "%prog" in self.version is replaced by the current program's + name. Does nothing if self.version is empty or undefined. + 'b'Options'u'Options'b'print_help(file : file = stdout) + + Print an extended help message, listing all options and any + help text provided with them, to 'file' (default stdout). + 'u'print_help(file : file = stdout) + + Print an extended help message, listing all options and any + help text provided with them, to 'file' (default stdout). + 'b'_match_abbrev(s : string, wordmap : {string : Option}) -> string + + Return the string key in 'wordmap' for which 's' is an unambiguous + abbreviation. If 's' is found to be ambiguous or doesn't match any of + 'words', raise BadOptionError. + 'u'_match_abbrev(s : string, wordmap : {string : Option}) -> string + + Return the string key in 'wordmap' for which 's' is an unambiguous + abbreviation. If 's' is found to be ambiguous or doesn't match any of + 'words', raise BadOptionError. + 'u'optparse'OS routines for NT or Posix depending on what system we're on. + +This exports: + - all functions from posix or nt, e.g. unlink, stat, etc. + - os.path is either posixpath or ntpath + - os.name is either 'posix' or 'nt' + - os.curdir is a string representing the current directory (always '.') + - os.pardir is a string representing the parent directory (always '..') + - os.sep is the (or a most common) pathname separator ('/' or '\\') + - os.extsep is the extension separator (always '.') + - os.altsep is the alternate pathname separator (None or '/') + - os.pathsep is the component separator used in $PATH etc + - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') + - os.defpath is the default search path for executables + - os.devnull is the file path of the null device ('/dev/null', etc.) + +Programs that import and use 'os' stand a better chance of being +portable between different platforms. Of course, they must then +only use functions that are defined by all platforms (e.g., unlink +and opendir), and leave all pathname manipulation to os.path +(e.g., split and join). +get_exec_path_exists_get_exports_list_have_functionsntpathno os specific module found_globals_add_setHAVE_FACCESSATHAVE_FCHMODATHAVE_FCHOWNATchownHAVE_FSTATATHAVE_FUTIMESATHAVE_LINKATHAVE_MKDIRATHAVE_MKFIFOATmkfifoHAVE_MKNODATmknodHAVE_OPENATHAVE_READLINKATHAVE_RENAMEATHAVE_SYMLINKATHAVE_UNLINKATHAVE_UTIMENSATsupports_dir_fdsupports_effective_idsHAVE_FCHDIRHAVE_FCHMODHAVE_FCHOWNHAVE_FDOPENDIRHAVE_FEXECVEexecveHAVE_FTRUNCATEHAVE_FUTIMENSHAVE_FUTIMESHAVE_FPATHCONFpathconfstatvfsfstatvfsHAVE_FSTATVFSsupports_fdHAVE_LCHFLAGSchflagsHAVE_LCHMODlchownHAVE_LCHOWNHAVE_LUTIMESHAVE_LSTATMS_WINDOWSsupports_follow_symlinksmakedirsexist_okmakedirs(name [, mode=0o777][, exist_ok=False]) + + Super-mkdir; create a leaf directory and all intermediate ones. Works like + mkdir, except that any intermediate path segment (not just the rightmost) + will be created if it does not exist. If the target directory already + exists, raise an OSError if exist_ok is False. Otherwise no exception is + raised. This is recursive. + + cdirremovedirsremovedirs(name) + + Super-rmdir; remove a leaf directory and all empty intermediate + ones. Works like rmdir except that, if the leaf directory is + successfully removed, directories corresponding to rightmost path + segments will be pruned away until either the whole path is + consumed or an error occurs. Errors during this latter phase are + ignored -- they generally mean that a directory was not empty. + + renamesrenames(old, new) + + Super-rename; create directories as necessary and delete any left + empty. Works like rename, except creation of any intermediate + directories needed to make the new pathname good is attempted + first. After the rename, directories corresponding to rightmost + path segments of the old name will be pruned until either the + whole path is consumed or a nonempty directory is found. + + Note: this function can fail with the new directory structure made + if you lack permissions needed to unlink the leaf directory or + file. + + topdownonerrorDirectory tree generator. + + For each directory in the directory tree rooted at top (including top + itself, but excluding '.' and '..'), yields a 3-tuple + + dirpath, dirnames, filenames + + dirpath is a string, the path to the directory. dirnames is a list of + the names of the subdirectories in dirpath (excluding '.' and '..'). + filenames is a list of the names of the non-directory files in dirpath. + Note that the names in the lists are just names, with no path components. + To get a full path (which begins with top) to a file or directory in + dirpath, do os.path.join(dirpath, name). + + If optional arg 'topdown' is true or not specified, the triple for a + directory is generated before the triples for any of its subdirectories + (directories are generated top down). If topdown is false, the triple + for a directory is generated after the triples for all of its + subdirectories (directories are generated bottom up). + + When topdown is true, the caller can modify the dirnames list in-place + (e.g., via del or slice assignment), and walk will only recurse into the + subdirectories whose names remain in dirnames; this can be used to prune the + search, or to impose a specific order of visiting. Modifying dirnames when + topdown is false has no effect on the behavior of os.walk(), since the + directories in dirnames have already been generated by the time dirnames + itself is generated. No matter the value of topdown, the list of + subdirectories is retrieved before the tuples for the directory and its + subdirectories are generated. + + By default errors from the os.scandir() call are ignored. If + optional arg 'onerror' is specified, it should be a function; it + will be called with one argument, an OSError instance. It can + report the error to continue with the walk, or raise the exception + to abort the walk. Note that the filename is available as the + filename attribute of the exception object. + + By default, os.walk does not follow symbolic links to subdirectories on + systems that support them. In order to get this functionality, set the + optional argument 'followlinks' to true. + + Caution: if you pass a relative pathname for top, don't change the + current working directory between resumptions of walk. walk never + changes the current directory, and assumes that the client doesn't + either. + + Example: + + import os + from os.path import join, getsize + for root, dirs, files in os.walk('python/Lib/email'): + print(root, "consumes", end="") + print(sum(getsize(join(root, name)) for name in files), end="") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + + nondirswalk_dirsscandir_itwalk_intois_symlinkfwalkfollow_symlinksdir_fdDirectory tree generator. + + This behaves exactly like walk(), except that it yields a 4-tuple + + dirpath, dirnames, filenames, dirfd + + `dirpath`, `dirnames` and `filenames` are identical to walk() output, + and `dirfd` is a file descriptor referring to the directory `dirpath`. + + The advantage of fwalk() over walk() is that it's safe against symlink + races (when follow_symlinks is False). + + If dir_fd is not None, it should be a file descriptor open to a directory, + and top should be relative; top will then be relative to that directory. + (dir_fd is always supported for fwalk.) + + Caution: + Since fwalk() yields file descriptors, those are only valid until the + next iteration step, so you should dup() them if you want to keep them + for a longer period. + + Example: + + import os + for root, dirs, files, rootfd in os.fwalk('python/Lib/email'): + print(root, "consumes", end="") + print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files), + end="") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + orig_stO_RDONLYtopfd_fwalktoppathisbytesentriesdirfddirpathexeclexecl(file, *args) + + Execute the executable file with argument list args, replacing the + current process. execvexecleexecle(file, *args, env) + + Execute the executable file with argument list args and + environment env, replacing the current process. execlpexeclp(file, *args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. execvpexeclpeexeclpe(file, *args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the current + process. execvpeexecvp(file, args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. + args may be a list or tuple of strings. _execvpeexecvpe(file, args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the + current process. + args may be a list or tuple of strings. exec_funcargrestsaved_exclast_excReturns the sequence of directories that will be searched for the + named executable (similar to a shell) when launching a process. + + *env* must be an environment variable dict or None. If *env* is None, + os.environ will be used. + supports_bytes_environpath_listbenv cannot contain 'PATH' and b'PATH' keys_Environencodekeydecodekeyencodevaluedecodevalueputenvunsetenvencodedkeyenviron({{{}}}){!r}: {!r}_putenv_unsetenv_createenvironcheck_strstr expected, not %sGet an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are str._check_bytesbytes expected, not %sgetenvbGet an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are bytes._fscodecEncode filename (an os.PathLike, bytes, or str) to the filesystem + encoding with 'surrogateescape' error handler, return bytes unchanged. + On Windows, use 'strict' error handler if the file system encoding is + 'mbcs' (which is the default encoding). + Decode filename (an os.PathLike, bytes, or str) from the filesystem + encoding with 'surrogateescape' error handler, return str unchanged. On + Windows, use 'strict' error handler if the file system encoding is + 'mbcs' (which is the default encoding). + spawnvP_WAITP_NOWAITP_NOWAITO_spawnvefargv must be a tuple or a listargv first element cannot be emptywpidWIFSTOPPEDNot stopped, signaled or exited???spawnv(mode, file, args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. spawnvespawnve(mode, file, args, env) -> integer + +Execute file with arguments from args in a subprocess with the +specified environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. spawnvpspawnvp(mode, file, args) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. spawnvpespawnvpe(mode, file, args, env) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. spawnlspawnl(mode, file, *args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. spawnlespawnle(mode, file, *args, env) -> integer + +Execute file with arguments from args in a subprocess with the +supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. spawnlpspawnlp(mode, file, *args) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. spawnlpespawnlpe(mode, file, *args, env) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. invalid cmd type (%s, expected string)invalid mode %rpopen() does not support unbuffered streams_wrap_closeinvalid fd type (%s, expected integer)_fspathReturn the path representation of a path-like object. + + If str or bytes is passed in, it is returned unchanged. Otherwise the + os.PathLike interface is used to get the path representation. If the + path representation is not str or bytes, TypeError is raised. If the + provided path is not str, bytes, or os.PathLike, TypeError is raised. + path_typepath_reprexpected str, bytes or os.PathLike object, not "expected str, bytes or os.PathLike object, "expected {}.__fspath__() to return str or bytes, not {}"expected {}.__fspath__() to return str or bytes, ""not {}"Abstract base class for implementing the file system path protocol.Return the file system path representation of the object._AddedDllDirectorycookieremove_dll_directory_cookie_remove_dll_directoryadd_dll_directoryAdd a path to the DLL search path. + + This search path is used when resolving dependencies for imported + extension modules (the module itself is resolved through sys.path), + and also by ctypes. + + Remove the directory by calling close() on the returned object or + using it in a with statement. + _add_dll_directory#'# Note: more names are added to __all__ later.# Any new dependencies of the os module and/or changes in path separator# requires updating importlib as well.# fstat always works# mac os x10.3# Some platforms don't support lchmod(). Often the function exists# anyway, as a stub that always returns ENOSUP or perhaps EOPNOTSUPP.# (No, I don't know why that's a good design.) ./configure will detect# this and reject it--so HAVE_LCHMOD still won't be defined on such# platforms. This is Very Helpful.# However, sometimes platforms without a working lchmod() *do* have# fchmodat(). (Examples: Linux kernel 3.2 with glibc 2.15,# OpenIndiana 3.x.) And fchmodat() has a flag that theoretically makes# it behave like lchmod(). So in theory it would be a suitable# replacement for lchmod(). But when lchmod() doesn't work, fchmodat()'s# flag doesn't work *either*. Sadly ./configure isn't sophisticated# enough to detect this condition--it only determines whether or not# fchmodat() minimally works.# Therefore we simply ignore fchmodat() when deciding whether or not# os.chmod supports follow_symlinks. Just checking lchmod() is# sufficient. After all--if you have a working fchmodat(), your# lchmod() almost certainly works too.# _add("HAVE_FCHMODAT", "chmod")# Python uses fixed values for the SEEK_ constants; they are mapped# to native constants if necessary in posixmodule.c# Other possible SEEK values are directly imported from posixmodule.c# Super directory utilities.# (Inspired by Eric Raymond; the doc strings are mostly his)# Defeats race condition when another thread created the path# xxx/newdir/. exists if xxx/newdir exists# Cannot rely on checking for EEXIST, since the operating system# could give priority to other errors like EACCES or EROFS# We may not have read permission for top, in which case we can't# get a list of the files the directory contains. os.walk# always suppressed the exception then, rather than blow up for a# minor reason when (say) a thousand readable directories are still# left to visit. That logic is copied here.# Note that scandir is global in this module due# to earlier import-*.# If is_dir() raises an OSError, consider that the entry is not# a directory, same behaviour than os.path.isdir().# Bottom-up: recurse into sub-directory, but exclude symlinks to# directories if followlinks is False# If is_symlink() raises an OSError, consider that the# entry is not a symbolic link, same behaviour than# os.path.islink().# Yield before recursion if going top down# Recurse into sub-directories# Issue #23605: os.path.islink() is used instead of caching# entry.is_symlink() result during the loop on os.scandir() because# the caller can replace the directory entry during the "yield"# above.# Yield after recursion if going bottom up# Note: To guard against symlink races, we use the standard# lstat()/open()/fstat() trick.# Note: This uses O(depth of the directory tree) file descriptors: if# necessary, it can be adapted to only require O(1) FDs, see issue# #13734.# Add dangling symlinks, ignore disappeared files# Use a local import instead of a global import to limit the number of# modules loaded at startup: the os module is always loaded at startup by# Python. It may also avoid a bootstrap issue.# {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a# BytesWarning when using python -b or python -bb: ignore the warning# Change environ to automatically call putenv(), unsetenv if they exist.# raise KeyError with the original key value# list() from dict object is an atomic operation# Where Env Var Names Must Be UPPERCASE# Where Env Var Names Can Be Mixed Case# unicode environ# bytes environ# Does type-checking of `filename`.# Supply spawn*() (probably only for Unix)# XXX Should we support P_DETACH? I suppose it could fork()**2# and close the std I/O streams. Also, P_OVERLAY is the same# as execv*()?# Internal helper; func is the exec*() function to use# Parent# Caller is responsible for waiting!# Note: spawnvp[e] isn't currently supported on Windows# These aren't supplied by the basic Windows code# but can be easily implemented in Python# At the moment, Windows doesn't implement spawnvp[e],# so it won't have spawnlp[e] either.# Supply os.popen()# Helper for popen() -- a proxy for a file whose close waits for the process# Shift left to match old behavior# Supply os.fdopen()# For testing purposes, make sure the function is available when the C# implementation exists.# Work from the object's type to match method resolution of other magic# methods.# If there is no C implementation, make the pure Python version the# implementation as transparently as possible.b'OS routines for NT or Posix depending on what system we're on. + +This exports: + - all functions from posix or nt, e.g. unlink, stat, etc. + - os.path is either posixpath or ntpath + - os.name is either 'posix' or 'nt' + - os.curdir is a string representing the current directory (always '.') + - os.pardir is a string representing the parent directory (always '..') + - os.sep is the (or a most common) pathname separator ('/' or '\\') + - os.extsep is the extension separator (always '.') + - os.altsep is the alternate pathname separator (None or '/') + - os.pathsep is the component separator used in $PATH etc + - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') + - os.defpath is the default search path for executables + - os.devnull is the file path of the null device ('/dev/null', etc.) + +Programs that import and use 'os' stand a better chance of being +portable between different platforms. Of course, they must then +only use functions that are defined by all platforms (e.g., unlink +and opendir), and leave all pathname manipulation to os.path +(e.g., split and join). +'u'OS routines for NT or Posix depending on what system we're on. + +This exports: + - all functions from posix or nt, e.g. unlink, stat, etc. + - os.path is either posixpath or ntpath + - os.name is either 'posix' or 'nt' + - os.curdir is a string representing the current directory (always '.') + - os.pardir is a string representing the parent directory (always '..') + - os.sep is the (or a most common) pathname separator ('/' or '\\') + - os.extsep is the extension separator (always '.') + - os.altsep is the alternate pathname separator (None or '/') + - os.pathsep is the component separator used in $PATH etc + - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') + - os.defpath is the default search path for executables + - os.devnull is the file path of the null device ('/dev/null', etc.) + +Programs that import and use 'os' stand a better chance of being +portable between different platforms. Of course, they must then +only use functions that are defined by all platforms (e.g., unlink +and opendir), and leave all pathname manipulation to os.path +(e.g., split and join). +'b'fsencode'u'fsencode'b'fsdecode'u'fsdecode'b'get_exec_path'u'get_exec_path'b'fdopen'u'fdopen'b'popen'u'popen'b'_exit'u'_exit'b'no os specific module found'u'no os specific module found'b'os.path'u'os.path'b'_have_functions'u'_have_functions'b'HAVE_FACCESSAT'u'HAVE_FACCESSAT'b'access'u'access'b'HAVE_FCHMODAT'u'HAVE_FCHMODAT'b'chmod'u'chmod'b'HAVE_FCHOWNAT'u'HAVE_FCHOWNAT'b'chown'u'chown'b'HAVE_FSTATAT'u'HAVE_FSTATAT'b'stat'u'stat'b'HAVE_FUTIMESAT'u'HAVE_FUTIMESAT'b'utime'u'utime'b'HAVE_LINKAT'u'HAVE_LINKAT'b'HAVE_MKDIRAT'u'HAVE_MKDIRAT'b'mkdir'u'mkdir'b'HAVE_MKFIFOAT'u'HAVE_MKFIFOAT'b'mkfifo'u'mkfifo'b'HAVE_MKNODAT'u'HAVE_MKNODAT'b'mknod'u'mknod'b'HAVE_OPENAT'u'HAVE_OPENAT'b'HAVE_READLINKAT'u'HAVE_READLINKAT'b'readlink'u'readlink'b'HAVE_RENAMEAT'u'HAVE_RENAMEAT'b'rename'u'rename'b'HAVE_SYMLINKAT'u'HAVE_SYMLINKAT'b'symlink'u'symlink'b'HAVE_UNLINKAT'u'HAVE_UNLINKAT'b'rmdir'u'rmdir'b'HAVE_UTIMENSAT'u'HAVE_UTIMENSAT'b'HAVE_FCHDIR'u'HAVE_FCHDIR'b'chdir'u'chdir'b'HAVE_FCHMOD'u'HAVE_FCHMOD'b'HAVE_FCHOWN'u'HAVE_FCHOWN'b'HAVE_FDOPENDIR'u'HAVE_FDOPENDIR'b'listdir'u'listdir'b'scandir'u'scandir'b'HAVE_FEXECVE'u'HAVE_FEXECVE'b'execve'u'execve'b'HAVE_FTRUNCATE'u'HAVE_FTRUNCATE'b'truncate'u'truncate'b'HAVE_FUTIMENS'u'HAVE_FUTIMENS'b'HAVE_FUTIMES'u'HAVE_FUTIMES'b'HAVE_FPATHCONF'u'HAVE_FPATHCONF'b'pathconf'u'pathconf'b'statvfs'u'statvfs'b'fstatvfs'u'fstatvfs'b'HAVE_FSTATVFS'u'HAVE_FSTATVFS'b'HAVE_LCHFLAGS'u'HAVE_LCHFLAGS'b'chflags'u'chflags'b'HAVE_LCHMOD'u'HAVE_LCHMOD'b'lchown'u'lchown'b'HAVE_LCHOWN'u'HAVE_LCHOWN'b'HAVE_LUTIMES'u'HAVE_LUTIMES'b'HAVE_LSTAT'u'HAVE_LSTAT'b'MS_WINDOWS'u'MS_WINDOWS'b'makedirs(name [, mode=0o777][, exist_ok=False]) + + Super-mkdir; create a leaf directory and all intermediate ones. Works like + mkdir, except that any intermediate path segment (not just the rightmost) + will be created if it does not exist. If the target directory already + exists, raise an OSError if exist_ok is False. Otherwise no exception is + raised. This is recursive. + + 'u'makedirs(name [, mode=0o777][, exist_ok=False]) + + Super-mkdir; create a leaf directory and all intermediate ones. Works like + mkdir, except that any intermediate path segment (not just the rightmost) + will be created if it does not exist. If the target directory already + exists, raise an OSError if exist_ok is False. Otherwise no exception is + raised. This is recursive. + + 'b'removedirs(name) + + Super-rmdir; remove a leaf directory and all empty intermediate + ones. Works like rmdir except that, if the leaf directory is + successfully removed, directories corresponding to rightmost path + segments will be pruned away until either the whole path is + consumed or an error occurs. Errors during this latter phase are + ignored -- they generally mean that a directory was not empty. + + 'u'removedirs(name) + + Super-rmdir; remove a leaf directory and all empty intermediate + ones. Works like rmdir except that, if the leaf directory is + successfully removed, directories corresponding to rightmost path + segments will be pruned away until either the whole path is + consumed or an error occurs. Errors during this latter phase are + ignored -- they generally mean that a directory was not empty. + + 'b'renames(old, new) + + Super-rename; create directories as necessary and delete any left + empty. Works like rename, except creation of any intermediate + directories needed to make the new pathname good is attempted + first. After the rename, directories corresponding to rightmost + path segments of the old name will be pruned until either the + whole path is consumed or a nonempty directory is found. + + Note: this function can fail with the new directory structure made + if you lack permissions needed to unlink the leaf directory or + file. + + 'u'renames(old, new) + + Super-rename; create directories as necessary and delete any left + empty. Works like rename, except creation of any intermediate + directories needed to make the new pathname good is attempted + first. After the rename, directories corresponding to rightmost + path segments of the old name will be pruned until either the + whole path is consumed or a nonempty directory is found. + + Note: this function can fail with the new directory structure made + if you lack permissions needed to unlink the leaf directory or + file. + + 'b'makedirs'u'makedirs'b'removedirs'u'removedirs'b'renames'u'renames'b'Directory tree generator. + + For each directory in the directory tree rooted at top (including top + itself, but excluding '.' and '..'), yields a 3-tuple + + dirpath, dirnames, filenames + + dirpath is a string, the path to the directory. dirnames is a list of + the names of the subdirectories in dirpath (excluding '.' and '..'). + filenames is a list of the names of the non-directory files in dirpath. + Note that the names in the lists are just names, with no path components. + To get a full path (which begins with top) to a file or directory in + dirpath, do os.path.join(dirpath, name). + + If optional arg 'topdown' is true or not specified, the triple for a + directory is generated before the triples for any of its subdirectories + (directories are generated top down). If topdown is false, the triple + for a directory is generated after the triples for all of its + subdirectories (directories are generated bottom up). + + When topdown is true, the caller can modify the dirnames list in-place + (e.g., via del or slice assignment), and walk will only recurse into the + subdirectories whose names remain in dirnames; this can be used to prune the + search, or to impose a specific order of visiting. Modifying dirnames when + topdown is false has no effect on the behavior of os.walk(), since the + directories in dirnames have already been generated by the time dirnames + itself is generated. No matter the value of topdown, the list of + subdirectories is retrieved before the tuples for the directory and its + subdirectories are generated. + + By default errors from the os.scandir() call are ignored. If + optional arg 'onerror' is specified, it should be a function; it + will be called with one argument, an OSError instance. It can + report the error to continue with the walk, or raise the exception + to abort the walk. Note that the filename is available as the + filename attribute of the exception object. + + By default, os.walk does not follow symbolic links to subdirectories on + systems that support them. In order to get this functionality, set the + optional argument 'followlinks' to true. + + Caution: if you pass a relative pathname for top, don't change the + current working directory between resumptions of walk. walk never + changes the current directory, and assumes that the client doesn't + either. + + Example: + + import os + from os.path import join, getsize + for root, dirs, files in os.walk('python/Lib/email'): + print(root, "consumes", end="") + print(sum(getsize(join(root, name)) for name in files), end="") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + + 'u'Directory tree generator. + + For each directory in the directory tree rooted at top (including top + itself, but excluding '.' and '..'), yields a 3-tuple + + dirpath, dirnames, filenames + + dirpath is a string, the path to the directory. dirnames is a list of + the names of the subdirectories in dirpath (excluding '.' and '..'). + filenames is a list of the names of the non-directory files in dirpath. + Note that the names in the lists are just names, with no path components. + To get a full path (which begins with top) to a file or directory in + dirpath, do os.path.join(dirpath, name). + + If optional arg 'topdown' is true or not specified, the triple for a + directory is generated before the triples for any of its subdirectories + (directories are generated top down). If topdown is false, the triple + for a directory is generated after the triples for all of its + subdirectories (directories are generated bottom up). + + When topdown is true, the caller can modify the dirnames list in-place + (e.g., via del or slice assignment), and walk will only recurse into the + subdirectories whose names remain in dirnames; this can be used to prune the + search, or to impose a specific order of visiting. Modifying dirnames when + topdown is false has no effect on the behavior of os.walk(), since the + directories in dirnames have already been generated by the time dirnames + itself is generated. No matter the value of topdown, the list of + subdirectories is retrieved before the tuples for the directory and its + subdirectories are generated. + + By default errors from the os.scandir() call are ignored. If + optional arg 'onerror' is specified, it should be a function; it + will be called with one argument, an OSError instance. It can + report the error to continue with the walk, or raise the exception + to abort the walk. Note that the filename is available as the + filename attribute of the exception object. + + By default, os.walk does not follow symbolic links to subdirectories on + systems that support them. In order to get this functionality, set the + optional argument 'followlinks' to true. + + Caution: if you pass a relative pathname for top, don't change the + current working directory between resumptions of walk. walk never + changes the current directory, and assumes that the client doesn't + either. + + Example: + + import os + from os.path import join, getsize + for root, dirs, files in os.walk('python/Lib/email'): + print(root, "consumes", end="") + print(sum(getsize(join(root, name)) for name in files), end="") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + + 'b'walk'u'walk'b'Directory tree generator. + + This behaves exactly like walk(), except that it yields a 4-tuple + + dirpath, dirnames, filenames, dirfd + + `dirpath`, `dirnames` and `filenames` are identical to walk() output, + and `dirfd` is a file descriptor referring to the directory `dirpath`. + + The advantage of fwalk() over walk() is that it's safe against symlink + races (when follow_symlinks is False). + + If dir_fd is not None, it should be a file descriptor open to a directory, + and top should be relative; top will then be relative to that directory. + (dir_fd is always supported for fwalk.) + + Caution: + Since fwalk() yields file descriptors, those are only valid until the + next iteration step, so you should dup() them if you want to keep them + for a longer period. + + Example: + + import os + for root, dirs, files, rootfd in os.fwalk('python/Lib/email'): + print(root, "consumes", end="") + print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files), + end="") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + 'u'Directory tree generator. + + This behaves exactly like walk(), except that it yields a 4-tuple + + dirpath, dirnames, filenames, dirfd + + `dirpath`, `dirnames` and `filenames` are identical to walk() output, + and `dirfd` is a file descriptor referring to the directory `dirpath`. + + The advantage of fwalk() over walk() is that it's safe against symlink + races (when follow_symlinks is False). + + If dir_fd is not None, it should be a file descriptor open to a directory, + and top should be relative; top will then be relative to that directory. + (dir_fd is always supported for fwalk.) + + Caution: + Since fwalk() yields file descriptors, those are only valid until the + next iteration step, so you should dup() them if you want to keep them + for a longer period. + + Example: + + import os + for root, dirs, files, rootfd in os.fwalk('python/Lib/email'): + print(root, "consumes", end="") + print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files), + end="") + print("bytes in", len(files), "non-directory files") + if 'CVS' in dirs: + dirs.remove('CVS') # don't visit CVS directories + 'b'fwalk'u'fwalk'b'execl(file, *args) + + Execute the executable file with argument list args, replacing the + current process. 'u'execl(file, *args) + + Execute the executable file with argument list args, replacing the + current process. 'b'execle(file, *args, env) + + Execute the executable file with argument list args and + environment env, replacing the current process. 'u'execle(file, *args, env) + + Execute the executable file with argument list args and + environment env, replacing the current process. 'b'execlp(file, *args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. 'u'execlp(file, *args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. 'b'execlpe(file, *args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the current + process. 'u'execlpe(file, *args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the current + process. 'b'execvp(file, args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. + args may be a list or tuple of strings. 'u'execvp(file, args) + + Execute the executable file (which is searched for along $PATH) + with argument list args, replacing the current process. + args may be a list or tuple of strings. 'b'execvpe(file, args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the + current process. + args may be a list or tuple of strings. 'u'execvpe(file, args, env) + + Execute the executable file (which is searched for along $PATH) + with argument list args and environment env, replacing the + current process. + args may be a list or tuple of strings. 'b'execl'u'execl'b'execle'u'execle'b'execlp'u'execlp'b'execlpe'u'execlpe'b'execvp'u'execvp'b'execvpe'u'execvpe'b'Returns the sequence of directories that will be searched for the + named executable (similar to a shell) when launching a process. + + *env* must be an environment variable dict or None. If *env* is None, + os.environ will be used. + 'u'Returns the sequence of directories that will be searched for the + named executable (similar to a shell) when launching a process. + + *env* must be an environment variable dict or None. If *env* is None, + os.environ will be used. + 'b'env cannot contain 'PATH' and b'PATH' keys'u'env cannot contain 'PATH' and b'PATH' keys'b'environ({{{}}})'u'environ({{{}}})'b'{!r}: {!r}'u'{!r}: {!r}'b'putenv'u'putenv'b'unsetenv'u'unsetenv'b'str expected, not %s'u'str expected, not %s'b'Get an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are str.'u'Get an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are str.'b'getenv'u'getenv'b'supports_bytes_environ'u'supports_bytes_environ'b'bytes expected, not %s'u'bytes expected, not %s'b'Get an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are bytes.'u'Get an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are bytes.'b'getenvb'u'getenvb'b'Encode filename (an os.PathLike, bytes, or str) to the filesystem + encoding with 'surrogateescape' error handler, return bytes unchanged. + On Windows, use 'strict' error handler if the file system encoding is + 'mbcs' (which is the default encoding). + 'u'Encode filename (an os.PathLike, bytes, or str) to the filesystem + encoding with 'surrogateescape' error handler, return bytes unchanged. + On Windows, use 'strict' error handler if the file system encoding is + 'mbcs' (which is the default encoding). + 'b'Decode filename (an os.PathLike, bytes, or str) from the filesystem + encoding with 'surrogateescape' error handler, return str unchanged. On + Windows, use 'strict' error handler if the file system encoding is + 'mbcs' (which is the default encoding). + 'u'Decode filename (an os.PathLike, bytes, or str) from the filesystem + encoding with 'surrogateescape' error handler, return str unchanged. On + Windows, use 'strict' error handler if the file system encoding is + 'mbcs' (which is the default encoding). + 'b'spawnv'u'spawnv'b'execv'u'execv'b'P_WAIT'u'P_WAIT'b'P_NOWAIT'u'P_NOWAIT'b'P_NOWAITO'u'P_NOWAITO'b'argv must be a tuple or a list'u'argv must be a tuple or a list'b'argv first element cannot be empty'u'argv first element cannot be empty'b'Not stopped, signaled or exited???'u'Not stopped, signaled or exited???'b'spawnv(mode, file, args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnv(mode, file, args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnve(mode, file, args, env) -> integer + +Execute file with arguments from args in a subprocess with the +specified environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnve(mode, file, args, env) -> integer + +Execute file with arguments from args in a subprocess with the +specified environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnvp(mode, file, args) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnvp(mode, file, args) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnvpe(mode, file, args, env) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnvpe(mode, file, args, env) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnve'u'spawnve'b'spawnvp'u'spawnvp'b'spawnvpe'u'spawnvpe'b'spawnl(mode, file, *args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnl(mode, file, *args) -> integer + +Execute file with arguments from args in a subprocess. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnle(mode, file, *args, env) -> integer + +Execute file with arguments from args in a subprocess with the +supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnle(mode, file, *args, env) -> integer + +Execute file with arguments from args in a subprocess with the +supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnl'u'spawnl'b'spawnle'u'spawnle'b'spawnlp(mode, file, *args) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnlp(mode, file, *args) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnlpe(mode, file, *args, env) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'u'spawnlpe(mode, file, *args, env) -> integer + +Execute file (which is looked for along $PATH) with arguments from +args in a subprocess with the supplied environment. +If mode == P_NOWAIT return the pid of the process. +If mode == P_WAIT return the process's exit code if it exits normally; +otherwise return -SIG, where SIG is the signal that killed it. 'b'spawnlp'u'spawnlp'b'spawnlpe'u'spawnlpe'b'invalid cmd type (%s, expected string)'u'invalid cmd type (%s, expected string)'b'invalid mode %r'u'invalid mode %r'b'popen() does not support unbuffered streams'u'popen() does not support unbuffered streams'b'invalid fd type (%s, expected integer)'u'invalid fd type (%s, expected integer)'b'Return the path representation of a path-like object. + + If str or bytes is passed in, it is returned unchanged. Otherwise the + os.PathLike interface is used to get the path representation. If the + path representation is not str or bytes, TypeError is raised. If the + provided path is not str, bytes, or os.PathLike, TypeError is raised. + 'u'Return the path representation of a path-like object. + + If str or bytes is passed in, it is returned unchanged. Otherwise the + os.PathLike interface is used to get the path representation. If the + path representation is not str or bytes, TypeError is raised. If the + provided path is not str, bytes, or os.PathLike, TypeError is raised. + 'b'__fspath__'u'__fspath__'b'expected str, bytes or os.PathLike object, not 'u'expected str, bytes or os.PathLike object, not 'b'expected {}.__fspath__() to return str or bytes, not {}'u'expected {}.__fspath__() to return str or bytes, not {}'b'fspath'u'fspath'b'Abstract base class for implementing the file system path protocol.'u'Abstract base class for implementing the file system path protocol.'b'Return the file system path representation of the object.'u'Return the file system path representation of the object.'b''u''b''u''b'Add a path to the DLL search path. + + This search path is used when resolving dependencies for imported + extension modules (the module itself is resolved through sys.path), + and also by ctypes. + + Remove the directory by calling close() on the returned object or + using it in a with statement. + 'u'Add a path to the DLL search path. + + This search path is used when resolving dependencies for imported + extension modules (the module itself is resolved through sys.path), + and also by ctypes. + + Remove the directory by calling close() on the returned object or + using it in a with statement. + 'u'os'Parser engine for the grammar tables generated by pgen. + +The grammar table must be loaded first. + +See Parser/parser.c in the Python distribution for additional info on +how this parsing engine works. + +Exception to signal the parser is stuck.%s: type=%r, value=%r, context=%rParser engine. + + The proper usage sequence is: + + p = Parser(grammar, [converter]) # create instance + p.setup([start]) # prepare for parsing + : + if p.addtoken(...): # parse a token; may raise ParseError + break + root = p.rootnode # root of abstract syntax tree + + A Parser instance may be reused by calling setup() repeatedly. + + A Parser instance contains state pertaining to the current token + sequence, and should not be used concurrently by different threads + to parse separate token sequences. + + See driver.py for how to get input tokens by tokenizing a file or + string. + + Parsing is complete when addtoken() returns True; the root of the + abstract syntax tree can then be retrieved from the rootnode + instance variable. When a syntax error occurs, addtoken() raises + the ParseError exception. There is no error recovery; the parser + cannot be used after a syntax error was reported (but it can be + reinitialized by calling setup()). + + Constructor. + + The grammar argument is a grammar.Grammar instance; see the + grammar module for more information. + + The parser is not ready yet for parsing; you must call the + setup() method to get it started. + + The optional convert argument is a function mapping concrete + syntax tree nodes to abstract syntax tree nodes. If not + given, no conversion is done and the syntax tree produced is + the concrete syntax tree. If given, it must be a function of + two arguments, the first being the grammar (a grammar.Grammar + instance), and the second being the concrete syntax tree node + to be converted. The syntax tree is converted from the bottom + up. + + A concrete syntax tree node is a (type, value, context, nodes) + tuple, where type is the node type (a token or symbol number), + value is None for symbols and a string for tokens, context is + None or an opaque value used for error reporting (typically a + (lineno, offset) pair), and nodes is a list of children for + symbols, and None for tokens. + + An abstract syntax tree node may be anything; this is entirely + up to the converter function. + + Prepare for parsing. + + This *must* be called before starting to parse. + + The optional argument is an alternative start symbol; it + defaults to the grammar's start symbol. + + You can use a Parser instance to parse any number of programs; + each time you call setup() the parser is reset to an initial + state determined by the (implicit or explicit) start symbol. + + newnodestackentryused_namesAdd a token; return True iff this is the end of the program.classifyilabeldfaarcsitsdfaitsstatesitsfirsttoo much inputbad inputTurn a token into a label. (Internal)bad tokenShift a token. (Internal)newdfaPush a nonterminal. (Internal)Pop a nonterminal. (Internal)popdfapopstatepopnode# Each stack entry is a tuple: (dfa, state, node).# A node is a tuple: (type, value, context, children),# where children is a list of nodes or None, and context may be None.# Aliased to self.rootnode.used_names in pop()# Map from token to label# Loop until the token is shifted; may raise exceptions# Look for a state with this label# Look it up in the list of labels# Shift a token; we're done with it# Pop while we are in an accept-only state# Done parsing!# Done with this token# See if it's a symbol and if we're in its first set# Push a symbol# To continue the outer while loop# An accepting state, pop it and try something else# Done parsing, but another token is input# No success finding a transition# Keep a listing of all used names# Check for reserved wordsb'Parser engine for the grammar tables generated by pgen. + +The grammar table must be loaded first. + +See Parser/parser.c in the Python distribution for additional info on +how this parsing engine works. + +'u'Parser engine for the grammar tables generated by pgen. + +The grammar table must be loaded first. + +See Parser/parser.c in the Python distribution for additional info on +how this parsing engine works. + +'b'Exception to signal the parser is stuck.'u'Exception to signal the parser is stuck.'b'%s: type=%r, value=%r, context=%r'u'%s: type=%r, value=%r, context=%r'b'Parser engine. + + The proper usage sequence is: + + p = Parser(grammar, [converter]) # create instance + p.setup([start]) # prepare for parsing + : + if p.addtoken(...): # parse a token; may raise ParseError + break + root = p.rootnode # root of abstract syntax tree + + A Parser instance may be reused by calling setup() repeatedly. + + A Parser instance contains state pertaining to the current token + sequence, and should not be used concurrently by different threads + to parse separate token sequences. + + See driver.py for how to get input tokens by tokenizing a file or + string. + + Parsing is complete when addtoken() returns True; the root of the + abstract syntax tree can then be retrieved from the rootnode + instance variable. When a syntax error occurs, addtoken() raises + the ParseError exception. There is no error recovery; the parser + cannot be used after a syntax error was reported (but it can be + reinitialized by calling setup()). + + 'u'Parser engine. + + The proper usage sequence is: + + p = Parser(grammar, [converter]) # create instance + p.setup([start]) # prepare for parsing + : + if p.addtoken(...): # parse a token; may raise ParseError + break + root = p.rootnode # root of abstract syntax tree + + A Parser instance may be reused by calling setup() repeatedly. + + A Parser instance contains state pertaining to the current token + sequence, and should not be used concurrently by different threads + to parse separate token sequences. + + See driver.py for how to get input tokens by tokenizing a file or + string. + + Parsing is complete when addtoken() returns True; the root of the + abstract syntax tree can then be retrieved from the rootnode + instance variable. When a syntax error occurs, addtoken() raises + the ParseError exception. There is no error recovery; the parser + cannot be used after a syntax error was reported (but it can be + reinitialized by calling setup()). + + 'b'Constructor. + + The grammar argument is a grammar.Grammar instance; see the + grammar module for more information. + + The parser is not ready yet for parsing; you must call the + setup() method to get it started. + + The optional convert argument is a function mapping concrete + syntax tree nodes to abstract syntax tree nodes. If not + given, no conversion is done and the syntax tree produced is + the concrete syntax tree. If given, it must be a function of + two arguments, the first being the grammar (a grammar.Grammar + instance), and the second being the concrete syntax tree node + to be converted. The syntax tree is converted from the bottom + up. + + A concrete syntax tree node is a (type, value, context, nodes) + tuple, where type is the node type (a token or symbol number), + value is None for symbols and a string for tokens, context is + None or an opaque value used for error reporting (typically a + (lineno, offset) pair), and nodes is a list of children for + symbols, and None for tokens. + + An abstract syntax tree node may be anything; this is entirely + up to the converter function. + + 'u'Constructor. + + The grammar argument is a grammar.Grammar instance; see the + grammar module for more information. + + The parser is not ready yet for parsing; you must call the + setup() method to get it started. + + The optional convert argument is a function mapping concrete + syntax tree nodes to abstract syntax tree nodes. If not + given, no conversion is done and the syntax tree produced is + the concrete syntax tree. If given, it must be a function of + two arguments, the first being the grammar (a grammar.Grammar + instance), and the second being the concrete syntax tree node + to be converted. The syntax tree is converted from the bottom + up. + + A concrete syntax tree node is a (type, value, context, nodes) + tuple, where type is the node type (a token or symbol number), + value is None for symbols and a string for tokens, context is + None or an opaque value used for error reporting (typically a + (lineno, offset) pair), and nodes is a list of children for + symbols, and None for tokens. + + An abstract syntax tree node may be anything; this is entirely + up to the converter function. + + 'b'Prepare for parsing. + + This *must* be called before starting to parse. + + The optional argument is an alternative start symbol; it + defaults to the grammar's start symbol. + + You can use a Parser instance to parse any number of programs; + each time you call setup() the parser is reset to an initial + state determined by the (implicit or explicit) start symbol. + + 'u'Prepare for parsing. + + This *must* be called before starting to parse. + + The optional argument is an alternative start symbol; it + defaults to the grammar's start symbol. + + You can use a Parser instance to parse any number of programs; + each time you call setup() the parser is reset to an initial + state determined by the (implicit or explicit) start symbol. + + 'b'Add a token; return True iff this is the end of the program.'u'Add a token; return True iff this is the end of the program.'b'too much input'u'too much input'b'bad input'u'bad input'b'Turn a token into a label. (Internal)'u'Turn a token into a label. (Internal)'b'bad token'u'bad token'b'Shift a token. (Internal)'u'Shift a token. (Internal)'b'Push a nonterminal. (Internal)'u'Push a nonterminal. (Internal)'b'Pop a nonterminal. (Internal)'u'Pop a nonterminal. (Internal)'u'lib2to3.pgen2.parse'u'pgen2.parse'Parse (absolute and relative) URLs. + +urlparse module is based upon the following RFC specifications. + +RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding +and L. Masinter, January 2005. + +RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter +and L.Masinter, December 1999. + +RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T. +Berners-Lee, R. Fielding, and L. Masinter, August 1998. + +RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998. + +RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June +1995. + +RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M. +McCahill, December 1994 + +RFC 3986 is considered the current standard and any future changes to +urlparse module should conform with it. The urlparse module is +currently not entirely compliant with this RFC due to defacto +scenarios for parsing, and for backward compatibility purposes, some +parsing quirks from older RFCs are retained. The testcases in +test_urlparse.py provides a good indicator of parsing behavior. +urlunparseurljoinurldefragurlunsplitparse_qsparse_qslquote_from_bytesDefragResultParseResultSplitResultDefragResultBytesParseResultBytesSplitResultBytesgophernntpwaisshttpmmsprosperortsprtspusftpsvnsvn+sshwssuses_relativetelnetsnewsrsyncnfsgitgit+sshuses_netlochdlsipsipsteluses_paramsmailtonon_hierarchicaluses_queryuses_fragmentabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.'abcdefghijklmnopqrstuvwxyz''ABCDEFGHIJKLMNOPQRSTUVWXYZ''0123456789''+-.'scheme_chars_UNSAFE_URL_BYTES_TO_REMOVEMAX_CACHE_SIZE_parse_cacheclear_cacheClear the parse cache and the quoters cache._safe_quoters_implicit_encoding_implicit_errors_noop_encode_result_decode_args_coerce_argsstr_inputCannot mix str and non-str arguments_ResultMixinStrStandard approach to encoding parsed results from str to bytes_encoded_counterpart_ResultMixinBytesStandard approach to decoding parsed results from bytes to str_decoded_counterpart_NetlocResultMixinBaseShared methods for the parsed result objects containing a netloc element_userinfo_hostinfoPort could not be cast to integer value as Port out of range 0-65535_NetlocResultMixinStruserinfohave_infohostinfohave_passwordhave_open_brbracketed_NetlocResultMixinBytesurl fragment_DefragResultBasescheme netloc path query fragment_SplitResultBasescheme netloc path params query fragment_ParseResultBase +DefragResult(url, fragment) + +A 2-tuple that contains the url without fragment identifier and the fragment +identifier as a separate argument. +The URL with no fragment identifier. +Fragment identifier separated from URL, that allows indirect identification of a +secondary resource by reference to a primary resource and additional identifying +information. +fragment +SplitResult(scheme, netloc, path, query, fragment) + +A 5-tuple that contains the different components of a URL. Similar to +ParseResult, but does not split params. +Specifies URL scheme for the request. +Network location where the request is made to. + +The hierarchical path, such as the path to a file to download. + +The query component, that contains non-hierarchical data, that along with data +in path component, identifies a resource in the scope of URI's scheme and +network location. + +Fragment identifier, that allows indirect identification of a secondary resource +by reference to a primary resource and additional identifying information. + +ParseResult(scheme, netloc, path, params, query, fragment) + +A 6-tuple that contains components of a parsed URL. + +Parameters for last path element used to dereference the URI in order to provide +access to perform some operation on the resource. +ResultBase_fix_result_transcoding_result_pairs_decoded_encodedallow_fragmentsParse a URL into 6 components: + :///;?# + Return a 6-tuple: (scheme, netloc, path, params, query, fragment). + Note that we don't break the components up in smaller bits + (e.g. netloc is a single string) and we don't expand % escapes._coerce_resultsplitresult_splitparams_splitnetloc/?#wdelim_checknetlocNFKCnetloc2/?#@:netloc '' contains invalid characters under NFKC normalization_remove_unsafe_bytes_from_urlParse a URL into 5 components: + :///?# + Return a 5-tuple: (scheme, netloc, path, query, fragment). + Note that we don't break the components up in smaller bits + (e.g. netloc is a single string) and we don't expand % escapes.Invalid IPv6 URLPut a parsed URL back together again. This may result in a + slightly different, but equivalent URL, if the URL that was parsed + originally had redundant delimiters, e.g. a ? with an empty query + (the draft states that these are equivalent).%s;%sCombine the elements of a tuple as returned by urlsplit() into a + complete URL as a string. The data argument can be any five-item iterable. + This may result in a slightly different, but equivalent URL, if the URL that + was parsed originally had unnecessary delimiters (for example, a ? with an + empty query; the RFC states that these are equivalent).Join a base URL and a possibly relative URL to form an absolute + interpretation of the latter.bschemebnetlocbpathbparamsbquerybfragmentbase_partssegmentsresolved_pathsegRemoves any existing fragment from URL. + + Returns a tuple of the defragmented URL and the fragment. If + the URL contained no fragments, the second element is the + empty string. + fragdefrag0123456789ABCDEFabcdef_hexdig_hextobyteunquote_to_bytes('abc%20def') -> b'abc def'.([-]+)_asciireReplace %xx escapes by their single-character equivalent. The optional + encoding and errors parameters specify how to decode percent-encoded + sequences into Unicode characters, as accepted by the bytes.decode() + method. + By default, percent-encoded sequences are decoded with UTF-8, and invalid + sequences are replaced by a placeholder character. + + unquote('abc%20def') -> 'abc def'. + Expected str, got bytesqskeep_blank_valuesstrict_parsingmax_num_fieldsParse a query given as a string argument. + + Arguments: + + qs: percent-encoded query string to be parsed + + keep_blank_values: flag indicating whether blank values in + percent-encoded queries should be treated as blank strings. + A true value indicates that blanks should be retained as + blank strings. The default false value indicates that + blank values are to be ignored and treated as if they were + not included. + + strict_parsing: flag indicating what to do with parsing errors. + If false (the default), errors are silently ignored. + If true, errors raise a ValueError exception. + + encoding and errors: specify how to decode percent-encoded sequences + into Unicode characters, as accepted by the bytes.decode() method. + + max_num_fields: int. If set, then throws a ValueError if there + are more than n fields read by parse_qsl(). + + separator: str. The symbol to use for separating the query arguments. + Defaults to &. + + Returns a dictionary. + parsed_resultpairsParse a query given as a string argument. + + Arguments: + + qs: percent-encoded query string to be parsed + + keep_blank_values: flag indicating whether blank values in + percent-encoded queries should be treated as blank strings. + A true value indicates that blanks should be retained as blank + strings. The default false value indicates that blank values + are to be ignored and treated as if they were not included. + + strict_parsing: flag indicating what to do with parsing errors. If + false (the default), errors are silently ignored. If true, + errors raise a ValueError exception. + + encoding and errors: specify how to decode percent-encoded sequences + into Unicode characters, as accepted by the bytes.decode() method. + + max_num_fields: int. If set, then throws a ValueError + if there are more than n fields read by parse_qsl(). + + separator: str. The symbol to use for separating the query arguments. + Defaults to &. + + Returns a list, as G-d intended. + Separator must be of type string or bytes.Max number of fields exceededname_valuebad query field: %rLike unquote(), but also replace plus signs by spaces, as required for + unquoting HTML form values. + + unquote_plus('%7e/abc+def') -> '~/abc def' + ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-~b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'b'abcdefghijklmnopqrstuvwxyz'b'_.-~'_ALWAYS_SAFE_ALWAYS_SAFE_BYTESQuoterA mapping from bytes (in range(0,256)) to strings. + + String values are percent-encoded byte values, unless the key < 128, and + in the "safe" set (either the specified safe set, or default set). + safe: bytes object.%{:02X}quote('abc def') -> 'abc%20def' + + Each part of a URL, e.g. the path info, the query, etc., has a + different set of reserved characters that must be quoted. The + quote function offers a cautious (not minimal) way to quote a + string for most of these parts. + + RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists + the following (un)reserved characters. + + unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + reserved = gen-delims / sub-delims + gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" + sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + / "*" / "+" / "," / ";" / "=" + + Each of the reserved characters is reserved in some component of a URL, + but not necessarily in all of them. + + The quote function %-escapes all characters that are neither in the + unreserved chars ("always safe") nor the additional chars set via the + safe arg. + + The default for the safe arg is '/'. The character is reserved, but in + typical usage the quote function is being called on a path where the + existing slash characters are to be preserved. + + Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings. + Now, "~" is included in the set of unreserved characters. + + string and safe may be either str or bytes objects. encoding and errors + must not be specified if string is a bytes object. + + The optional encoding and errors parameters specify how to deal with + non-ASCII characters, as accepted by the str.encode method. + By default, encoding='utf-8' (characters are encoded with UTF-8), and + errors='strict' (unsupported characters raise a UnicodeEncodeError). + quote() doesn't support 'encoding' for bytesquote() doesn't support 'errors' for bytesLike quote(), but also replace ' ' with '+', as required for quoting + HTML form values. Plus signs in the original string are escaped unless + they are included in safe. It also does not have safe default to '/'. + spaceLike quote(), but accepts a bytes object rather than a str, and does + not perform string-to-bytes encoding. It always returns an ASCII string. + quote_from_bytes(b'abc def?') -> 'abc%20def%3f' + quote_from_bytes() expected bytesquoterdoseqquote_viaEncode a dict or sequence of two-element tuples into a URL query string. + + If any values in the query arg are sequences and doseq is true, each + sequence element is converted to a separate parameter. + + If the query arg is a sequence of two-element tuples, the order of the + parameters in the output will match the order of parameters in the + input. + + The components of a query arg may each be either a string or a bytes type. + + The safe, encoding, and errors parameters are passed down to the function + specified by quote_via (encoding and errors only if a component is a str). + tyvanot a valid non-string sequence or mapping object"not a valid non-string sequence ""or mapping object"urllib.parse.to_bytes() is deprecated as of 3.8_to_bytesto_bytes(u"URL") --> 'URL'.URL contains non-ASCII charactersTransform a string like '' into 'scheme://host/path'. + + The string is returned unchanged if it's not a wrapped URL. + URL:splittypeurllib.parse.splittype() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splittype() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead"_typeprogsplittype('type:opaquestring') --> 'type', 'opaquestring'.([^/:]+):(.*)splithosturllib.parse.splithost() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splithost() is deprecated as of 3.8, "_hostprogsplithost('//host[:port]/path') --> 'host[:port]', '/path'.//([^/#?]*)(.*)host_portsplituserurllib.parse.splituser() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splituser() is deprecated as of 3.8, "splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.splitpasswdurllib.parse.splitpasswd() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splitpasswd() is deprecated as of 3.8, "_splitpasswdsplitpasswd('user:passwd') -> 'user', 'passwd'.splitporturllib.parse.splitport() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splitport() is deprecated as of 3.8, "_splitport_portprogsplitport('host:port') --> 'host', 'port'.(.*):([0-9]*)splitnportdefporturllib.parse.splitnport() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splitnport() is deprecated as of 3.8, "_splitnportSplit host and port, returning numeric port. + Return given default port if no ':' found; defaults to -1. + Return numerical port if a valid number are found after ':'. + Return None if ':' but not a valid number.nportsplitqueryurllib.parse.splitquery() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splitquery() is deprecated as of 3.8, "_splitquerysplitquery('/path?query') --> '/path', 'query'.splittagurllib.parse.splittag() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splittag() is deprecated as of 3.8, "_splittagsplittag('/path#tag') --> '/path', 'tag'.splitattrurllib.parse.splitattr() is deprecated as of 3.8, use urllib.parse.urlparse() instead"urllib.parse.splitattr() is deprecated as of 3.8, "_splitattrsplitattr('/path;attr1=value1;attr2=value2;...') -> + '/path', ['attr1=value1', 'attr2=value2', ...].splitvalueurllib.parse.splitvalue() is deprecated as of 3.8, use urllib.parse.parse_qsl() instead"urllib.parse.splitvalue() is deprecated as of 3.8, ""use urllib.parse.parse_qsl() instead"_splitvaluesplitvalue('attr=value') --> 'attr', 'value'.# A classification of schemes.# The empty string classifies URLs with no scheme specified,# being the default value returned by “urlsplit” and “urlparse”.# These are not actually used anymore, but should stay for backwards# compatibility. (They are undocumented, but have a public-looking name.)# Characters valid in scheme names# Unsafe bytes to be removed per WHATWG spec# XXX: Consider replacing with functools.lru_cache# Helpers for bytes handling# For 3.2, we deliberately require applications that# handle improperly quoted URLs to do their own# decoding and encoding. If valid use cases are# presented, we may relax this by using latin-1# decoding internally for 3.3# Invokes decode if necessary to create str args# and returns the coerced inputs along with# an appropriate result coercion function# - noop for str inputs# - encoding function otherwise# We special-case the empty string to support the# "scheme=''" default argument to some functions# Result objects are more helpful than simple tuples# Scoped IPv6 address may have zone info, which must not be lowercased# like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keys# For backwards compatibility, alias _NetlocResultMixinStr# ResultBase is no longer part of the documented API, but it is# retained since deprecating it isn't worth the hassle# Structured result objects for string data# Structured result objects for bytes data# Set up the encode/decode result pairs# position of end of domain part of url, default is end# look for delimiters; the order is NOT important# find first of this delim# if found# use earliest delim position# return (domain, rest)# looking for characters like \u2100 that expand to 'a/c'# IDNA uses NFKC equivalence, so normalize for this check# ignore characters already included# but not the surrounding text# avoid runaway growth# optimize the common case# make sure "url" is not actually a port number (in which case# "scheme" is really part of the path)# not a port number# the last item is not a directory, so will not be taken into account# in resolving the relative path# for rfc3986, ignore all base path should the first character be root.# filter out elements that would cause redundant slashes on re-joining# the resolved_path# ignore any .. segments that would otherwise cause an IndexError# when popped from resolved_path if resolving for rfc3986# do some post-processing here. if the last segment was a relative dir,# then we need to append the trailing '/'# Note: strings are encoded as UTF-8. This is only an issue if it contains# unescaped non-ASCII characters, which URIs should not.# Is it a string-like object?# If max_num_fields is defined then check that the number of fields# is less than max_num_fields. This prevents a memory exhaustion DOS# attack via post bodies with many fields.# Handle case of a control-name with no equal sign# Keeps a cache internally, using defaultdict, for efficiency (lookups# of cached keys don't call Python code at all).# Without this, will just display as a defaultdict# Handle a cache miss. Store quoted string in cache and return.# Check if ' ' in string, where string may either be a str or bytes. If# there are no spaces, the regular quote will produce the right answer.# Normalize 'safe' by converting to bytes and removing non-ASCII chars# It's a bother at times that strings and string-like objects are# sequences.# non-sequence items should not work with len()# non-empty strings will fail this# Zero-length sequences of all types will get here and succeed,# but that's a minor nit. Since the original implementation# allowed empty dicts that type of behavior probably should be# preserved for consistency# Is this a sufficient test for sequence-ness?# not a sequence# loop over the sequence# Most URL schemes require ASCII. If that changes, the conversion# can be relaxed.# XXX get rid of to_bytes()# splittag('/path#tag') --> '/path', 'tag'b'Parse (absolute and relative) URLs. + +urlparse module is based upon the following RFC specifications. + +RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding +and L. Masinter, January 2005. + +RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter +and L.Masinter, December 1999. + +RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T. +Berners-Lee, R. Fielding, and L. Masinter, August 1998. + +RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998. + +RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June +1995. + +RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M. +McCahill, December 1994 + +RFC 3986 is considered the current standard and any future changes to +urlparse module should conform with it. The urlparse module is +currently not entirely compliant with this RFC due to defacto +scenarios for parsing, and for backward compatibility purposes, some +parsing quirks from older RFCs are retained. The testcases in +test_urlparse.py provides a good indicator of parsing behavior. +'u'Parse (absolute and relative) URLs. + +urlparse module is based upon the following RFC specifications. + +RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding +and L. Masinter, January 2005. + +RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter +and L.Masinter, December 1999. + +RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T. +Berners-Lee, R. Fielding, and L. Masinter, August 1998. + +RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998. + +RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June +1995. + +RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M. +McCahill, December 1994 + +RFC 3986 is considered the current standard and any future changes to +urlparse module should conform with it. The urlparse module is +currently not entirely compliant with this RFC due to defacto +scenarios for parsing, and for backward compatibility purposes, some +parsing quirks from older RFCs are retained. The testcases in +test_urlparse.py provides a good indicator of parsing behavior. +'b'urlunparse'u'urlunparse'b'urljoin'u'urljoin'b'urldefrag'u'urldefrag'b'urlsplit'u'urlsplit'b'urlunsplit'u'urlunsplit'b'parse_qs'u'parse_qs'b'parse_qsl'u'parse_qsl'b'quote_from_bytes'u'quote_from_bytes'b'unquote_to_bytes'u'unquote_to_bytes'b'DefragResult'u'DefragResult'b'ParseResult'u'ParseResult'b'SplitResult'u'SplitResult'b'DefragResultBytes'u'DefragResultBytes'b'ParseResultBytes'u'ParseResultBytes'b'SplitResultBytes'u'SplitResultBytes'b'gopher'u'gopher'b'nntp'u'nntp'b'wais'u'wais'b'shttp'u'shttp'b'mms'u'mms'b'prospero'u'prospero'b'rtsp'u'rtsp'b'rtspu'u'rtspu'b'sftp'u'sftp'b'svn'u'svn'b'svn+ssh'u'svn+ssh'b'ws'u'ws'b'wss'u'wss'b'telnet'u'telnet'b'snews'u'snews'b'rsync'u'rsync'b'nfs'u'nfs'b'git'u'git'b'git+ssh'u'git+ssh'b'hdl'u'hdl'b'sip'u'sip'b'sips'u'sips'b'tel'u'tel'b'mailto'u'mailto'b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.'u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.'b'Clear the parse cache and the quoters cache.'u'Clear the parse cache and the quoters cache.'b'Cannot mix str and non-str arguments'u'Cannot mix str and non-str arguments'b'Standard approach to encoding parsed results from str to bytes'u'Standard approach to encoding parsed results from str to bytes'b'Standard approach to decoding parsed results from bytes to str'u'Standard approach to decoding parsed results from bytes to str'b'Shared methods for the parsed result objects containing a netloc element'u'Shared methods for the parsed result objects containing a netloc element'b'Port could not be cast to integer value as 'u'Port could not be cast to integer value as 'b'Port out of range 0-65535'u'Port out of range 0-65535'b'url fragment'u'url fragment'b'scheme netloc path query fragment'u'scheme netloc path query fragment'b'scheme netloc path params query fragment'u'scheme netloc path params query fragment'b' +DefragResult(url, fragment) + +A 2-tuple that contains the url without fragment identifier and the fragment +identifier as a separate argument. +'u' +DefragResult(url, fragment) + +A 2-tuple that contains the url without fragment identifier and the fragment +identifier as a separate argument. +'b'The URL with no fragment identifier.'u'The URL with no fragment identifier.'b' +Fragment identifier separated from URL, that allows indirect identification of a +secondary resource by reference to a primary resource and additional identifying +information. +'u' +Fragment identifier separated from URL, that allows indirect identification of a +secondary resource by reference to a primary resource and additional identifying +information. +'b' +SplitResult(scheme, netloc, path, query, fragment) + +A 5-tuple that contains the different components of a URL. Similar to +ParseResult, but does not split params. +'u' +SplitResult(scheme, netloc, path, query, fragment) + +A 5-tuple that contains the different components of a URL. Similar to +ParseResult, but does not split params. +'b'Specifies URL scheme for the request.'u'Specifies URL scheme for the request.'b' +Network location where the request is made to. +'u' +Network location where the request is made to. +'b' +The hierarchical path, such as the path to a file to download. +'u' +The hierarchical path, such as the path to a file to download. +'b' +The query component, that contains non-hierarchical data, that along with data +in path component, identifies a resource in the scope of URI's scheme and +network location. +'u' +The query component, that contains non-hierarchical data, that along with data +in path component, identifies a resource in the scope of URI's scheme and +network location. +'b' +Fragment identifier, that allows indirect identification of a secondary resource +by reference to a primary resource and additional identifying information. +'u' +Fragment identifier, that allows indirect identification of a secondary resource +by reference to a primary resource and additional identifying information. +'b' +ParseResult(scheme, netloc, path, params, query, fragment) + +A 6-tuple that contains components of a parsed URL. +'u' +ParseResult(scheme, netloc, path, params, query, fragment) + +A 6-tuple that contains components of a parsed URL. +'b' +Parameters for last path element used to dereference the URI in order to provide +access to perform some operation on the resource. +'u' +Parameters for last path element used to dereference the URI in order to provide +access to perform some operation on the resource. +'b'Parse a URL into 6 components: + :///;?# + Return a 6-tuple: (scheme, netloc, path, params, query, fragment). + Note that we don't break the components up in smaller bits + (e.g. netloc is a single string) and we don't expand % escapes.'u'Parse a URL into 6 components: + :///;?# + Return a 6-tuple: (scheme, netloc, path, params, query, fragment). + Note that we don't break the components up in smaller bits + (e.g. netloc is a single string) and we don't expand % escapes.'b'/?#'u'/?#'b'NFKC'u'NFKC'b'/?#@:'u'/?#@:'b'netloc ''u'netloc ''b'' contains invalid 'u'' contains invalid 'b'characters under NFKC normalization'u'characters under NFKC normalization'b'Parse a URL into 5 components: + :///?# + Return a 5-tuple: (scheme, netloc, path, query, fragment). + Note that we don't break the components up in smaller bits + (e.g. netloc is a single string) and we don't expand % escapes.'u'Parse a URL into 5 components: + :///?# + Return a 5-tuple: (scheme, netloc, path, query, fragment). + Note that we don't break the components up in smaller bits + (e.g. netloc is a single string) and we don't expand % escapes.'b'Invalid IPv6 URL'u'Invalid IPv6 URL'b'Put a parsed URL back together again. This may result in a + slightly different, but equivalent URL, if the URL that was parsed + originally had redundant delimiters, e.g. a ? with an empty query + (the draft states that these are equivalent).'u'Put a parsed URL back together again. This may result in a + slightly different, but equivalent URL, if the URL that was parsed + originally had redundant delimiters, e.g. a ? with an empty query + (the draft states that these are equivalent).'b'%s;%s'u'%s;%s'b'Combine the elements of a tuple as returned by urlsplit() into a + complete URL as a string. The data argument can be any five-item iterable. + This may result in a slightly different, but equivalent URL, if the URL that + was parsed originally had unnecessary delimiters (for example, a ? with an + empty query; the RFC states that these are equivalent).'u'Combine the elements of a tuple as returned by urlsplit() into a + complete URL as a string. The data argument can be any five-item iterable. + This may result in a slightly different, but equivalent URL, if the URL that + was parsed originally had unnecessary delimiters (for example, a ? with an + empty query; the RFC states that these are equivalent).'b'Join a base URL and a possibly relative URL to form an absolute + interpretation of the latter.'u'Join a base URL and a possibly relative URL to form an absolute + interpretation of the latter.'b'Removes any existing fragment from URL. + + Returns a tuple of the defragmented URL and the fragment. If + the URL contained no fragments, the second element is the + empty string. + 'u'Removes any existing fragment from URL. + + Returns a tuple of the defragmented URL and the fragment. If + the URL contained no fragments, the second element is the + empty string. + 'b'0123456789ABCDEFabcdef'u'0123456789ABCDEFabcdef'b'unquote_to_bytes('abc%20def') -> b'abc def'.'u'unquote_to_bytes('abc%20def') -> b'abc def'.'b'([-]+)'u'([-]+)'b'Replace %xx escapes by their single-character equivalent. The optional + encoding and errors parameters specify how to decode percent-encoded + sequences into Unicode characters, as accepted by the bytes.decode() + method. + By default, percent-encoded sequences are decoded with UTF-8, and invalid + sequences are replaced by a placeholder character. + + unquote('abc%20def') -> 'abc def'. + 'u'Replace %xx escapes by their single-character equivalent. The optional + encoding and errors parameters specify how to decode percent-encoded + sequences into Unicode characters, as accepted by the bytes.decode() + method. + By default, percent-encoded sequences are decoded with UTF-8, and invalid + sequences are replaced by a placeholder character. + + unquote('abc%20def') -> 'abc def'. + 'b'Expected str, got bytes'u'Expected str, got bytes'b'Parse a query given as a string argument. + + Arguments: + + qs: percent-encoded query string to be parsed + + keep_blank_values: flag indicating whether blank values in + percent-encoded queries should be treated as blank strings. + A true value indicates that blanks should be retained as + blank strings. The default false value indicates that + blank values are to be ignored and treated as if they were + not included. + + strict_parsing: flag indicating what to do with parsing errors. + If false (the default), errors are silently ignored. + If true, errors raise a ValueError exception. + + encoding and errors: specify how to decode percent-encoded sequences + into Unicode characters, as accepted by the bytes.decode() method. + + max_num_fields: int. If set, then throws a ValueError if there + are more than n fields read by parse_qsl(). + + separator: str. The symbol to use for separating the query arguments. + Defaults to &. + + Returns a dictionary. + 'u'Parse a query given as a string argument. + + Arguments: + + qs: percent-encoded query string to be parsed + + keep_blank_values: flag indicating whether blank values in + percent-encoded queries should be treated as blank strings. + A true value indicates that blanks should be retained as + blank strings. The default false value indicates that + blank values are to be ignored and treated as if they were + not included. + + strict_parsing: flag indicating what to do with parsing errors. + If false (the default), errors are silently ignored. + If true, errors raise a ValueError exception. + + encoding and errors: specify how to decode percent-encoded sequences + into Unicode characters, as accepted by the bytes.decode() method. + + max_num_fields: int. If set, then throws a ValueError if there + are more than n fields read by parse_qsl(). + + separator: str. The symbol to use for separating the query arguments. + Defaults to &. + + Returns a dictionary. + 'b'Parse a query given as a string argument. + + Arguments: + + qs: percent-encoded query string to be parsed + + keep_blank_values: flag indicating whether blank values in + percent-encoded queries should be treated as blank strings. + A true value indicates that blanks should be retained as blank + strings. The default false value indicates that blank values + are to be ignored and treated as if they were not included. + + strict_parsing: flag indicating what to do with parsing errors. If + false (the default), errors are silently ignored. If true, + errors raise a ValueError exception. + + encoding and errors: specify how to decode percent-encoded sequences + into Unicode characters, as accepted by the bytes.decode() method. + + max_num_fields: int. If set, then throws a ValueError + if there are more than n fields read by parse_qsl(). + + separator: str. The symbol to use for separating the query arguments. + Defaults to &. + + Returns a list, as G-d intended. + 'u'Parse a query given as a string argument. + + Arguments: + + qs: percent-encoded query string to be parsed + + keep_blank_values: flag indicating whether blank values in + percent-encoded queries should be treated as blank strings. + A true value indicates that blanks should be retained as blank + strings. The default false value indicates that blank values + are to be ignored and treated as if they were not included. + + strict_parsing: flag indicating what to do with parsing errors. If + false (the default), errors are silently ignored. If true, + errors raise a ValueError exception. + + encoding and errors: specify how to decode percent-encoded sequences + into Unicode characters, as accepted by the bytes.decode() method. + + max_num_fields: int. If set, then throws a ValueError + if there are more than n fields read by parse_qsl(). + + separator: str. The symbol to use for separating the query arguments. + Defaults to &. + + Returns a list, as G-d intended. + 'b'Separator must be of type string or bytes.'u'Separator must be of type string or bytes.'b'Max number of fields exceeded'u'Max number of fields exceeded'b'bad query field: %r'u'bad query field: %r'b'Like unquote(), but also replace plus signs by spaces, as required for + unquoting HTML form values. + + unquote_plus('%7e/abc+def') -> '~/abc def' + 'u'Like unquote(), but also replace plus signs by spaces, as required for + unquoting HTML form values. + + unquote_plus('%7e/abc+def') -> '~/abc def' + 'b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-~'b'A mapping from bytes (in range(0,256)) to strings. + + String values are percent-encoded byte values, unless the key < 128, and + in the "safe" set (either the specified safe set, or default set). + 'u'A mapping from bytes (in range(0,256)) to strings. + + String values are percent-encoded byte values, unless the key < 128, and + in the "safe" set (either the specified safe set, or default set). + 'b'safe: bytes object.'u'safe: bytes object.'b'%{:02X}'u'%{:02X}'b'quote('abc def') -> 'abc%20def' + + Each part of a URL, e.g. the path info, the query, etc., has a + different set of reserved characters that must be quoted. The + quote function offers a cautious (not minimal) way to quote a + string for most of these parts. + + RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists + the following (un)reserved characters. + + unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + reserved = gen-delims / sub-delims + gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" + sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + / "*" / "+" / "," / ";" / "=" + + Each of the reserved characters is reserved in some component of a URL, + but not necessarily in all of them. + + The quote function %-escapes all characters that are neither in the + unreserved chars ("always safe") nor the additional chars set via the + safe arg. + + The default for the safe arg is '/'. The character is reserved, but in + typical usage the quote function is being called on a path where the + existing slash characters are to be preserved. + + Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings. + Now, "~" is included in the set of unreserved characters. + + string and safe may be either str or bytes objects. encoding and errors + must not be specified if string is a bytes object. + + The optional encoding and errors parameters specify how to deal with + non-ASCII characters, as accepted by the str.encode method. + By default, encoding='utf-8' (characters are encoded with UTF-8), and + errors='strict' (unsupported characters raise a UnicodeEncodeError). + 'u'quote('abc def') -> 'abc%20def' + + Each part of a URL, e.g. the path info, the query, etc., has a + different set of reserved characters that must be quoted. The + quote function offers a cautious (not minimal) way to quote a + string for most of these parts. + + RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists + the following (un)reserved characters. + + unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + reserved = gen-delims / sub-delims + gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" + sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + / "*" / "+" / "," / ";" / "=" + + Each of the reserved characters is reserved in some component of a URL, + but not necessarily in all of them. + + The quote function %-escapes all characters that are neither in the + unreserved chars ("always safe") nor the additional chars set via the + safe arg. + + The default for the safe arg is '/'. The character is reserved, but in + typical usage the quote function is being called on a path where the + existing slash characters are to be preserved. + + Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings. + Now, "~" is included in the set of unreserved characters. + + string and safe may be either str or bytes objects. encoding and errors + must not be specified if string is a bytes object. + + The optional encoding and errors parameters specify how to deal with + non-ASCII characters, as accepted by the str.encode method. + By default, encoding='utf-8' (characters are encoded with UTF-8), and + errors='strict' (unsupported characters raise a UnicodeEncodeError). + 'b'quote() doesn't support 'encoding' for bytes'u'quote() doesn't support 'encoding' for bytes'b'quote() doesn't support 'errors' for bytes'u'quote() doesn't support 'errors' for bytes'b'Like quote(), but also replace ' ' with '+', as required for quoting + HTML form values. Plus signs in the original string are escaped unless + they are included in safe. It also does not have safe default to '/'. + 'u'Like quote(), but also replace ' ' with '+', as required for quoting + HTML form values. Plus signs in the original string are escaped unless + they are included in safe. It also does not have safe default to '/'. + 'b'Like quote(), but accepts a bytes object rather than a str, and does + not perform string-to-bytes encoding. It always returns an ASCII string. + quote_from_bytes(b'abc def?') -> 'abc%20def%3f' + 'u'Like quote(), but accepts a bytes object rather than a str, and does + not perform string-to-bytes encoding. It always returns an ASCII string. + quote_from_bytes(b'abc def?') -> 'abc%20def%3f' + 'b'quote_from_bytes() expected bytes'u'quote_from_bytes() expected bytes'b'Encode a dict or sequence of two-element tuples into a URL query string. + + If any values in the query arg are sequences and doseq is true, each + sequence element is converted to a separate parameter. + + If the query arg is a sequence of two-element tuples, the order of the + parameters in the output will match the order of parameters in the + input. + + The components of a query arg may each be either a string or a bytes type. + + The safe, encoding, and errors parameters are passed down to the function + specified by quote_via (encoding and errors only if a component is a str). + 'u'Encode a dict or sequence of two-element tuples into a URL query string. + + If any values in the query arg are sequences and doseq is true, each + sequence element is converted to a separate parameter. + + If the query arg is a sequence of two-element tuples, the order of the + parameters in the output will match the order of parameters in the + input. + + The components of a query arg may each be either a string or a bytes type. + + The safe, encoding, and errors parameters are passed down to the function + specified by quote_via (encoding and errors only if a component is a str). + 'b'items'b'not a valid non-string sequence or mapping object'u'not a valid non-string sequence or mapping object'b'urllib.parse.to_bytes() is deprecated as of 3.8'u'urllib.parse.to_bytes() is deprecated as of 3.8'b'to_bytes(u"URL") --> 'URL'.'u'to_bytes(u"URL") --> 'URL'.'b'URL 'u'URL 'b' contains non-ASCII characters'u' contains non-ASCII characters'b'Transform a string like '' into 'scheme://host/path'. + + The string is returned unchanged if it's not a wrapped URL. + 'u'Transform a string like '' into 'scheme://host/path'. + + The string is returned unchanged if it's not a wrapped URL. + 'b'URL:'u'URL:'b'urllib.parse.splittype() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splittype() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splittype('type:opaquestring') --> 'type', 'opaquestring'.'u'splittype('type:opaquestring') --> 'type', 'opaquestring'.'b'([^/:]+):(.*)'u'([^/:]+):(.*)'b'urllib.parse.splithost() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splithost() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splithost('//host[:port]/path') --> 'host[:port]', '/path'.'u'splithost('//host[:port]/path') --> 'host[:port]', '/path'.'b'//([^/#?]*)(.*)'u'//([^/#?]*)(.*)'b'urllib.parse.splituser() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splituser() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.'u'splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.'b'urllib.parse.splitpasswd() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splitpasswd() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splitpasswd('user:passwd') -> 'user', 'passwd'.'u'splitpasswd('user:passwd') -> 'user', 'passwd'.'b'urllib.parse.splitport() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splitport() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splitport('host:port') --> 'host', 'port'.'u'splitport('host:port') --> 'host', 'port'.'b'(.*):([0-9]*)'u'(.*):([0-9]*)'b'urllib.parse.splitnport() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splitnport() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'Split host and port, returning numeric port. + Return given default port if no ':' found; defaults to -1. + Return numerical port if a valid number are found after ':'. + Return None if ':' but not a valid number.'u'Split host and port, returning numeric port. + Return given default port if no ':' found; defaults to -1. + Return numerical port if a valid number are found after ':'. + Return None if ':' but not a valid number.'b'urllib.parse.splitquery() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splitquery() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splitquery('/path?query') --> '/path', 'query'.'u'splitquery('/path?query') --> '/path', 'query'.'b'urllib.parse.splittag() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splittag() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splittag('/path#tag') --> '/path', 'tag'.'u'splittag('/path#tag') --> '/path', 'tag'.'b'urllib.parse.splitattr() is deprecated as of 3.8, use urllib.parse.urlparse() instead'u'urllib.parse.splitattr() is deprecated as of 3.8, use urllib.parse.urlparse() instead'b'splitattr('/path;attr1=value1;attr2=value2;...') -> + '/path', ['attr1=value1', 'attr2=value2', ...].'u'splitattr('/path;attr1=value1;attr2=value2;...') -> + '/path', ['attr1=value1', 'attr2=value2', ...].'b'urllib.parse.splitvalue() is deprecated as of 3.8, use urllib.parse.parse_qsl() instead'u'urllib.parse.splitvalue() is deprecated as of 3.8, use urllib.parse.parse_qsl() instead'b'splitvalue('attr=value') --> 'attr', 'value'.'u'splitvalue('attr=value') --> 'attr', 'value'.'A parser of RFC 2822 and MIME email messages.HeaderParserBytesHeaderParseremail.feedparserParser of RFC 2822 and MIME email messages. + + Creates an in-memory object tree representing the email message, which + can then be manipulated and turned over to a Generator to return the + textual representation of the message. + + The string must be formatted as a block of RFC 2822 headers and header + continuation lines, optionally preceded by a `Unix-from' header. The + header block is terminated either by the end of the string or by a + blank line. + + _class is the class to instantiate for new message objects when they + must be created. This class must have a constructor that can take + zero arguments. Default is Message.Message. + + The policy keyword specifies a policy object that controls a number of + aspects of the parser's operation. The default policy maintains + backward compatibility. + + headersonlyCreate a message structure from the data in a file. + + Reads all the data from the file and returns the root of the message + structure. Optional headersonly is a flag specifying whether to stop + parsing after reading the headers or not. The default is False, + meaning it parses the entire contents of the file. + Create a message structure from a string. + + Returns the root of the message structure. Optional headersonly is a + flag specifying whether to stop parsing after reading the headers or + not. The default is False, meaning it parses the entire contents of + the file. + Parser of binary RFC 2822 and MIME email messages. + + Creates an in-memory object tree representing the email message, which + can then be manipulated and turned over to a Generator to return the + textual representation of the message. + + The input must be formatted as a block of RFC 2822 headers and header + continuation lines, optionally preceded by a `Unix-from' header. The + header block is terminated either by the end of the input or by a + blank line. + + _class is the class to instantiate for new message objects when they + must be created. This class must have a constructor that can take + zero arguments. Default is Message.Message. + Create a message structure from the data in a binary file. + + Reads all the data from the file and returns the root of the message + structure. Optional headersonly is a flag specifying whether to stop + parsing after reading the headers or not. The default is False, + meaning it parses the entire contents of the file. + Create a message structure from a byte string. + + Returns the root of the message structure. Optional headersonly is a + flag specifying whether to stop parsing after reading the headers or + not. The default is False, meaning it parses the entire contents of + the file. + # Author: Barry Warsaw, Thomas Wouters, Anthony Baxterb'A parser of RFC 2822 and MIME email messages.'u'A parser of RFC 2822 and MIME email messages.'b'Parser'u'Parser'b'HeaderParser'u'HeaderParser'b'BytesParser'u'BytesParser'b'BytesHeaderParser'u'BytesHeaderParser'b'Parser of RFC 2822 and MIME email messages. + + Creates an in-memory object tree representing the email message, which + can then be manipulated and turned over to a Generator to return the + textual representation of the message. + + The string must be formatted as a block of RFC 2822 headers and header + continuation lines, optionally preceded by a `Unix-from' header. The + header block is terminated either by the end of the string or by a + blank line. + + _class is the class to instantiate for new message objects when they + must be created. This class must have a constructor that can take + zero arguments. Default is Message.Message. + + The policy keyword specifies a policy object that controls a number of + aspects of the parser's operation. The default policy maintains + backward compatibility. + + 'u'Parser of RFC 2822 and MIME email messages. + + Creates an in-memory object tree representing the email message, which + can then be manipulated and turned over to a Generator to return the + textual representation of the message. + + The string must be formatted as a block of RFC 2822 headers and header + continuation lines, optionally preceded by a `Unix-from' header. The + header block is terminated either by the end of the string or by a + blank line. + + _class is the class to instantiate for new message objects when they + must be created. This class must have a constructor that can take + zero arguments. Default is Message.Message. + + The policy keyword specifies a policy object that controls a number of + aspects of the parser's operation. The default policy maintains + backward compatibility. + + 'b'Create a message structure from the data in a file. + + Reads all the data from the file and returns the root of the message + structure. Optional headersonly is a flag specifying whether to stop + parsing after reading the headers or not. The default is False, + meaning it parses the entire contents of the file. + 'u'Create a message structure from the data in a file. + + Reads all the data from the file and returns the root of the message + structure. Optional headersonly is a flag specifying whether to stop + parsing after reading the headers or not. The default is False, + meaning it parses the entire contents of the file. + 'b'Create a message structure from a string. + + Returns the root of the message structure. Optional headersonly is a + flag specifying whether to stop parsing after reading the headers or + not. The default is False, meaning it parses the entire contents of + the file. + 'u'Create a message structure from a string. + + Returns the root of the message structure. Optional headersonly is a + flag specifying whether to stop parsing after reading the headers or + not. The default is False, meaning it parses the entire contents of + the file. + 'b'Parser of binary RFC 2822 and MIME email messages. + + Creates an in-memory object tree representing the email message, which + can then be manipulated and turned over to a Generator to return the + textual representation of the message. + + The input must be formatted as a block of RFC 2822 headers and header + continuation lines, optionally preceded by a `Unix-from' header. The + header block is terminated either by the end of the input or by a + blank line. + + _class is the class to instantiate for new message objects when they + must be created. This class must have a constructor that can take + zero arguments. Default is Message.Message. + 'u'Parser of binary RFC 2822 and MIME email messages. + + Creates an in-memory object tree representing the email message, which + can then be manipulated and turned over to a Generator to return the + textual representation of the message. + + The input must be formatted as a block of RFC 2822 headers and header + continuation lines, optionally preceded by a `Unix-from' header. The + header block is terminated either by the end of the input or by a + blank line. + + _class is the class to instantiate for new message objects when they + must be created. This class must have a constructor that can take + zero arguments. Default is Message.Message. + 'b'Create a message structure from the data in a binary file. + + Reads all the data from the file and returns the root of the message + structure. Optional headersonly is a flag specifying whether to stop + parsing after reading the headers or not. The default is False, + meaning it parses the entire contents of the file. + 'u'Create a message structure from the data in a binary file. + + Reads all the data from the file and returns the root of the message + structure. Optional headersonly is a flag specifying whether to stop + parsing after reading the headers or not. The default is False, + meaning it parses the entire contents of the file. + 'b'Create a message structure from a byte string. + + Returns the root of the message structure. Optional headersonly is a + flag specifying whether to stop parsing after reading the headers or + not. The default is False, meaning it parses the entire contents of + the file. + 'u'Create a message structure from a byte string. + + Returns the root of the message structure. Optional headersonly is a + flag specifying whether to stop parsing after reading the headers or + not. The default is False, meaning it parses the entire contents of + the file. + 'u'email.parser'Pattern compiler. + +The grammar is taken from PatternGrammar.txt. + +The compiler compiles a pattern to a pytree.*Pattern instance. +driverliteralsPatternSyntaxErrortokenize_wrapperTokenizes a string suppressing significant whitespace.PatternCompilergrammar_fileInitializer. + + Takes an optional alternative filename for the pattern grammar. + pattern_grammarSymbolspython_grammarpygrammarpattern_convertwith_treeCompiles a pattern string to a nested pytree.*Pattern object.compile_nodeCompiles a node, recursively. + + This is one big switch on the node type. + altsWildcardPatternNegatedUnitcompile_basicNegatedPatternHUGEPLUSget_intLeafPattern_type_of_literalTOKEN_MAPInvalid token: %rCan't have details for tokenInvalid symbol: %rNodePatternTOKENraw_node_infoConverts raw node information to a Node or Leaf instance.# Fairly local imports# Really local imports# XXX Optimize certain Wildcard-containing-Wildcard patterns# that can be merged# Avoid unneeded recursion# Skip the odd children since they are just '|' tokens# Now we've reduced it to: STRING | NAME [Details] | (...) | [...]# Compile STRING | NAME [Details] | (...) | [...]# Details present# Map named tokens to the type value for a LeafPatternb'Pattern compiler. + +The grammar is taken from PatternGrammar.txt. + +The compiler compiles a pattern to a pytree.*Pattern instance. +'u'Pattern compiler. + +The grammar is taken from PatternGrammar.txt. + +The compiler compiles a pattern to a pytree.*Pattern instance. +'b'Tokenizes a string suppressing significant whitespace.'u'Tokenizes a string suppressing significant whitespace.'b'Initializer. + + Takes an optional alternative filename for the pattern grammar. + 'u'Initializer. + + Takes an optional alternative filename for the pattern grammar. + 'b'Compiles a pattern string to a nested pytree.*Pattern object.'u'Compiles a pattern string to a nested pytree.*Pattern object.'b'Compiles a node, recursively. + + This is one big switch on the node type. + 'u'Compiles a node, recursively. + + This is one big switch on the node type. + 'b'Invalid token: %r'u'Invalid token: %r'b'Can't have details for token'u'Can't have details for token'b'Invalid symbol: %r'u'Invalid symbol: %r'b'NAME'u'NAME'b'STRING'u'STRING'b'NUMBER'u'NUMBER'b'TOKEN'u'TOKEN'b'Converts raw node information to a Node or Leaf instance.'u'Converts raw node information to a Node or Leaf instance.'u'lib2to3.patcomp'u'patcomp' +The Python Debugger Pdb +======================= + +To use the debugger in its simplest form: + + >>> import pdb + >>> pdb.run('') + +The debugger's prompt is '(Pdb) '. This will stop in the first +function call in . + +Alternatively, if a statement terminated with an unhandled exception, +you can use pdb's post-mortem facility to inspect the contents of the +traceback: + + >>> + + >>> import pdb + >>> pdb.pm() + +The commands recognized by the debugger are listed in the next +section. Most can be abbreviated as indicated; e.g., h(elp) means +that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel', +nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in +square brackets. Alternatives in the command syntax are separated +by a vertical bar (|). + +A blank line repeats the previous command literally, except for +'list', where it lists the next 11 lines. + +Commands that the debugger doesn't recognize are assumed to be Python +statements and are executed in the context of the program being +debugged. Python statements can also be prefixed with an exclamation +point ('!'). This is a powerful way to inspect the program being +debugged; it is even possible to change variables or call functions. +When an exception occurs in such a statement, the exception name is +printed but the debugger's state is not changed. + +The debugger supports aliases, which can save typing. And aliases can +have parameters (see the alias help entry) which allows one a certain +level of adaptability to the context under examination. + +Multiple commands may be entered on a single line, separated by the +pair ';;'. No intelligence is applied to separating the commands; the +input is split at the first ';;', even if it is in the middle of a +quoted string. + +If a file ".pdbrc" exists in your home directory or in the current +directory, it is read in and executed as if it had been typed at the +debugger prompt. This is particularly useful for aliases. If both +files exist, the one in the home directory is read first and aliases +defined there can be overridden by the local file. This behavior can be +disabled by passing the "readrc=False" argument to the Pdb constructor. + +Aside from aliases, the debugger is not directly programmable; but it +is implemented as a class from which you can derive your own debugger +class, which you can make as fancy as you like. + + +Debugger commands +================= + +bdbRestartCauses a debugger to be restarted for the debugged python program.post_mortemfind_functiondef\s+%s\s*[(]crelasti2lineno_rstrString that doesn't quote its repr. +-> line_prefix_previous_sigint_handlerreadrcpdb.Pdb(Pdb) displayingmainpyfile_wait_for_mainpyfileset_completer_delims +`@#$%^&*()=+[{]}\|;:'",<>?allow_kbdintrcLines~/.pdbrcrcFile.pdbrccommands_dopromptcommands_silentcommands_definingcommands_bnumsigint_handler +Program interrupted. (Use 'cont' to resume).curindexcurframecurframe_localsexecRcLinesThis method is called when there is the remote possibility + that we ever need to stop in this function.--Call--This function is called when we stop or break at this line.bp_commandsCall every command that was set for the current active breakpoint + (if there is one). + + Returns True if the normal interaction function must be called, + False otherwise.lastcmd_backprint_stack_entry_cmdloopThis function is called when a return trap is set here.--Return--This function is called if an exception occurs, + but only if we are to stop at or just below this level.__exception__Internal --KeyboardInterrupt--_getval_exceptdisplay %s: %r [old: %r]Custom displayhook for the exec in default(), which prevents + assignment of the _ variable in the builtins. + save_stdinHandle alias expansion and ';;' separator.tmpArg%*;;markerInterpret the argument as though it had been typed in response + to the prompt. + + Checks whether this line is typed at the normal prompt or in + a breakpoint command list definition. + handle_command_defHandles one command line during command list definition.silentcmdlistcommands_resuming***_complete_location_complete_expression_complete_bpnumberdotteddo_commandscommands [bpnumber] + (com) ... + (com) end + (Pdb) + + Specify a list of commands for breakpoint number bpnumber. + The commands themselves are entered on the following lines. + Type a line containing just 'end' to terminate the commands. + The commands are executed when the breakpoint is hit. + + To remove all commands from a breakpoint, type commands and + follow it immediately with end; that is, give no commands. + + With no bpnumber argument, commands refers to the last + breakpoint set. + + You can use breakpoint commands to start your program up + again. Simply use the continue command, or step, or any other + command that resumes execution. + + Specifying any command resuming execution (currently continue, + step, next, return, jump, quit and their abbreviations) + terminates the command list (as if that command was + immediately followed by end). This is because any time you + resume execution (even with a simple next or step), you may + encounter another breakpoint -- which could have its own + command list, leading to ambiguities about which list to + execute. + + If you use the 'silent' command in the command list, the usual + message about stopping at a breakpoint is not printed. This + may be desirable for breakpoints that are to print a specific + message and then continue. If none of the other commands + print anything, you will see no sign that the breakpoint was + reached. + bnumUsage: commands [bnum] + ... + endold_command_defsprompt_back(com) command definition aborted, old commands restoredcomplete_commandsdo_breakb(reak) [ ([filename:]lineno | function) [, condition] ] + Without argument, list all breaks. + + With a line number argument, set a break at this line in the + current file. With a function name, set a break at the first + executable line of that function. If a second argument is + present, it is a string specifying an expression which must + evaluate to true before the breakpoint is honored. + + The line number may be prefixed with a filename and a colon, + to specify a breakpoint in another file (probably one that + hasn't been loaded yet). The file is searched for on + sys.path; the .py suffix may be omitted. + Num Type Disp Enb Wherelookupmodule%r not found from sys.pathBad lineno: %slineinfoThe specified object %r is not a function or was not found along sys.path.'The specified object %r is not a function ''or was not found along sys.path.'defaultFilechecklineBreakpoint %d at %s:%dProduce a reasonable default.do_bcomplete_breakcomplete_bdo_tbreaktbreak [ ([filename:]lineno | function) [, condition] ] + Same arguments as break, but sets a temporary breakpoint: it + is automatically deleted when first hit. + complete_tbreakidentifieridstringCheck whether specified line seems to be executable. + + Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank + line or EOF). Warning: testing is not comprehensive. + End of fileBlank or commentdo_enableenable bpnumber [bpnumber ...] + Enables the breakpoints given as a space separated list of + breakpoint numbers. + Enabled %scomplete_enabledo_disabledisable bpnumber [bpnumber ...] + Disables the breakpoints given as a space separated list of + breakpoint numbers. Disabling a breakpoint means it cannot + cause the program to stop execution, but unlike clearing a + breakpoint, it remains in the list of breakpoints and can be + (re-)enabled. + Disabled %scomplete_disabledo_conditioncondition bpnumber [condition] + Set a new condition for the breakpoint, an expression which + must evaluate to true before the breakpoint is honored. If + condition is absent, any existing condition is removed; i.e., + the breakpoint is made unconditional. + Breakpoint %d is now unconditional.New condition set for breakpoint %d.complete_conditiondo_ignoreignore bpnumber [count] + Set the ignore count for the given breakpoint number. If + count is omitted, the ignore count is set to 0. A breakpoint + becomes active when the ignore count is zero. When non-zero, + the count is decremented each time the breakpoint is reached + and the breakpoint is not disabled and any associated + condition evaluates to true. + %d crossingscountstr1 crossingWill ignore next %s of breakpoint %d.Will stop next time breakpoint %d is reached.complete_ignorecl(ear) filename:lineno +cl(ear) [bpnumber [bpnumber...]] + With a space separated list of breakpoint numbers, clear + those breakpoints. Without argument, clear all breaks (but + first ask confirmation). With a filename:lineno argument, + clear all breaks at that line in that file. + Clear all breaks? replyyesDeleted %sInvalid line number (%s)numberlistdo_clcomplete_clearcomplete_cldo_wherew(here) + Print a stack trace, with the most recent frame at the bottom. + An arrow indicates the "current frame", which determines the + context of most commands. 'bt' is an alias for this command. + print_stack_tracedo_wdo_bt_select_framedo_upu(p) [count] + Move the current frame count (default one) levels up in the + stack trace (to an older frame). + Oldest frameInvalid frame count (%s)newframedo_udo_downd(own) [count] + Move the current frame count (default one) levels down in the + stack trace (to a newer frame). + Newest framedo_ddo_untilunt(il) [lineno] + Without argument, continue execution until the line with a + number greater than the current one is reached. With a line + number, continue execution until a line with a number greater + or equal to that is reached. In both cases, also stop when + the current frame returns. + Error in argument: %r"until" line number is smaller than current line number'"until" line number is smaller than current ''line number'do_untdo_steps(tep) + Execute the current line, stop at the first possible occasion + (either in a function that is called or in the current + function). + do_sdo_nextn(ext) + Continue execution until the next line in the current function + is reached or it returns. + do_ndo_runrun [args...] + Restart the debugged python program. If a string is supplied + it is split with "shlex", and the result is used as the new + sys.argv. History, breakpoints, actions and debugger options + are preserved. "restart" is an alias for "run". + argv0do_restartdo_returnr(eturn) + Continue execution until the current function returns. + do_rdo_continuec(ont(inue)) + Continue execution, only stop when a breakpoint is encountered. + do_cdo_contdo_jumpj(ump) lineno + Set the next line that will be executed. Only available in + the bottom-most frame. This lets you jump back and execute + code again, or jump forward to skip code that you don't want + to run. + + It should be noted that not all jumps are allowed -- for + instance it is not possible to jump into the middle of a + for loop or out of a finally clause. + You can only jump within the bottom frameJump failed: %sThe 'jump' command requires a line numberdo_jdo_debugdebug code + Enter a recursive debugger that steps through the code + argument (which is an arbitrary expression or statement to be + executed in the current environment). + ENTERING RECURSIVE DEBUGGERLEAVING RECURSIVE DEBUGGERcomplete_debugdo_quitq(uit) +exit + Quit from the debugger. The program being executed is aborted. + _user_requested_quitdo_qdo_exitdo_EOFEOF + Handles the receipt of EOF as a command. + do_argsa(rgs) + Print the argument list of the current function. + %s = %r%s = *** undefined ***do_ado_retvalretval + Print the return value for the last return of a function. + Not yet returned!do_rv_getval** raised %s **do_pp expression + Print the value of the expression. + do_pppp expression + Pretty-print the value of the expression. + complete_printcomplete_pcomplete_ppdo_listl(ist) [first [,last] | .] + + List source code for the current file. Without arguments, + list 11 lines around the current line or continue the previous + listing. With . as argument, list 11 lines around the current + line. With one argument, list 11 lines starting at that line. + With two arguments, list the given range; if the second + argument is less than the first, it is a count. + + The current line in the current frame is indicated by "->". + If an exception is being debugged, the line where the + exception was originally raised or propagated is indicated by + ">>", if it differs from the current line. + breaklist_print_lines[EOF]do_ldo_longlistlonglist | ll + List the whole source code for the current function or frame. + do_lldo_sourcesource expression + Try to get source code for the given object and display it. + complete_sourcePrint a range of lines.current_linenoexc_linenodo_whatiswhatis arg + Print the type of the argument. + Method %sFunction %sClass %s.%scomplete_whatisdo_displaydisplay [expression] + + Display the value of the expression if it changed, each time execution + stops in the current frame. + + Without expression, list all display expressions for the current frame. + Currently displaying:display %s: %rcomplete_displaydo_undisplayundisplay [expression] + + Do not display the expression any more in the current frame. + + Without expression, clear all display expressions for the current frame. + not displaying %scomplete_undisplaydo_interactinteract + + Start an interactive interpreter whose global namespace + contains all the (global and local) names found in the current scope. + *interactive*do_aliasalias [name [command [parameter parameter ...] ]] + Create an alias called 'name' that executes 'command'. The + command must *not* be enclosed in quotes. Replaceable + parameters can be indicated by %1, %2, and so on, while %* is + replaced by all the parameters. If no command is given, the + current alias for name is shown. If no name is given, all + aliases are listed. + + Aliases may be nested and can contain anything that can be + legally typed at the pdb prompt. Note! You *can* override + internal pdb commands with aliases! Those internal commands + are then hidden until the alias is removed. Aliasing is + recursively applied to the first word of the command line; all + other words in the line are left alone. + + As an example, here are two useful aliases (especially when + placed in the .pdbrc file): + + # Print instance variables (usage "pi classInst") + alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) + # Print instance variables in self + alias ps pi self + %s = %sdo_unaliasunalias name + Delete the specified alias. + complete_unaliasprompt_prefix> h(elp) + Without argument, print the list of available commands. + With a command name as argument, print help about that command. + "help pdb" shows the full pdb documentation. + "help exec" gives help on the ! command. + topicNo help for %r; please do not run Python with -OO if you need command help'No help for %r; please do not run Python with -OO ''if you need command help'No help for %rdo_hhelp_exec(!) statement + Execute the (one-line) statement in the context of the current + stack frame. The exclamation point can be omitted unless the + first word of the statement resembles a debugger command. To + assign to a global variable you must always prefix the command + with a 'global' command, e.g.: + (Pdb) global list_options; list_options = ['-l'] + (Pdb) + help_pdbHelper function for break/clear parsing -- may be overridden. + + lookupmodule() translates (possibly incomplete) file or module name + into an absolute file name. + _runmodulerunpy_get_module_detailsmod_spec_runscriptexec(compile(%r, %r, 'exec'))downuptbreakuntiljumplonglistwhatisdisplayundisplayunalias_help_order_commandexpressionA valid traceback must be passed if no exception is being handled"A valid traceback must be passed if no ""exception is being handled"import x; x.main()TESTCMDpydocpagerusage: pdb.py [-c command] ... [-m module | pyfile] [arg] ... + +Debug the Python program given by pyfile. Alternatively, +an executable module or package to debug can be specified using +the -m switch. + +Initial commands are read from .pdbrc files in your home directory +and in the current directory, if they exist. Commands supplied with +-c are executed after commands from .pdbrc files. + +To let the script run until an exception occurs, use "-c continue". +To let the script run up to a given line X in the debugged file, use +"-c 'until X'"._usagemhc:command=run_as_module--commandError:does not existThe program finished and will be restartedRestartingwith arguments:The program exited via sys.exit(). Exit status:print_excUncaught exception. Entering post mortem debuggingRunning 'cont' or 'step' will restart the programPost mortem debugger finished. The will be restarted# NOTE: the actual command documentation is collected from docstrings of the# commands and is appended to __doc__ after the class has been defined.# consumer of this info expects the first line to be 1# must be a module frame: do not try to cut a block out of it# Interaction prompt line will separate file and call info from code# text using value of line_prefix string. A newline and arrow may# be to your liking. You can set it once pdb is imported using the# command "pdb.line_prefix = '\n% '".# line_prefix = ': ' # Use this to get the old situation back# Probably a better default# Try to load readline if it exists# remove some common file name delimiters# Read ~/.pdbrc and ./.pdbrc# associates a command list to breakpoint numbers# for each bp num, tells if the prompt# must be disp. after execing the cmd list# for each bp num, tells if the stack trace# True while in the process of defining# a command list# The breakpoint number for which we are# defining a list# when setting up post-mortem debugging with a traceback, save all# the original line numbers to be displayed along the current line# numbers (which can be different, e.g. due to finally clauses)# The f_locals dictionary is updated from the actual frame# locals whenever the .f_locals accessor is called, so we# cache it here to ensure that modifications are not overwritten.# Can be executed earlier than 'setup' if desired# local copy because of recursion# execute every line only once# if onecmd returns True, the command wants to exit# from the interaction, save leftover rc lines# to execute before next interaction# Override Bdb methods# self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit# An 'Internal StopIteration' exception is an exception debug event# issued by the interpreter when handling a subgenerator run with# 'yield from' or a generator controlled by a for loop. No exception has# actually occurred in this case. The debugger uses this debug event to# stop when the debuggee is returning from such generators.# General interaction function# keyboard interrupts allow for an easy way to cancel# the current command, so allow them during interactive input# Called before loop, handles display expressions# check for identity first; this prevents custom __eq__ to# be called at every loop, and also prevents instances whose# fields are changed to be displayed# Restore the previous signal handler at the Pdb prompt.# ValueError: signal only works in main thread# no interaction desired at this time (happens if .pdbrc contains# a command like "continue")# reproduce the behavior of the standard displayhook, not printing None# split into ';;' separated commands# unless it's an alias command# queue up everything after marker# continue to handle other cmd def in the cmd list# end of cmd list# Determine if we must stop# one of the resuming commands# interface abstraction functions# Generic completion functions. Individual complete_foo methods can be# assigned below to one of these functions.# Complete a file/module/function location for break/tbreak/clear.# Here comes a line number or a condition which we can't complete.# First, try to find matching functions (i.e. expressions).# Then, try to complete file names as well.# Complete a breakpoint number. (This would be more helpful if we could# display additional info along with the completions, such as file/line# of the breakpoint.)# Complete an arbitrary expression.# Collect globals and locals. It is usually not really sensible to also# complete builtins, and they clutter the namespace quite heavily, so we# leave them out.# Walk an attribute chain up to the last part, similar to what# rlcompleter does. This will bail if any of the parts are not# simple attribute access, which is what we want.# Complete a simple name.# Command definitions, called by cmdloop()# The argument is the remaining string on the command line# Return true to exit from the command loop# Save old definitions for the case of a keyboard interrupt.# Restore old definitions.# There's at least one# parse arguments; comma has lowest precedence# and cannot occur in filename# parse stuff after comma: "condition"# parse stuff before comma: [filename:]lineno | function# no colon; can be lineno or function#use co_name to identify the bkpt (function names#could be aliased, but co_name is invariant)# last thing to try# ok contains a function name# Check for reasonable breakpoint# now set the break point# To be overridden in derived debuggers# Input is identifier, may be in single quotes# not in single quotes# quoted# Protection for derived debuggers# Best first guess at file to look at# More than one part.# First is module, second is method/class# this method should be callable before starting debugging, so default# to "no globals" if there is no current frame# Don't allow setting breakpoint at a blank line# Make sure it works for "clear C:\foo\bar.py:12"# 'c' is already an abbreviation for 'continue'# this is caught in the main debugger loop# ValueError happens when do_continue() is invoked from# a non-main thread in which case we just continue without# SIGINT set. Would printing a message here (once) make# sense?# Do the jump, fix up our copy of the stack, and display the# new position# assume it's a count# _getval() already printed the error# Is it an instance method?# Is it a function?# Is it a class?# None of the above...# List of all the commands making the program resume execution.# Print a traceback starting at the top stack frame.# The most recently entered frame is printed last;# this is different from dbx and gdb, but consistent with# the Python interpreter's stack trace.# It is also consistent with the up/down commands (which are# compatible with dbx and gdb: up moves towards 'main()'# and down moves towards the most recent stack frame).# Provide help# other helper functions# The script has to run in __main__ namespace (or imports from# __main__ will break).# So we clear up the __main__ and set several special variables# (this gets rid of pdb's globals and cleans old variables on restarts).# When bdb sets tracing, a number of call and line events happens# BEFORE debugger even reaches user's code (and the exact sequence of# events depends on python version). So we take special measures to# avoid stopping before we reach the main script (see user_line and# user_call for details).# Collect all command help into docstring, if not run with -OO# unfortunately we can't guess this order from the class definition# Simplified interface# Post-Mortem interface# handling the default# sys.exc_info() returns (type, value, traceback) if an exception is# being handled, otherwise it returns None# Main program for testing# print help# Get script filename# Hide "pdb.py" and pdb options from argument list# Replace pdb's dir with script's dir in front of module search path.# Note on saving/restoring sys.argv: it's a good idea when sys.argv was# modified by the script being debugged. It's a bad idea when it was# changed by the user from the command line. There is a "restart" command# which allows explicit specification of command line arguments.# In most cases SystemExit does not warrant a post-mortem session.# When invoked as main program, invoke the debugger on a scriptb' +The Python Debugger Pdb +======================= + +To use the debugger in its simplest form: + + >>> import pdb + >>> pdb.run('') + +The debugger's prompt is '(Pdb) '. This will stop in the first +function call in . + +Alternatively, if a statement terminated with an unhandled exception, +you can use pdb's post-mortem facility to inspect the contents of the +traceback: + + >>> + + >>> import pdb + >>> pdb.pm() + +The commands recognized by the debugger are listed in the next +section. Most can be abbreviated as indicated; e.g., h(elp) means +that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel', +nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in +square brackets. Alternatives in the command syntax are separated +by a vertical bar (|). + +A blank line repeats the previous command literally, except for +'list', where it lists the next 11 lines. + +Commands that the debugger doesn't recognize are assumed to be Python +statements and are executed in the context of the program being +debugged. Python statements can also be prefixed with an exclamation +point ('!'). This is a powerful way to inspect the program being +debugged; it is even possible to change variables or call functions. +When an exception occurs in such a statement, the exception name is +printed but the debugger's state is not changed. + +The debugger supports aliases, which can save typing. And aliases can +have parameters (see the alias help entry) which allows one a certain +level of adaptability to the context under examination. + +Multiple commands may be entered on a single line, separated by the +pair ';;'. No intelligence is applied to separating the commands; the +input is split at the first ';;', even if it is in the middle of a +quoted string. + +If a file ".pdbrc" exists in your home directory or in the current +directory, it is read in and executed as if it had been typed at the +debugger prompt. This is particularly useful for aliases. If both +files exist, the one in the home directory is read first and aliases +defined there can be overridden by the local file. This behavior can be +disabled by passing the "readrc=False" argument to the Pdb constructor. + +Aside from aliases, the debugger is not directly programmable; but it +is implemented as a class from which you can derive your own debugger +class, which you can make as fancy as you like. + + +Debugger commands +================= + +'u' +The Python Debugger Pdb +======================= + +To use the debugger in its simplest form: + + >>> import pdb + >>> pdb.run('') + +The debugger's prompt is '(Pdb) '. This will stop in the first +function call in . + +Alternatively, if a statement terminated with an unhandled exception, +you can use pdb's post-mortem facility to inspect the contents of the +traceback: + + >>> + + >>> import pdb + >>> pdb.pm() + +The commands recognized by the debugger are listed in the next +section. Most can be abbreviated as indicated; e.g., h(elp) means +that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel', +nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in +square brackets. Alternatives in the command syntax are separated +by a vertical bar (|). + +A blank line repeats the previous command literally, except for +'list', where it lists the next 11 lines. + +Commands that the debugger doesn't recognize are assumed to be Python +statements and are executed in the context of the program being +debugged. Python statements can also be prefixed with an exclamation +point ('!'). This is a powerful way to inspect the program being +debugged; it is even possible to change variables or call functions. +When an exception occurs in such a statement, the exception name is +printed but the debugger's state is not changed. + +The debugger supports aliases, which can save typing. And aliases can +have parameters (see the alias help entry) which allows one a certain +level of adaptability to the context under examination. + +Multiple commands may be entered on a single line, separated by the +pair ';;'. No intelligence is applied to separating the commands; the +input is split at the first ';;', even if it is in the middle of a +quoted string. + +If a file ".pdbrc" exists in your home directory or in the current +directory, it is read in and executed as if it had been typed at the +debugger prompt. This is particularly useful for aliases. If both +files exist, the one in the home directory is read first and aliases +defined there can be overridden by the local file. This behavior can be +disabled by passing the "readrc=False" argument to the Pdb constructor. + +Aside from aliases, the debugger is not directly programmable; but it +is implemented as a class from which you can derive your own debugger +class, which you can make as fancy as you like. + + +Debugger commands +================= + +'b'Causes a debugger to be restarted for the debugged python program.'u'Causes a debugger to be restarted for the debugged python program.'b'run'u'run'b'pm'u'pm'b'Pdb'u'Pdb'b'runeval'u'runeval'b'runctx'u'runctx'b'runcall'u'runcall'b'set_trace'u'set_trace'b'post_mortem'u'post_mortem'b'def\s+%s\s*[(]'u'def\s+%s\s*[(]'b'String that doesn't quote its repr.'u'String that doesn't quote its repr.'b' +-> 'u' +-> 'b'pdb.Pdb'u'pdb.Pdb'b'(Pdb) 'u'(Pdb) 'b' +`@#$%^&*()=+[{]}\|;:'",<>?'u' +`@#$%^&*()=+[{]}\|;:'",<>?'b'~/.pdbrc'u'~/.pdbrc'b'.pdbrc'u'.pdbrc'b' +Program interrupted. (Use 'cont' to resume).'u' +Program interrupted. (Use 'cont' to resume).'b'This method is called when there is the remote possibility + that we ever need to stop in this function.'u'This method is called when there is the remote possibility + that we ever need to stop in this function.'b'--Call--'u'--Call--'b'This function is called when we stop or break at this line.'u'This function is called when we stop or break at this line.'b'Call every command that was set for the current active breakpoint + (if there is one). + + Returns True if the normal interaction function must be called, + False otherwise.'u'Call every command that was set for the current active breakpoint + (if there is one). + + Returns True if the normal interaction function must be called, + False otherwise.'b'currentbp'u'currentbp'b'This function is called when a return trap is set here.'u'This function is called when a return trap is set here.'b'--Return--'u'--Return--'b'This function is called if an exception occurs, + but only if we are to stop at or just below this level.'u'This function is called if an exception occurs, + but only if we are to stop at or just below this level.'b'__exception__'u'__exception__'b'Internal 'u'Internal 'b'--KeyboardInterrupt--'u'--KeyboardInterrupt--'b'display %s: %r [old: %r]'u'display %s: %r [old: %r]'b'Custom displayhook for the exec in default(), which prevents + assignment of the _ variable in the builtins. + 'u'Custom displayhook for the exec in default(), which prevents + assignment of the _ variable in the builtins. + 'b''u''b'Handle alias expansion and ';;' separator.'u'Handle alias expansion and ';;' separator.'b'%*'u'%*'b';;'u';;'b'Interpret the argument as though it had been typed in response + to the prompt. + + Checks whether this line is typed at the normal prompt or in + a breakpoint command list definition. + 'u'Interpret the argument as though it had been typed in response + to the prompt. + + Checks whether this line is typed at the normal prompt or in + a breakpoint command list definition. + 'b'Handles one command line during command list definition.'u'Handles one command line during command list definition.'b'silent'u'silent'b'***'u'***'b'commands [bpnumber] + (com) ... + (com) end + (Pdb) + + Specify a list of commands for breakpoint number bpnumber. + The commands themselves are entered on the following lines. + Type a line containing just 'end' to terminate the commands. + The commands are executed when the breakpoint is hit. + + To remove all commands from a breakpoint, type commands and + follow it immediately with end; that is, give no commands. + + With no bpnumber argument, commands refers to the last + breakpoint set. + + You can use breakpoint commands to start your program up + again. Simply use the continue command, or step, or any other + command that resumes execution. + + Specifying any command resuming execution (currently continue, + step, next, return, jump, quit and their abbreviations) + terminates the command list (as if that command was + immediately followed by end). This is because any time you + resume execution (even with a simple next or step), you may + encounter another breakpoint -- which could have its own + command list, leading to ambiguities about which list to + execute. + + If you use the 'silent' command in the command list, the usual + message about stopping at a breakpoint is not printed. This + may be desirable for breakpoints that are to print a specific + message and then continue. If none of the other commands + print anything, you will see no sign that the breakpoint was + reached. + 'u'commands [bpnumber] + (com) ... + (com) end + (Pdb) + + Specify a list of commands for breakpoint number bpnumber. + The commands themselves are entered on the following lines. + Type a line containing just 'end' to terminate the commands. + The commands are executed when the breakpoint is hit. + + To remove all commands from a breakpoint, type commands and + follow it immediately with end; that is, give no commands. + + With no bpnumber argument, commands refers to the last + breakpoint set. + + You can use breakpoint commands to start your program up + again. Simply use the continue command, or step, or any other + command that resumes execution. + + Specifying any command resuming execution (currently continue, + step, next, return, jump, quit and their abbreviations) + terminates the command list (as if that command was + immediately followed by end). This is because any time you + resume execution (even with a simple next or step), you may + encounter another breakpoint -- which could have its own + command list, leading to ambiguities about which list to + execute. + + If you use the 'silent' command in the command list, the usual + message about stopping at a breakpoint is not printed. This + may be desirable for breakpoints that are to print a specific + message and then continue. If none of the other commands + print anything, you will see no sign that the breakpoint was + reached. + 'b'Usage: commands [bnum] + ... + end'u'Usage: commands [bnum] + ... + end'b'(com) 'u'(com) 'b'command definition aborted, old commands restored'u'command definition aborted, old commands restored'b'b(reak) [ ([filename:]lineno | function) [, condition] ] + Without argument, list all breaks. + + With a line number argument, set a break at this line in the + current file. With a function name, set a break at the first + executable line of that function. If a second argument is + present, it is a string specifying an expression which must + evaluate to true before the breakpoint is honored. + + The line number may be prefixed with a filename and a colon, + to specify a breakpoint in another file (probably one that + hasn't been loaded yet). The file is searched for on + sys.path; the .py suffix may be omitted. + 'u'b(reak) [ ([filename:]lineno | function) [, condition] ] + Without argument, list all breaks. + + With a line number argument, set a break at this line in the + current file. With a function name, set a break at the first + executable line of that function. If a second argument is + present, it is a string specifying an expression which must + evaluate to true before the breakpoint is honored. + + The line number may be prefixed with a filename and a colon, + to specify a breakpoint in another file (probably one that + hasn't been loaded yet). The file is searched for on + sys.path; the .py suffix may be omitted. + 'b'Num Type Disp Enb Where'u'Num Type Disp Enb Where'b'%r not found from sys.path'u'%r not found from sys.path'b'Bad lineno: %s'u'Bad lineno: %s'b'The specified object %r is not a function or was not found along sys.path.'u'The specified object %r is not a function or was not found along sys.path.'b'Breakpoint %d at %s:%d'u'Breakpoint %d at %s:%d'b'Produce a reasonable default.'u'Produce a reasonable default.'b'tbreak [ ([filename:]lineno | function) [, condition] ] + Same arguments as break, but sets a temporary breakpoint: it + is automatically deleted when first hit. + 'u'tbreak [ ([filename:]lineno | function) [, condition] ] + Same arguments as break, but sets a temporary breakpoint: it + is automatically deleted when first hit. + 'b'Check whether specified line seems to be executable. + + Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank + line or EOF). Warning: testing is not comprehensive. + 'u'Check whether specified line seems to be executable. + + Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank + line or EOF). Warning: testing is not comprehensive. + 'b'curframe'u'curframe'b'End of file'u'End of file'b'"""'u'"""'b'''''u'''''b'Blank or comment'u'Blank or comment'b'enable bpnumber [bpnumber ...] + Enables the breakpoints given as a space separated list of + breakpoint numbers. + 'u'enable bpnumber [bpnumber ...] + Enables the breakpoints given as a space separated list of + breakpoint numbers. + 'b'Enabled %s'u'Enabled %s'b'disable bpnumber [bpnumber ...] + Disables the breakpoints given as a space separated list of + breakpoint numbers. Disabling a breakpoint means it cannot + cause the program to stop execution, but unlike clearing a + breakpoint, it remains in the list of breakpoints and can be + (re-)enabled. + 'u'disable bpnumber [bpnumber ...] + Disables the breakpoints given as a space separated list of + breakpoint numbers. Disabling a breakpoint means it cannot + cause the program to stop execution, but unlike clearing a + breakpoint, it remains in the list of breakpoints and can be + (re-)enabled. + 'b'Disabled %s'u'Disabled %s'b'condition bpnumber [condition] + Set a new condition for the breakpoint, an expression which + must evaluate to true before the breakpoint is honored. If + condition is absent, any existing condition is removed; i.e., + the breakpoint is made unconditional. + 'u'condition bpnumber [condition] + Set a new condition for the breakpoint, an expression which + must evaluate to true before the breakpoint is honored. If + condition is absent, any existing condition is removed; i.e., + the breakpoint is made unconditional. + 'b'Breakpoint %d is now unconditional.'u'Breakpoint %d is now unconditional.'b'New condition set for breakpoint %d.'u'New condition set for breakpoint %d.'b'ignore bpnumber [count] + Set the ignore count for the given breakpoint number. If + count is omitted, the ignore count is set to 0. A breakpoint + becomes active when the ignore count is zero. When non-zero, + the count is decremented each time the breakpoint is reached + and the breakpoint is not disabled and any associated + condition evaluates to true. + 'u'ignore bpnumber [count] + Set the ignore count for the given breakpoint number. If + count is omitted, the ignore count is set to 0. A breakpoint + becomes active when the ignore count is zero. When non-zero, + the count is decremented each time the breakpoint is reached + and the breakpoint is not disabled and any associated + condition evaluates to true. + 'b'%d crossings'u'%d crossings'b'1 crossing'u'1 crossing'b'Will ignore next %s of breakpoint %d.'u'Will ignore next %s of breakpoint %d.'b'Will stop next time breakpoint %d is reached.'u'Will stop next time breakpoint %d is reached.'b'cl(ear) filename:lineno +cl(ear) [bpnumber [bpnumber...]] + With a space separated list of breakpoint numbers, clear + those breakpoints. Without argument, clear all breaks (but + first ask confirmation). With a filename:lineno argument, + clear all breaks at that line in that file. + 'u'cl(ear) filename:lineno +cl(ear) [bpnumber [bpnumber...]] + With a space separated list of breakpoint numbers, clear + those breakpoints. Without argument, clear all breaks (but + first ask confirmation). With a filename:lineno argument, + clear all breaks at that line in that file. + 'b'Clear all breaks? 'u'Clear all breaks? 'b'yes'u'yes'b'Deleted %s'u'Deleted %s'b'Invalid line number (%s)'u'Invalid line number (%s)'b'w(here) + Print a stack trace, with the most recent frame at the bottom. + An arrow indicates the "current frame", which determines the + context of most commands. 'bt' is an alias for this command. + 'u'w(here) + Print a stack trace, with the most recent frame at the bottom. + An arrow indicates the "current frame", which determines the + context of most commands. 'bt' is an alias for this command. + 'b'u(p) [count] + Move the current frame count (default one) levels up in the + stack trace (to an older frame). + 'u'u(p) [count] + Move the current frame count (default one) levels up in the + stack trace (to an older frame). + 'b'Oldest frame'u'Oldest frame'b'Invalid frame count (%s)'u'Invalid frame count (%s)'b'd(own) [count] + Move the current frame count (default one) levels down in the + stack trace (to a newer frame). + 'u'd(own) [count] + Move the current frame count (default one) levels down in the + stack trace (to a newer frame). + 'b'Newest frame'u'Newest frame'b'unt(il) [lineno] + Without argument, continue execution until the line with a + number greater than the current one is reached. With a line + number, continue execution until a line with a number greater + or equal to that is reached. In both cases, also stop when + the current frame returns. + 'u'unt(il) [lineno] + Without argument, continue execution until the line with a + number greater than the current one is reached. With a line + number, continue execution until a line with a number greater + or equal to that is reached. In both cases, also stop when + the current frame returns. + 'b'Error in argument: %r'u'Error in argument: %r'b'"until" line number is smaller than current line number'u'"until" line number is smaller than current line number'b's(tep) + Execute the current line, stop at the first possible occasion + (either in a function that is called or in the current + function). + 'u's(tep) + Execute the current line, stop at the first possible occasion + (either in a function that is called or in the current + function). + 'b'n(ext) + Continue execution until the next line in the current function + is reached or it returns. + 'u'n(ext) + Continue execution until the next line in the current function + is reached or it returns. + 'b'run [args...] + Restart the debugged python program. If a string is supplied + it is split with "shlex", and the result is used as the new + sys.argv. History, breakpoints, actions and debugger options + are preserved. "restart" is an alias for "run". + 'u'run [args...] + Restart the debugged python program. If a string is supplied + it is split with "shlex", and the result is used as the new + sys.argv. History, breakpoints, actions and debugger options + are preserved. "restart" is an alias for "run". + 'b'r(eturn) + Continue execution until the current function returns. + 'u'r(eturn) + Continue execution until the current function returns. + 'b'c(ont(inue)) + Continue execution, only stop when a breakpoint is encountered. + 'u'c(ont(inue)) + Continue execution, only stop when a breakpoint is encountered. + 'b'j(ump) lineno + Set the next line that will be executed. Only available in + the bottom-most frame. This lets you jump back and execute + code again, or jump forward to skip code that you don't want + to run. + + It should be noted that not all jumps are allowed -- for + instance it is not possible to jump into the middle of a + for loop or out of a finally clause. + 'u'j(ump) lineno + Set the next line that will be executed. Only available in + the bottom-most frame. This lets you jump back and execute + code again, or jump forward to skip code that you don't want + to run. + + It should be noted that not all jumps are allowed -- for + instance it is not possible to jump into the middle of a + for loop or out of a finally clause. + 'b'You can only jump within the bottom frame'u'You can only jump within the bottom frame'b'Jump failed: %s'u'Jump failed: %s'b'The 'jump' command requires a line number'u'The 'jump' command requires a line number'b'debug code + Enter a recursive debugger that steps through the code + argument (which is an arbitrary expression or statement to be + executed in the current environment). + 'u'debug code + Enter a recursive debugger that steps through the code + argument (which is an arbitrary expression or statement to be + executed in the current environment). + 'b'ENTERING RECURSIVE DEBUGGER'u'ENTERING RECURSIVE DEBUGGER'b'LEAVING RECURSIVE DEBUGGER'u'LEAVING RECURSIVE DEBUGGER'b'q(uit) +exit + Quit from the debugger. The program being executed is aborted. + 'u'q(uit) +exit + Quit from the debugger. The program being executed is aborted. + 'b'EOF + Handles the receipt of EOF as a command. + 'u'EOF + Handles the receipt of EOF as a command. + 'b'a(rgs) + Print the argument list of the current function. + 'u'a(rgs) + Print the argument list of the current function. + 'b'%s = %r'u'%s = %r'b'%s = *** undefined ***'u'%s = *** undefined ***'b'retval + Print the return value for the last return of a function. + 'u'retval + Print the return value for the last return of a function. + 'b'Not yet returned!'u'Not yet returned!'b'** raised %s **'u'** raised %s **'b'p expression + Print the value of the expression. + 'u'p expression + Print the value of the expression. + 'b'pp expression + Pretty-print the value of the expression. + 'u'pp expression + Pretty-print the value of the expression. + 'b'l(ist) [first [,last] | .] + + List source code for the current file. Without arguments, + list 11 lines around the current line or continue the previous + listing. With . as argument, list 11 lines around the current + line. With one argument, list 11 lines starting at that line. + With two arguments, list the given range; if the second + argument is less than the first, it is a count. + + The current line in the current frame is indicated by "->". + If an exception is being debugged, the line where the + exception was originally raised or propagated is indicated by + ">>", if it differs from the current line. + 'u'l(ist) [first [,last] | .] + + List source code for the current file. Without arguments, + list 11 lines around the current line or continue the previous + listing. With . as argument, list 11 lines around the current + line. With one argument, list 11 lines starting at that line. + With two arguments, list the given range; if the second + argument is less than the first, it is a count. + + The current line in the current frame is indicated by "->". + If an exception is being debugged, the line where the + exception was originally raised or propagated is indicated by + ">>", if it differs from the current line. + 'b'[EOF]'u'[EOF]'b'longlist | ll + List the whole source code for the current function or frame. + 'u'longlist | ll + List the whole source code for the current function or frame. + 'b'source expression + Try to get source code for the given object and display it. + 'u'source expression + Try to get source code for the given object and display it. + 'b'Print a range of lines.'u'Print a range of lines.'b'whatis arg + Print the type of the argument. + 'u'whatis arg + Print the type of the argument. + 'b'Method %s'u'Method %s'b'Function %s'u'Function %s'b'Class %s.%s'u'Class %s.%s'b'display [expression] + + Display the value of the expression if it changed, each time execution + stops in the current frame. + + Without expression, list all display expressions for the current frame. + 'u'display [expression] + + Display the value of the expression if it changed, each time execution + stops in the current frame. + + Without expression, list all display expressions for the current frame. + 'b'Currently displaying:'u'Currently displaying:'b'display %s: %r'u'display %s: %r'b'undisplay [expression] + + Do not display the expression any more in the current frame. + + Without expression, clear all display expressions for the current frame. + 'u'undisplay [expression] + + Do not display the expression any more in the current frame. + + Without expression, clear all display expressions for the current frame. + 'b'not displaying %s'u'not displaying %s'b'interact + + Start an interactive interpreter whose global namespace + contains all the (global and local) names found in the current scope. + 'u'interact + + Start an interactive interpreter whose global namespace + contains all the (global and local) names found in the current scope. + 'b'*interactive*'u'*interactive*'b'alias [name [command [parameter parameter ...] ]] + Create an alias called 'name' that executes 'command'. The + command must *not* be enclosed in quotes. Replaceable + parameters can be indicated by %1, %2, and so on, while %* is + replaced by all the parameters. If no command is given, the + current alias for name is shown. If no name is given, all + aliases are listed. + + Aliases may be nested and can contain anything that can be + legally typed at the pdb prompt. Note! You *can* override + internal pdb commands with aliases! Those internal commands + are then hidden until the alias is removed. Aliasing is + recursively applied to the first word of the command line; all + other words in the line are left alone. + + As an example, here are two useful aliases (especially when + placed in the .pdbrc file): + + # Print instance variables (usage "pi classInst") + alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) + # Print instance variables in self + alias ps pi self + 'u'alias [name [command [parameter parameter ...] ]] + Create an alias called 'name' that executes 'command'. The + command must *not* be enclosed in quotes. Replaceable + parameters can be indicated by %1, %2, and so on, while %* is + replaced by all the parameters. If no command is given, the + current alias for name is shown. If no name is given, all + aliases are listed. + + Aliases may be nested and can contain anything that can be + legally typed at the pdb prompt. Note! You *can* override + internal pdb commands with aliases! Those internal commands + are then hidden until the alias is removed. Aliasing is + recursively applied to the first word of the command line; all + other words in the line are left alone. + + As an example, here are two useful aliases (especially when + placed in the .pdbrc file): + + # Print instance variables (usage "pi classInst") + alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) + # Print instance variables in self + alias ps pi self + 'b'%s = %s'u'%s = %s'b'unalias name + Delete the specified alias. + 'u'unalias name + Delete the specified alias. + 'b'do_continue'u'do_continue'b'do_step'u'do_step'b'do_next'u'do_next'b'do_return'u'do_return'b'do_quit'u'do_quit'b'do_jump'u'do_jump'b'> 'u'> 'b'h(elp) + Without argument, print the list of available commands. + With a command name as argument, print help about that command. + "help pdb" shows the full pdb documentation. + "help exec" gives help on the ! command. + 'u'h(elp) + Without argument, print the list of available commands. + With a command name as argument, print help about that command. + "help pdb" shows the full pdb documentation. + "help exec" gives help on the ! command. + 'b'No help for %r; please do not run Python with -OO if you need command help'u'No help for %r; please do not run Python with -OO if you need command help'b'No help for %r'u'No help for %r'b'(!) statement + Execute the (one-line) statement in the context of the current + stack frame. The exclamation point can be omitted unless the + first word of the statement resembles a debugger command. To + assign to a global variable you must always prefix the command + with a 'global' command, e.g.: + (Pdb) global list_options; list_options = ['-l'] + (Pdb) + 'u'(!) statement + Execute the (one-line) statement in the context of the current + stack frame. The exclamation point can be omitted unless the + first word of the statement resembles a debugger command. To + assign to a global variable you must always prefix the command + with a 'global' command, e.g.: + (Pdb) global list_options; list_options = ['-l'] + (Pdb) + 'b'Helper function for break/clear parsing -- may be overridden. + + lookupmodule() translates (possibly incomplete) file or module name + into an absolute file name. + 'u'Helper function for break/clear parsing -- may be overridden. + + lookupmodule() translates (possibly incomplete) file or module name + into an absolute file name. + 'b'exec(compile(%r, %r, 'exec'))'u'exec(compile(%r, %r, 'exec'))'b'where'u'where'b'down'u'down'b'up'u'up'b'tbreak'u'tbreak'b'enable'u'enable'b'condition'u'condition'b'step'b'until'u'until'b'jump'u'jump'b'retval'u'retval'b'longlist'u'longlist'b'p'u'p'b'whatis'u'whatis'b'display'u'display'b'undisplay'u'undisplay'b'unalias'u'unalias'b'quit'u'quit'b'A valid traceback must be passed if no exception is being handled'u'A valid traceback must be passed if no exception is being handled'b'import x; x.main()'u'import x; x.main()'b'usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ... + +Debug the Python program given by pyfile. Alternatively, +an executable module or package to debug can be specified using +the -m switch. + +Initial commands are read from .pdbrc files in your home directory +and in the current directory, if they exist. Commands supplied with +-c are executed after commands from .pdbrc files. + +To let the script run until an exception occurs, use "-c continue". +To let the script run up to a given line X in the debugged file, use +"-c 'until X'".'u'usage: pdb.py [-c command] ... [-m module | pyfile] [arg] ... + +Debug the Python program given by pyfile. Alternatively, +an executable module or package to debug can be specified using +the -m switch. + +Initial commands are read from .pdbrc files in your home directory +and in the current directory, if they exist. Commands supplied with +-c are executed after commands from .pdbrc files. + +To let the script run until an exception occurs, use "-c continue". +To let the script run up to a given line X in the debugged file, use +"-c 'until X'".'b'mhc:'u'mhc:'b'command='u'command='b'--command'u'--command'b'Error:'u'Error:'b'does not exist'u'does not exist'b'The program finished and will be restarted'u'The program finished and will be restarted'b'Restarting'u'Restarting'b'with arguments:'u'with arguments:'b'The program exited via sys.exit(). Exit status:'u'The program exited via sys.exit(). Exit status:'b'Uncaught exception. Entering post mortem debugging'u'Uncaught exception. Entering post mortem debugging'b'Running 'cont' or 'step' will restart the program'u'Running 'cont' or 'step' will restart the program'b'Post mortem debugger finished. The 'u'Post mortem debugger finished. The 'b' will be restarted'u' will be restarted'u'pdb'PgenGrammarParserGeneratorclose_streamgettokenstartsymboladdfirstsetsmake_grammarmake_labelisfinalmake_firstrawfirstitokencalcfirsttotalsetoverlapcheckrecursion for rule %rinverserule %s is ambiguous; %s is in the first sets of %s as well as %s"rule %s is ambiguous; %s is in the"" first sets of %s as well as %s"ENDMARKERexpectparse_rhsmake_dfaoldlensimplify_dfanewlenfinishNFAStateaddclosureDFAStatenfastatenfasetaddarcdump_nfaDump of NFA for State(final) -> %d %s -> %ddump_dfaDump of DFA forchangesstate_istate_junifystateparse_altaazzparse_itemparse_atomraise_errorexpected (...) or NAME or STRING, got %s/%sexpected %s/%s, got %s/%s# Initialize lookahead# map from symbol name to set of tokens##assert ilabel not in first # XXX failed on <> ... !=# XXX Maybe this should be a method on a subclass of converter?# Either a symbol name or a named token# A symbol name (a non-terminal)# A named token (NAME, NUMBER, STRING)# Either a keyword or an operator# A keyword# An operator (any non-numeric token)# Fails if unknown token#print name, self.first[name].keys()# dummy to detect left recursion# MSTART: (NEWLINE | RULE)* ENDMARKER# RULE: NAME ':' RHS NEWLINE#self.dump_nfa(name, a, z)#self.dump_dfa(name, dfa)#print name, oldlen, newlen# To turn an NFA into a DFA, we define the states of the DFA# to correspond to *sets* of states of the NFA. Then do some# state reduction. Let's represent sets as dicts with 1 for# values.# NB states grows while we're iterating# List of DFAState instances; first one is start# This is not theoretically optimal, but works well enough.# Algorithm: repeatedly look for two states that have the same# set of arcs (same labels pointing to the same nodes) and# unify them, until things stop changing.# dfa is a list of DFAState instances#print " unify", i, j# RHS: ALT ('|' ALT)*# ALT: ITEM+# ITEM: '[' RHS ']' | ATOM ['+' | '*']# ATOM: '(' RHS ')' | NAME | STRING#print token.tok_name[self.type], repr(self.value)# list of (label, NFAState) pairs# map from label to DFAState# Equality test -- ignore the nfaset instance variable# Can't just return self.arcs == other.arcs, because that# would invoke this method recursively, with cycles...# For Py3 compatibility.b'recursion for rule %r'u'recursion for rule %r'b'rule %s is ambiguous; %s is in the first sets of %s as well as %s'u'rule %s is ambiguous; %s is in the first sets of %s as well as %s'b'Dump of NFA for'u'Dump of NFA for'b' State'u' State'b'(final)'u'(final)'b' -> %d'u' -> %d'b' %s -> %d'u' %s -> %d'b'Dump of DFA for'u'Dump of DFA for'b'expected (...) or NAME or STRING, got %s/%s'u'expected (...) or NAME or STRING, got %s/%s'b'expected %s/%s, got %s/%s'u'expected %s/%s, got %s/%s'u'lib2to3.pgen2.pgen'u'pgen2.pgen'u'pgen'Create portable serialized representations of Python objects. + +See module copyreg for a mechanism for registering custom picklers. +See module pickletools source for extensive comments. + +Classes: + + Pickler + Unpickler + +Functions: + + dump(object, file) + dumps(object) -> string + load(file) -> object + loads(string) -> object + +Misc variables: + + __version__ + format_version + compatible_formats + +_compat_pickle_HAVE_PICKLE_BUFFER4.0format_version1.21.33.0compatible_formatsDEFAULT_PROTOCOLA common base class for the other pickling exceptions.This exception is raised when an unpicklable object is passed to the + dump() method. + + This exception is raised when there is a problem unpickling an object, + such as a security violation. + + Note that other exceptions may also be raised during unpickling, including + (but not necessarily limited to) AttributeError, EOFError, ImportError, + and IndexError. + + _StopMARKSTOPPOPPOP_MARKDUPFLOATINTJBININTBININT1LONGBININT2PERSIDBINPERSIDREDUCEBINSTRINGSHORT_BINSTRINGVBINUNICODEAPPENDBUILDGLOBALDICTEMPTY_DICTAPPENDSBINGETINSTLONG_BINGETEMPTY_LISTOBJBINPUTLONG_BINPUTSETITEMTUPLEEMPTY_TUPLESETITEMSBINFLOATI01 +I00 +€PROTONEWOBJ‚EXT1ƒEXT2„EXT4…TUPLE1†TUPLE2‡TUPLE3ˆNEWTRUE‰NEWFALSEŠLONG1‹LONG4_tuplesize2codeBINBYTESSHORT_BINBYTESŒSHORT_BINUNICODEBINUNICODE8ŽBINBYTES8EMPTY_SETADDITEMS‘FROZENSET’NEWOBJ_EX“STACK_GLOBAL”MEMOIZE•FRAME–BYTEARRAY8—NEXT_BUFFER˜READONLY_BUFFER[A-Z][A-Z0-9_]+$_Framer_FRAME_SIZE_MIN_FRAME_SIZE_TARGETfile_writecurrent_framestart_framingend_framingcommit_frameCan't get local attribute {!r} on {!r}Can't get attribute {!r} on {!r}whichmoduleFind the module an object belong to.encode_longEncode a long to a two's complement little-endian binary string. + Note that 0 is a special case, returning an empty string, to save a + byte in the LONG1 pickling context. + + >>> encode_long(0) + b'' + >>> encode_long(255) + b'\xff\x00' + >>> encode_long(32767) + b'\xff\x7f' + >>> encode_long(-256) + b'\x00\xff' + >>> encode_long(-32768) + b'\x00\x80' + >>> encode_long(-128) + b'\x80' + >>> encode_long(127) + b'\x7f' + >>> + signed0xffdecode_longDecode a long from a two's complement little-endian binary string. + + >>> decode_long(b'') + 0 + >>> decode_long(b"\xff\x00") + 255 + >>> decode_long(b"\xff\x7f") + 32767 + >>> decode_long(b"\x00\xff") + -256 + >>> decode_long(b"\x00\x80") + -32768 + >>> decode_long(b"\x80") + -128 + >>> decode_long(b"\x7f") + 127 + _Picklerfix_importsbuffer_callbackThis takes a binary file for writing a pickle data stream. + + The optional *protocol* argument tells the pickler to use the + given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. + The default protocol is 4. It was introduced in Python 3.4, and + is incompatible with previous versions. + + Specifying a negative protocol version selects the highest + protocol version supported. The higher the protocol used, the + more recent the version of Python needed to read the pickle + produced. + + The *file* argument must have a write() method that accepts a + single bytes argument. It can thus be a file object opened for + binary writing, an io.BytesIO instance, or any other custom + object that meets this interface. + + If *fix_imports* is True and *protocol* is less than 3, pickle + will try to map the new Python 3 names to the old module names + used in Python 2, so that the pickle data stream is readable + with Python 2. + + If *buffer_callback* is None (the default), buffer views are + serialized into *file* as part of the pickle stream. + + If *buffer_callback* is not None, then it can be called any number + of times with a buffer view. If the callback returns a false value + (such as None), the given buffer is out-of-band; otherwise the + buffer is serialized in-band, i.e. inside the pickle stream. + + It is an error if *buffer_callback* is not None and *protocol* + is None or smaller than 5. + pickle protocol must be <= %dbuffer_callback needs protocol >= 5_buffer_callback_file_writefile must have a 'write' attributeframer_write_large_bytesClears the pickler's "memo". + + The memo is the data structure that remembers which objects the + pickler has already seen, so that shared or recursive objects + are pickled by reference and not by value. This method is + useful when re-using picklers. + Write a pickled representation of obj to the open file.Pickler.__init__() was not called by %s.__init__()"Pickler.__init__() was not called by ""%s.__init__()"dsave_bytessave_bytearraysave_picklebufferPickleBuffer can only pickled with protocol >= 5"PickleBuffer can only pickled with ""protocol >= 5"PickleBuffer can not be pickled when pointing to a non-contiguous buffer"PickleBuffer can not be pickled when ""pointing to a non-contiguous buffer"in_bandsave_strsurrogatepass\u005c\u0000\u000a\u000d\u001asave_tuplesave_list_BATCHSIZEsave_dictsave_setbatchsave_frozensetobj2Can't pickle %r: it's not the same object as %s.%sCan't pickle %r: it's not found as %s.%slastnamer_name_mappingr_import_mappingcan't pickle global identifier '%s.%s' using pickle protocol %i"can't pickle global identifier '%s.%s' using ""pickle protocol %i"save_type_UnpicklerbuffersThis takes a binary file for reading a pickle data stream. + + The protocol version of the pickle is detected automatically, so + no proto argument is needed. + + The argument *file* must have two methods, a read() method that + takes an integer argument, and a readline() method that requires + no arguments. Both methods should return bytes. Thus *file* + can be a binary file object opened for reading, an io.BytesIO + object, or any other custom object that meets this interface. + + The file-like object must have two methods, a read() method + that takes an integer argument, and a readline() method that + requires no arguments. Both methods should return bytes. + Thus file-like object can be a binary file object opened for + reading, a BytesIO object, or any other custom object that + meets this interface. + + If *buffers* is not None, it should be an iterable of buffer-enabled + objects that is consumed each time the pickle stream references + an out-of-band buffer view. Such buffers have been given in order + to the *buffer_callback* of a Pickler object. + + If *buffers* is None (the default), then the buffers are taken + from the pickle stream, assuming they are serialized there. + It is an error for *buffers* to be None if the pickle stream + was produced with a non-None *buffer_callback*. + + Other optional arguments are *fix_imports*, *encoding* and + *errors*, which are used to control compatibility support for + pickle stream generated by Python 2. If *fix_imports* is True, + pickle will try to map the old Python 2 names to the new names + used in Python 3. The *encoding* and *errors* tell pickle how + to decode 8-bit string instances pickled by Python 2; these + default to 'ASCII' and 'strict', respectively. *encoding* can be + 'bytes' to read theses 8-bit string instances as bytes objects. + _buffers_file_readline_file_readRead a pickled object representation from the open file. + + Return the reconstituted object hierarchy specified in the file. + Unpickler.__init__() was not called by %s.__init__()"Unpickler.__init__() was not called by "_unframermetastackstopinstpop_markunsupported persistent id encounteredload_protounsupported pickle protocol: %dframe size > sys.maxsize: %dload_persidload_binpersidload_noneload_falseload_trueload_intload_binintload_binint1load_binint2load_longload_long1load_long4LONG pickle has negative byte countload_floatload_binfloat_decode_stringload_string"'the STRING opcode argument must be quotedload_binstringBINSTRING pickle has negative byte countload_binbytesBINBYTES exceeds system's maximum size of %d bytes"BINBYTES exceeds system's maximum size ""of %d bytes"load_unicodeload_binunicodeBINUNICODE exceeds system's maximum size of %d bytes"BINUNICODE exceeds system's maximum size "load_binunicode8BINUNICODE8 exceeds system's maximum size of %d bytes"BINUNICODE8 exceeds system's maximum size "load_binbytes8BINBYTES8 exceeds system's maximum size of %d bytes"BINBYTES8 exceeds system's maximum size "load_bytearray8BYTEARRAY8 exceeds system's maximum size of %d bytes"BYTEARRAY8 exceeds system's maximum size "load_next_bufferpickle stream refers to out-of-band data but no *buffers* argument was given"pickle stream refers to out-of-band data ""but no *buffers* argument was given"not enough out-of-band buffersload_readonly_bufferload_short_binstringload_short_binbytesload_short_binunicodeload_tupleload_empty_tupleload_tuple1load_tuple2load_tuple3load_empty_listload_empty_dictionaryload_empty_setload_frozensetload_listload_dict_instantiatein constructor for %s: %sload_instload_objload_newobjload_newobj_exload_globalload_stack_globalSTACK_GLOBAL requires strload_ext1get_extensionload_ext2load_ext4EXT specifies code <= 0unregistered extension code %dpickle.find_classload_reduceload_popload_pop_markload_dupload_getload_bingetload_long_bingetload_putnegative PUT argumentload_binputnegative BINPUT argumentload_long_binputnegative LONG_BINPUT argumentload_memoizeload_appendload_appendslist_objload_setitemload_setitemsload_additemsset_objload_buildload_markload_stopCan't load pickle from unicode stringdisplay contents of the pickle filespickle_filethe pickle file--testrun self-test suiterun verbosely; only affects self-test run# Shortcut for use in isinstance testing# These are purely informational; no code uses these.# File format version we write# Original protocol 0# Protocol 0 with INST added# Original protocol 1# Protocol 1 with BINFLOAT added# Protocol 2# Protocol 3# Protocol 4# Protocol 5# Old format versions we can read# This is the highest protocol number we know how to read.# The protocol we write by default. May be less than HIGHEST_PROTOCOL.# Only bump this if the oldest still supported version of Python already# includes it.# An instance of _Stop is raised by Unpickler.load_stop() in response to# the STOP opcode, passing the object that is the result of unpickling.# Jython has PyStringMap; it's a dict subclass with string keys# Pickle opcodes. See pickletools.py for extensive docs. The listing# here is in kind-of alphabetical order of 1-character pickle code.# pickletools groups them by purpose.# push special markobject on stack# every pickle ends with STOP# discard topmost stack item# discard stack top through topmost markobject# duplicate top stack item# push float object; decimal string argument# push integer or bool; decimal string argument# push four-byte signed int# push 1-byte unsigned int# push long; decimal string argument# push 2-byte unsigned int# push None# push persistent object; id is taken from string arg# " " " ; " " " " stack# apply callable to argtuple, both on stack# push string; NL-terminated string argument# push string; counted binary string argument# " " ; " " " " < 256 bytes# push Unicode string; raw-unicode-escaped'd argument# " " " ; counted UTF-8 string argument# append stack top to list below it# call __setstate__ or __dict__.update()# push self.find_class(modname, name); 2 string args# build a dict from stack items# push empty dict# extend list on stack by topmost stack slice# push item from memo on stack; index is string arg# " " " " " " ; " " 1-byte arg# build & push class instance# push item from memo on stack; index is 4-byte arg# build list from topmost stack items# push empty list# store stack top in memo; index is string arg# " " " " " ; " " 1-byte arg# " " " " " ; " " 4-byte arg# add key+value pair to dict# build tuple from topmost stack items# push empty tuple# modify dict by adding topmost key+value pairs# push float; arg is 8-byte float encoding# not an opcode; see INT docs in pickletools.py# identify pickle protocol# build object by applying cls.__new__ to argtuple# push object from extension registry; 1-byte index# ditto, but 2-byte index# ditto, but 4-byte index# build 1-tuple from stack top# build 2-tuple from two topmost stack items# build 3-tuple from three topmost stack items# push True# push False# push long from < 256 bytes# push really big long# Protocol 3 (Python 3.x)# push bytes; counted binary string argument# push short string; UTF-8 length < 256 bytes# push very long string# push very long bytes string# push empty set on the stack# modify set by adding topmost stack items# build frozenset from topmost stack items# like NEWOBJ but work with keyword only arguments# same as GLOBAL but using names on the stacks# store top of the stack in memo# indicate the beginning of a new frame# push bytearray# push next out-of-band buffer# make top of stack readonly# Issue a single call to the write method of the underlying# file object for the frame opcode with the size of the# frame. The concatenation is expected to be less expensive# than issuing an additional call to write.# Issue a separate call to write to append the frame# contents without concatenation to the above to avoid a# memory copy.# Start the new frame with a new io.BytesIO instance so that# the file object can have delayed access to the previous frame# contents via an unreleased memoryview of the previous# io.BytesIO instance.# Terminate the current frame and flush it to the file.# Perform direct write of the header and payload of the large binary# object. Be careful not to concatenate the header and the payload# prior to calling 'write' as we do not want to allocate a large# temporary bytes object.# We intentionally do not insert a protocol 4 frame opcode to make# it possible to optimize file.read calls in the loader.# Tools used for pickling.# Protect the iteration by using a list copy of sys.modules against dynamic# modules that trigger imports of other modules upon calls to getattr.# bpo-42406# Pickling machinery# Check whether Pickler was initialized correctly. This is# only needed to mimic the behavior of _pickle.Pickler.dump().# The Pickler memo is a dictionary mapping object ids to 2-tuples# that contain the Unpickler memo key and the object being memoized.# The memo key is written to the pickle and will become# the key in the Unpickler's memo. The object is stored in the# Pickler memo so that transient objects are kept alive during# pickling.# The use of the Unpickler memo length as the memo key is just a# convention. The only requirement is that the memo values be unique.# But there appears no advantage to any other scheme, and this# scheme allows the Unpickler memo to be implemented as a plain (but# growable) array, indexed by memo key.# Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.# Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.# Check for persistent id (defined by a subclass)# Check the memo# Check the type dispatch table# Call unbound method with explicit self# Check private dispatch table if any, or else# copyreg.dispatch_table# Check for a class with a custom metaclass; treat as regular# class# Check for a __reduce_ex__ method, fall back to __reduce__# Check for string returned by reduce(), meaning "save as global"# Assert that reduce() returned a tuple# Assert that it returned an appropriately sized tuple# Save the reduce() output and finally memoize the object# This exists so a subclass can override it# Save a persistent id reference# This API is called by some subclasses# A __reduce__ implementation can direct protocol 2 or newer to# use the more efficient NEWOBJ opcode, while still# allowing protocol 0 and 1 to work normally. For this to# work, the function returned by __reduce__ should be# called __newobj__, and its first argument should be a# class. The implementation for __newobj__# should be as follows, although pickle has no way to# verify this:# def __newobj__(cls, *args):# return cls.__new__(cls, *args)# Protocols 0 and 1 will pickle a reference to __newobj__,# while protocol 2 (and above) will pickle a reference to# cls, the remaining args tuple, and the NEWOBJ code,# which calls cls.__new__(cls, *args) at unpickling time# (see load_newobj below). If __reduce__ returns a# three-tuple, the state from the third tuple item will be# pickled regardless of the protocol, calling __setstate__# at unpickling time (see load_build below).# Note that no standard __newobj__ implementation exists;# you have to provide your own. This is to enforce# compatibility with Python 2.2 (pickles written using# protocol 0 or 1 in Python 2.3 should be unpicklable by# Python 2.2).# If the object is already in the memo, this means it is# recursive. In this case, throw away everything we put on the# stack, and fetch the object back from the memo.# More new special cases (that work with older protocols as# well): when __reduce__ returns a tuple with 4 or 5 items,# the 4th and 5th item should be iterators that provide list# items and dict items (as (key, value) tuples), or None.# If a state_setter is specified, call it instead of load_build# to update obj's with its previous state.# First, push state_setter and its tuple of expected arguments# (obj, state) onto the stack.# simple BINGET opcode as obj is already memoized.# Trigger a state_setter(obj, state) function call.# The purpose of state_setter is to carry-out an# inplace modification of obj. We do not care about what the# method might return, so its output is eventually removed from# the stack.# Methods below this point are dispatched through the dispatch table# If the int is small enough to fit in a signed 4-byte 2's-comp# format, we can store it more efficiently than the general# case.# First one- and two-byte unsigned ints:# Next check for 4-byte signed ints:# bytes object is empty# bytearray is empty# Write data in-band# XXX The C implementation avoids a copy here# Write data out-of-band# EOF on DOS# tuple is empty# Subtle. Same as in the big comment below.# proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple# has more than 3 elements.# Subtle. d was not in memo when we entered save_tuple(), so# the process of saving the tuple's elements must have saved# the tuple itself: the tuple is recursive. The proper action# now is to throw away everything we put on the stack, and# simply GET the tuple (it's already constructed). This check# could have been done in the "for element" loop instead, but# recursive tuples are a rare thing.# proto 0 -- POP_MARK not available# No recursion.# proto 0 -- can't use EMPTY_LIST# Helper to batch up APPENDS sequences# else tmp is empty, and we're done# proto 0 -- can't use EMPTY_DICT# Helper to batch up SETITEMS sequences; proto >= 1 only# Non-ASCII identifiers are supported only with protocols >= 3.# Unpickling machinery# Check whether Unpickler was initialized correctly. This is# only needed to mimic the behavior of _pickle.Unpickler.dump().# Return a list of items pushed in the stack after last MARK instruction.# Corrupt or hostile pickle -- we never write one like this# Used to allow strings from Python 2 to be decoded either as# bytes or Unicode strings. This should be used only with the# STRING, BINSTRING and SHORT_BINSTRING opcodes.# Strip outermost quotes# Deprecated BINSTRING uses signed 32-bit length# INST and OBJ differ only in how they get a class object. It's not# only sensible to do the rest in a common routine, the two routines# previously diverged and grew different bugs.# klass is the class to instantiate, and k points to the topmost mark# object, following which are the arguments for klass.__init__.# Stack is ... markobject classobject arg1 arg2 ...# note that 0 is forbidden# Corrupt or hostile pickle.# Subclasses may override this.# Even if the PEP 307 requires extend() and append() methods,# fall back on append() if the object has no extend() method# for backward compatibility.# Shorthands# Use the faster _pickle if possible# Doctestb'Create portable serialized representations of Python objects. + +See module copyreg for a mechanism for registering custom picklers. +See module pickletools source for extensive comments. + +Classes: + + Pickler + Unpickler + +Functions: + + dump(object, file) + dumps(object) -> string + load(file) -> object + loads(string) -> object + +Misc variables: + + __version__ + format_version + compatible_formats + +'u'Create portable serialized representations of Python objects. + +See module copyreg for a mechanism for registering custom picklers. +See module pickletools source for extensive comments. + +Classes: + + Pickler + Unpickler + +Functions: + + dump(object, file) + dumps(object) -> string + load(file) -> object + loads(string) -> object + +Misc variables: + + __version__ + format_version + compatible_formats + +'b'PickleError'u'PickleError'b'PicklingError'u'PicklingError'b'UnpicklingError'u'UnpicklingError'b'Pickler'u'Pickler'b'Unpickler'u'Unpickler'b'dumps'u'dumps'b'load'u'load'b'loads'u'loads'b'PickleBuffer'u'PickleBuffer'b'4.0'u'4.0'b'1.2'u'1.2'b'1.3'u'1.3'b'2.0'u'2.0'b'3.0'u'3.0'b'5.0'u'5.0'b'A common base class for the other pickling exceptions.'u'A common base class for the other pickling exceptions.'b'This exception is raised when an unpicklable object is passed to the + dump() method. + + 'u'This exception is raised when an unpicklable object is passed to the + dump() method. + + 'b'This exception is raised when there is a problem unpickling an object, + such as a security violation. + + Note that other exceptions may also be raised during unpickling, including + (but not necessarily limited to) AttributeError, EOFError, ImportError, + and IndexError. + + 'u'This exception is raised when there is a problem unpickling an object, + such as a security violation. + + Note that other exceptions may also be raised during unpickling, including + (but not necessarily limited to) AttributeError, EOFError, ImportError, + and IndexError. + + 'b'J'b'K'b'R'b'V'b'j'b'o'b'I01 +'b'I00 +'b'€'b'‚'b'ƒ'b'„'b'…'b'†'b'‡'b'ˆ'b'‰'b'Š'b'‹'b'Œ'b'Ž'b'‘'b'’'b'“'b'”'b'•'b'–'b'—'b'˜'b'[A-Z][A-Z0-9_]+$'u'[A-Z][A-Z0-9_]+$'b''u''b'Can't get local attribute {!r} on {!r}'u'Can't get local attribute {!r} on {!r}'b'Can't get attribute {!r} on {!r}'u'Can't get attribute {!r} on {!r}'b'Find the module an object belong to.'u'Find the module an object belong to.'b'Encode a long to a two's complement little-endian binary string. + Note that 0 is a special case, returning an empty string, to save a + byte in the LONG1 pickling context. + + >>> encode_long(0) + b'' + >>> encode_long(255) + b'\xff\x00' + >>> encode_long(32767) + b'\xff\x7f' + >>> encode_long(-256) + b'\x00\xff' + >>> encode_long(-32768) + b'\x00\x80' + >>> encode_long(-128) + b'\x80' + >>> encode_long(127) + b'\x7f' + >>> + 'u'Encode a long to a two's complement little-endian binary string. + Note that 0 is a special case, returning an empty string, to save a + byte in the LONG1 pickling context. + + >>> encode_long(0) + b'' + >>> encode_long(255) + b'\xff\x00' + >>> encode_long(32767) + b'\xff\x7f' + >>> encode_long(-256) + b'\x00\xff' + >>> encode_long(-32768) + b'\x00\x80' + >>> encode_long(-128) + b'\x80' + >>> encode_long(127) + b'\x7f' + >>> + 'b'Decode a long from a two's complement little-endian binary string. + + >>> decode_long(b'') + 0 + >>> decode_long(b"\xff\x00") + 255 + >>> decode_long(b"\xff\x7f") + 32767 + >>> decode_long(b"\x00\xff") + -256 + >>> decode_long(b"\x00\x80") + -32768 + >>> decode_long(b"\x80") + -128 + >>> decode_long(b"\x7f") + 127 + 'u'Decode a long from a two's complement little-endian binary string. + + >>> decode_long(b'') + 0 + >>> decode_long(b"\xff\x00") + 255 + >>> decode_long(b"\xff\x7f") + 32767 + >>> decode_long(b"\x00\xff") + -256 + >>> decode_long(b"\x00\x80") + -32768 + >>> decode_long(b"\x80") + -128 + >>> decode_long(b"\x7f") + 127 + 'b'This takes a binary file for writing a pickle data stream. + + The optional *protocol* argument tells the pickler to use the + given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. + The default protocol is 4. It was introduced in Python 3.4, and + is incompatible with previous versions. + + Specifying a negative protocol version selects the highest + protocol version supported. The higher the protocol used, the + more recent the version of Python needed to read the pickle + produced. + + The *file* argument must have a write() method that accepts a + single bytes argument. It can thus be a file object opened for + binary writing, an io.BytesIO instance, or any other custom + object that meets this interface. + + If *fix_imports* is True and *protocol* is less than 3, pickle + will try to map the new Python 3 names to the old module names + used in Python 2, so that the pickle data stream is readable + with Python 2. + + If *buffer_callback* is None (the default), buffer views are + serialized into *file* as part of the pickle stream. + + If *buffer_callback* is not None, then it can be called any number + of times with a buffer view. If the callback returns a false value + (such as None), the given buffer is out-of-band; otherwise the + buffer is serialized in-band, i.e. inside the pickle stream. + + It is an error if *buffer_callback* is not None and *protocol* + is None or smaller than 5. + 'u'This takes a binary file for writing a pickle data stream. + + The optional *protocol* argument tells the pickler to use the + given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. + The default protocol is 4. It was introduced in Python 3.4, and + is incompatible with previous versions. + + Specifying a negative protocol version selects the highest + protocol version supported. The higher the protocol used, the + more recent the version of Python needed to read the pickle + produced. + + The *file* argument must have a write() method that accepts a + single bytes argument. It can thus be a file object opened for + binary writing, an io.BytesIO instance, or any other custom + object that meets this interface. + + If *fix_imports* is True and *protocol* is less than 3, pickle + will try to map the new Python 3 names to the old module names + used in Python 2, so that the pickle data stream is readable + with Python 2. + + If *buffer_callback* is None (the default), buffer views are + serialized into *file* as part of the pickle stream. + + If *buffer_callback* is not None, then it can be called any number + of times with a buffer view. If the callback returns a false value + (such as None), the given buffer is out-of-band; otherwise the + buffer is serialized in-band, i.e. inside the pickle stream. + + It is an error if *buffer_callback* is not None and *protocol* + is None or smaller than 5. + 'b'pickle protocol must be <= %d'u'pickle protocol must be <= %d'b'buffer_callback needs protocol >= 5'u'buffer_callback needs protocol >= 5'b'file must have a 'write' attribute'u'file must have a 'write' attribute'b'Clears the pickler's "memo". + + The memo is the data structure that remembers which objects the + pickler has already seen, so that shared or recursive objects + are pickled by reference and not by value. This method is + useful when re-using picklers. + 'u'Clears the pickler's "memo". + + The memo is the data structure that remembers which objects the + pickler has already seen, so that shared or recursive objects + are pickled by reference and not by value. This method is + useful when re-using picklers. + 'b'Write a pickled representation of obj to the open file.'u'Write a pickled representation of obj to the open file.'b'_file_write'u'_file_write'b'Pickler.__init__() was not called by %s.__init__()'u'Pickler.__init__() was not called by %s.__init__()'b'd'u'>d'b'PickleBuffer can only pickled with protocol >= 5'u'PickleBuffer can only pickled with protocol >= 5'b'PickleBuffer can not be pickled when pointing to a non-contiguous buffer'u'PickleBuffer can not be pickled when pointing to a non-contiguous buffer'b'surrogatepass'u'surrogatepass'b'\u005c'u'\u005c'b'\u0000'u'\u0000'b'\u000a'u'\u000a'b'\u000d'u'\u000d'b''u''b'\u001a'u'\u001a'b'Can't pickle %r: it's not the same object as %s.%s'u'Can't pickle %r: it's not the same object as %s.%s'b'Can't pickle %r: it's not found as %s.%s'u'Can't pickle %r: it's not found as %s.%s'b'can't pickle global identifier '%s.%s' using pickle protocol %i'u'can't pickle global identifier '%s.%s' using pickle protocol %i'b'This takes a binary file for reading a pickle data stream. + + The protocol version of the pickle is detected automatically, so + no proto argument is needed. + + The argument *file* must have two methods, a read() method that + takes an integer argument, and a readline() method that requires + no arguments. Both methods should return bytes. Thus *file* + can be a binary file object opened for reading, an io.BytesIO + object, or any other custom object that meets this interface. + + The file-like object must have two methods, a read() method + that takes an integer argument, and a readline() method that + requires no arguments. Both methods should return bytes. + Thus file-like object can be a binary file object opened for + reading, a BytesIO object, or any other custom object that + meets this interface. + + If *buffers* is not None, it should be an iterable of buffer-enabled + objects that is consumed each time the pickle stream references + an out-of-band buffer view. Such buffers have been given in order + to the *buffer_callback* of a Pickler object. + + If *buffers* is None (the default), then the buffers are taken + from the pickle stream, assuming they are serialized there. + It is an error for *buffers* to be None if the pickle stream + was produced with a non-None *buffer_callback*. + + Other optional arguments are *fix_imports*, *encoding* and + *errors*, which are used to control compatibility support for + pickle stream generated by Python 2. If *fix_imports* is True, + pickle will try to map the old Python 2 names to the new names + used in Python 3. The *encoding* and *errors* tell pickle how + to decode 8-bit string instances pickled by Python 2; these + default to 'ASCII' and 'strict', respectively. *encoding* can be + 'bytes' to read theses 8-bit string instances as bytes objects. + 'u'This takes a binary file for reading a pickle data stream. + + The protocol version of the pickle is detected automatically, so + no proto argument is needed. + + The argument *file* must have two methods, a read() method that + takes an integer argument, and a readline() method that requires + no arguments. Both methods should return bytes. Thus *file* + can be a binary file object opened for reading, an io.BytesIO + object, or any other custom object that meets this interface. + + The file-like object must have two methods, a read() method + that takes an integer argument, and a readline() method that + requires no arguments. Both methods should return bytes. + Thus file-like object can be a binary file object opened for + reading, a BytesIO object, or any other custom object that + meets this interface. + + If *buffers* is not None, it should be an iterable of buffer-enabled + objects that is consumed each time the pickle stream references + an out-of-band buffer view. Such buffers have been given in order + to the *buffer_callback* of a Pickler object. + + If *buffers* is None (the default), then the buffers are taken + from the pickle stream, assuming they are serialized there. + It is an error for *buffers* to be None if the pickle stream + was produced with a non-None *buffer_callback*. + + Other optional arguments are *fix_imports*, *encoding* and + *errors*, which are used to control compatibility support for + pickle stream generated by Python 2. If *fix_imports* is True, + pickle will try to map the old Python 2 names to the new names + used in Python 3. The *encoding* and *errors* tell pickle how + to decode 8-bit string instances pickled by Python 2; these + default to 'ASCII' and 'strict', respectively. *encoding* can be + 'bytes' to read theses 8-bit string instances as bytes objects. + 'b'Read a pickled object representation from the open file. + + Return the reconstituted object hierarchy specified in the file. + 'u'Read a pickled object representation from the open file. + + Return the reconstituted object hierarchy specified in the file. + 'b'_file_read'u'_file_read'b'Unpickler.__init__() was not called by %s.__init__()'u'Unpickler.__init__() was not called by %s.__init__()'b'unsupported persistent id encountered'u'unsupported persistent id encountered'b'unsupported pickle protocol: %d'u'unsupported pickle protocol: %d'b'frame size > sys.maxsize: %d'u'frame size > sys.maxsize: %d'b'LONG pickle has negative byte count'u'LONG pickle has negative byte count'b'"''b'the STRING opcode argument must be quoted'u'the STRING opcode argument must be quoted'b'BINSTRING pickle has negative byte count'u'BINSTRING pickle has negative byte count'b'BINBYTES exceeds system's maximum size of %d bytes'u'BINBYTES exceeds system's maximum size of %d bytes'b'BINUNICODE exceeds system's maximum size of %d bytes'u'BINUNICODE exceeds system's maximum size of %d bytes'b'BINUNICODE8 exceeds system's maximum size of %d bytes'u'BINUNICODE8 exceeds system's maximum size of %d bytes'b'BINBYTES8 exceeds system's maximum size of %d bytes'u'BINBYTES8 exceeds system's maximum size of %d bytes'b'BYTEARRAY8 exceeds system's maximum size of %d bytes'u'BYTEARRAY8 exceeds system's maximum size of %d bytes'b'pickle stream refers to out-of-band data but no *buffers* argument was given'u'pickle stream refers to out-of-band data but no *buffers* argument was given'b'not enough out-of-band buffers'u'not enough out-of-band buffers'b'in constructor for %s: %s'u'in constructor for %s: %s'b'STACK_GLOBAL requires str'u'STACK_GLOBAL requires str'b'EXT specifies code <= 0'u'EXT specifies code <= 0'b'unregistered extension code %d'u'unregistered extension code %d'b'pickle.find_class'u'pickle.find_class'b'negative PUT argument'u'negative PUT argument'b'negative BINPUT argument'u'negative BINPUT argument'b'negative LONG_BINPUT argument'u'negative LONG_BINPUT argument'b'Can't load pickle from unicode string'u'Can't load pickle from unicode string'b'display contents of the pickle files'u'display contents of the pickle files'b'pickle_file'u'pickle_file'b'the pickle file'u'the pickle file'b'--test'u'--test'b'run self-test suite'u'run self-test suite'b'run verbosely; only affects self-test run'u'run verbosely; only affects self-test run'Utilities to support packages.simplegenericget_importeriter_importersget_loaderwalk_packagesiter_modulesImpImporterImpLoaderread_codeextend_pathModuleInfomodule_finder name ispkgA namedtuple with minimal info about a module.Return the finder-specific module spec.Yields ModuleInfo for all modules recursively + on path, or, if path is None, all accessible modules. + + 'path' should be either None or a list of paths to look for + modules in. + + 'prefix' is a string to output on the front of every module name + on output. + + Note that this function must import all *packages* (NOT all + modules!) on the given path, in order to access the __path__ + attribute to find submodules. + + 'onerror' is a function which gets called with one argument (the + name of the package which was being imported) if any exception + occurs while trying to import a package. If no onerror function is + supplied, ImportErrors are caught and ignored, while all other + exceptions are propagated, terminating the search. + + Examples: + + # list all modules python can access + walk_packages() + + # list all submodules of ctypes + walk_packages(ctypes.__path__, ctypes.__name__+'.') + ispkgYields ModuleInfo for all submodules on path, + or, if path is None, all top-level modules on sys.path. + + 'path' should be either None or a list of paths to look for + modules in. + + 'prefix' is a string to output on the front of every module name + on output. + importerspath must be None or list of paths to look for modules in"path must be None or list of paths to look for ""modules in"yieldediter_importer_modulesimporter_iter_file_finder_modulesdircontentssubname_import_impPEP 302 Finder that wraps Python's "classic" import algorithm + + ImpImporter(dirname) produces a PEP 302 finder that searches that + directory. ImpImporter(None) produces a PEP 302 finder that searches + the current sys.path, plus any modules that are frozen or built-in. + + Note that ImpImporter does not currently support being used by placement + on sys.meta_path. + This emulation is deprecated, use 'importlib' insteadetcPEP 302 Loader that wraps Python's "classic" import algorithm + _reopenmod_typePY_SOURCEPY_COMPILEDC_EXTENSION_fix_nameLoader for module %s cannot handle module %s"Loader for module %s cannot handle ""module %s"PKG_DIRECTORY_get_delegatezipimportzipimporteriter_zipimport_modules_zip_directory_cachedirlistpath_itemRetrieve a finder for the given path item + + The returned finder is cached in sys.path_importer_cache + if it was newly created by a path hook. + + The cache (or part of it) can be cleared manually if a + rescan of sys.path_hooks is necessary. + Yield finders for the given module name + + If fullname contains a '.', the finders will be for the package + containing fullname, otherwise they will be all registered top level + finders (i.e. those on both sys.meta_path and sys.path_hooks). + + If the named module is in a package, that package is imported as a side + effect of invoking this function. + + If no module name is specified, all top level finders are produced. + Relative module name {!r} not supportedpkg_namepkgmodule_or_nameGet a "loader" object for module_or_name + + Returns None if the module cannot be found or imported. + If the named module is not already imported, its containing package + (if any) is imported, in order to establish the package __path__. + Find a "loader" object for fullname + + This is a backwards compatibility wrapper around + importlib.util.find_spec that converts most failures to ImportError + and only returns the loader rather than the full spec + Error while finding loader for {!r} ({}: {})Extend a package's path. + + Intended use is to place the following code in a package's __init__.py: + + from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) + + This will add to the package's __path__ all subdirectories of + directories on sys.path named after the package. This is useful + if one wants to distribute different parts of a single logical + package as multiple directories. + + It also looks for *.pkg files beginning where * matches the name + argument. This feature is similar to *.pth files (see site.py), + except that it doesn't special-case lines starting with 'import'. + A *.pkg file is trusted at face value: apart from checking for + duplicates, all entries found in a *.pkg file are added to the + path, regardless of whether they are exist the filesystem. (This + is a feature.) + + If the input path is not a list (as is the case for frozen + packages) it is returned unchanged. The input path is not + modified; an extended copy is returned. Items are only appended + to the copy at the end. + + It is assumed that sys.path is a sequence. Items of sys.path that + are not (unicode or 8-bit) strings referring to existing + directories are ignored. Unicode items of sys.path that cause + errors when used as filenames may cause this function to raise an + exception (in line with os.path.isdir() behavior). + .pkgsname_pkgparent_packagefinal_namesearch_pathportionpkgfileCan't open %s: %s +Get a resource from a package. + + This is a wrapper round the PEP 302 loader get_data API. The package + argument should be the name of a package, in standard module format + (foo.bar). The resource argument should be in the form of a relative + filename, using '/' as the path separator. The parent directory name '..' + is not allowed, and nor is a rooted name (starting with a '/'). + + The function returns a binary string, which is the contents of the + specified resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a PEP 302 loader + which does not support get_data(), then None is returned. + # Works with legacy finders.# This helper is needed in order for the PEP 302 emulation to# correctly handle compiled files# Skip rest of the header# don't traverse path items we've seen before# Implement a file walker for the normal importlib path hook# ignore unreadable directories like import does# handle packages before same-named modules# not a package# Note: we ignore 'path' argument since it is only used via meta_path# Note: we don't set __loader__ because we want the module to look# normal; i.e. this is just a wrapper for standard import machinery# Get the containing package's __path__# This hack fixes an impedance mismatch between pkgutil and# importlib, where the latter raises other errors for cases where# pkgutil previously raised ImportError# This could happen e.g. when this is called from inside a# frozen package. Return the path unchanged in that case.# Start with a copy of the existing path# We can't do anything: find_loader() returns None when# passed a dotted name.# Is this finder PEP 420 compliant?# XXX This may still add duplicate entries to path on# case-insensitive filesystems# XXX Is this the right thing for subpackages like zope.app?# It looks for a file named "zope.app.pkg"# Don't check for existence!# XXX needs test# Modify the resource name to be compatible with the loader.get_data# signature - an os.path format "filename" starting with the dirname of# the package's __file__b'Utilities to support packages.'u'Utilities to support packages.'b'get_importer'u'get_importer'b'iter_importers'u'iter_importers'b'get_loader'u'get_loader'b'walk_packages'u'walk_packages'b'iter_modules'u'iter_modules'b'ImpImporter'u'ImpImporter'b'ImpLoader'u'ImpLoader'b'read_code'u'read_code'b'extend_path'u'extend_path'b'ModuleInfo'u'ModuleInfo'b'module_finder name ispkg'u'module_finder name ispkg'b'A namedtuple with minimal info about a module.'u'A namedtuple with minimal info about a module.'b'Return the finder-specific module spec.'u'Return the finder-specific module spec.'b'Yields ModuleInfo for all modules recursively + on path, or, if path is None, all accessible modules. + + 'path' should be either None or a list of paths to look for + modules in. + + 'prefix' is a string to output on the front of every module name + on output. + + Note that this function must import all *packages* (NOT all + modules!) on the given path, in order to access the __path__ + attribute to find submodules. + + 'onerror' is a function which gets called with one argument (the + name of the package which was being imported) if any exception + occurs while trying to import a package. If no onerror function is + supplied, ImportErrors are caught and ignored, while all other + exceptions are propagated, terminating the search. + + Examples: + + # list all modules python can access + walk_packages() + + # list all submodules of ctypes + walk_packages(ctypes.__path__, ctypes.__name__+'.') + 'u'Yields ModuleInfo for all modules recursively + on path, or, if path is None, all accessible modules. + + 'path' should be either None or a list of paths to look for + modules in. + + 'prefix' is a string to output on the front of every module name + on output. + + Note that this function must import all *packages* (NOT all + modules!) on the given path, in order to access the __path__ + attribute to find submodules. + + 'onerror' is a function which gets called with one argument (the + name of the package which was being imported) if any exception + occurs while trying to import a package. If no onerror function is + supplied, ImportErrors are caught and ignored, while all other + exceptions are propagated, terminating the search. + + Examples: + + # list all modules python can access + walk_packages() + + # list all submodules of ctypes + walk_packages(ctypes.__path__, ctypes.__name__+'.') + 'b'Yields ModuleInfo for all submodules on path, + or, if path is None, all top-level modules on sys.path. + + 'path' should be either None or a list of paths to look for + modules in. + + 'prefix' is a string to output on the front of every module name + on output. + 'u'Yields ModuleInfo for all submodules on path, + or, if path is None, all top-level modules on sys.path. + + 'path' should be either None or a list of paths to look for + modules in. + + 'prefix' is a string to output on the front of every module name + on output. + 'b'path must be None or list of paths to look for modules in'u'path must be None or list of paths to look for modules in'b'imp'u'imp'b'PEP 302 Finder that wraps Python's "classic" import algorithm + + ImpImporter(dirname) produces a PEP 302 finder that searches that + directory. ImpImporter(None) produces a PEP 302 finder that searches + the current sys.path, plus any modules that are frozen or built-in. + + Note that ImpImporter does not currently support being used by placement + on sys.meta_path. + 'u'PEP 302 Finder that wraps Python's "classic" import algorithm + + ImpImporter(dirname) produces a PEP 302 finder that searches that + directory. ImpImporter(None) produces a PEP 302 finder that searches + the current sys.path, plus any modules that are frozen or built-in. + + Note that ImpImporter does not currently support being used by placement + on sys.meta_path. + 'b'This emulation is deprecated, use 'importlib' instead'u'This emulation is deprecated, use 'importlib' instead'b'PEP 302 Loader that wraps Python's "classic" import algorithm + 'u'PEP 302 Loader that wraps Python's "classic" import algorithm + 'b'Loader for module %s cannot handle module %s'u'Loader for module %s cannot handle module %s'b'Retrieve a finder for the given path item + + The returned finder is cached in sys.path_importer_cache + if it was newly created by a path hook. + + The cache (or part of it) can be cleared manually if a + rescan of sys.path_hooks is necessary. + 'u'Retrieve a finder for the given path item + + The returned finder is cached in sys.path_importer_cache + if it was newly created by a path hook. + + The cache (or part of it) can be cleared manually if a + rescan of sys.path_hooks is necessary. + 'b'Yield finders for the given module name + + If fullname contains a '.', the finders will be for the package + containing fullname, otherwise they will be all registered top level + finders (i.e. those on both sys.meta_path and sys.path_hooks). + + If the named module is in a package, that package is imported as a side + effect of invoking this function. + + If no module name is specified, all top level finders are produced. + 'u'Yield finders for the given module name + + If fullname contains a '.', the finders will be for the package + containing fullname, otherwise they will be all registered top level + finders (i.e. those on both sys.meta_path and sys.path_hooks). + + If the named module is in a package, that package is imported as a side + effect of invoking this function. + + If no module name is specified, all top level finders are produced. + 'b'Relative module name {!r} not supported'u'Relative module name {!r} not supported'b'Get a "loader" object for module_or_name + + Returns None if the module cannot be found or imported. + If the named module is not already imported, its containing package + (if any) is imported, in order to establish the package __path__. + 'u'Get a "loader" object for module_or_name + + Returns None if the module cannot be found or imported. + If the named module is not already imported, its containing package + (if any) is imported, in order to establish the package __path__. + 'b'Find a "loader" object for fullname + + This is a backwards compatibility wrapper around + importlib.util.find_spec that converts most failures to ImportError + and only returns the loader rather than the full spec + 'u'Find a "loader" object for fullname + + This is a backwards compatibility wrapper around + importlib.util.find_spec that converts most failures to ImportError + and only returns the loader rather than the full spec + 'b'Error while finding loader for {!r} ({}: {})'u'Error while finding loader for {!r} ({}: {})'b'Extend a package's path. + + Intended use is to place the following code in a package's __init__.py: + + from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) + + This will add to the package's __path__ all subdirectories of + directories on sys.path named after the package. This is useful + if one wants to distribute different parts of a single logical + package as multiple directories. + + It also looks for *.pkg files beginning where * matches the name + argument. This feature is similar to *.pth files (see site.py), + except that it doesn't special-case lines starting with 'import'. + A *.pkg file is trusted at face value: apart from checking for + duplicates, all entries found in a *.pkg file are added to the + path, regardless of whether they are exist the filesystem. (This + is a feature.) + + If the input path is not a list (as is the case for frozen + packages) it is returned unchanged. The input path is not + modified; an extended copy is returned. Items are only appended + to the copy at the end. + + It is assumed that sys.path is a sequence. Items of sys.path that + are not (unicode or 8-bit) strings referring to existing + directories are ignored. Unicode items of sys.path that cause + errors when used as filenames may cause this function to raise an + exception (in line with os.path.isdir() behavior). + 'u'Extend a package's path. + + Intended use is to place the following code in a package's __init__.py: + + from pkgutil import extend_path + __path__ = extend_path(__path__, __name__) + + This will add to the package's __path__ all subdirectories of + directories on sys.path named after the package. This is useful + if one wants to distribute different parts of a single logical + package as multiple directories. + + It also looks for *.pkg files beginning where * matches the name + argument. This feature is similar to *.pth files (see site.py), + except that it doesn't special-case lines starting with 'import'. + A *.pkg file is trusted at face value: apart from checking for + duplicates, all entries found in a *.pkg file are added to the + path, regardless of whether they are exist the filesystem. (This + is a feature.) + + If the input path is not a list (as is the case for frozen + packages) it is returned unchanged. The input path is not + modified; an extended copy is returned. Items are only appended + to the copy at the end. + + It is assumed that sys.path is a sequence. Items of sys.path that + are not (unicode or 8-bit) strings referring to existing + directories are ignored. Unicode items of sys.path that cause + errors when used as filenames may cause this function to raise an + exception (in line with os.path.isdir() behavior). + 'b'.pkg'u'.pkg'b'Can't open %s: %s +'u'Can't open %s: %s +'b'Get a resource from a package. + + This is a wrapper round the PEP 302 loader get_data API. The package + argument should be the name of a package, in standard module format + (foo.bar). The resource argument should be in the form of a relative + filename, using '/' as the path separator. The parent directory name '..' + is not allowed, and nor is a rooted name (starting with a '/'). + + The function returns a binary string, which is the contents of the + specified resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a PEP 302 loader + which does not support get_data(), then None is returned. + 'u'Get a resource from a package. + + This is a wrapper round the PEP 302 loader get_data API. The package + argument should be the name of a package, in standard module format + (foo.bar). The resource argument should be in the form of a relative + filename, using '/' as the path separator. The parent directory name '..' + is not allowed, and nor is a rooted name (starting with a '/'). + + The function returns a binary string, which is the contents of the + specified resource. + + For packages located in the filesystem, which have already been imported, + this is the rough equivalent of + + d = os.path.dirname(sys.modules[package].__file__) + data = open(os.path.join(d, resource), 'rb').read() + + If the package cannot be located or loaded, or it uses a PEP 302 loader + which does not support get_data(), then None is returned. + 'u'pkgutil' This module tries to retrieve as much platform-identifying data as + possible. It makes this information available via function APIs. + + If called from the command line, it prints the platform + information concatenated as single string to stdout. The output + format is useable as part of a filename. + + + Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com + Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee or royalty is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation or portions thereof, including modifications, + that you make. + + EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, + INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING + FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! + +1.0.8RCrc_ver_stages([0-9]+|[._+-])_component_re_comparable_version._+-(__libc_init)|(GLIBC_([0-9.]+))|(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)b'(__libc_init)'b'(GLIBC_([0-9.]+))'br'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)'_libc_searchlibc_ver Tries to determine the libc version that the file executable + (which defaults to the Python interpreter) is linked against. + + Returns a tuple of strings (lib,version) which default to the + given parameters in case the lookup fails. + + Note that the function has intimate knowledge of how different + libc versions add symbols to the executable and thus is probably + only useable for executables compiled using gcc. + + The file is read and scanned in chunks of chunksize bytes. + + confstrCS_GNU_LIBC_VERSIONverlibcGLIBClibcinitglibcglibcversionsosoversion_norm_version Normalize the version and build strings and return a single + version string using the format major.minor.build (or patchlevel). + (?:([\w ]+) ([\w.]+) .*\[.* ([\d.]+)\])r'(?:([\w ]+) ([\w.]+) 'r'.*'r'\[.* ([\d.]+)\])'_ver_output_syscmd_verwin16dossupported_platforms Tries to figure out the OS version used and returns + a tuple (system, release, version). + + It uses the "ver" shell command for this which is known + to exists on Windows, DOS. XXX Others too ? + + In case this fails, the given parameters are used as + defaults. + + command /c vercmd /c verCalledProcessErrorXP2003Serverpost2003Vista8.1post8.1post10_WIN32_CLIENT_RELEASES2008Server2008ServerR22012Server2012ServerR2post2012ServerR2_WIN32_SERVER_RELEASESwin32_is_iotwin32_editionIoTUAPNanoServerWindowsCoreHeadlessIoTEdgeOSSOFTWARE\Microsoft\Windows NT\CurrentVersioncvkeyOpenKeyExEditionIdwin32_vercsdptypewinverplatform_version{0}.{1}.{2}SP{}service_pack_majorService Pack SPproduct_typeCurrentType_mac_ver_xmlplistlibProductVersionversioninfoPower Macintosh Get macOS version information and return it as tuple (release, + versioninfo, machine) with versioninfo being a tuple (version, + dev_stage, non_release_version). + + Entries which cannot be determined are set to the parameter values + which default to ''. All tuple entries are strings. + _java_getpropjava.langSystemgetPropertyjava_vervendorvminfoosinfo Version interface for Jython. + + Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being + a tuple (vm_name, vm_release, vm_vendor) and osinfo being a + tuple (os_name, os_version, os_arch). + + Values which cannot be determined are set to the defaults + given as parameters (which all default to ''). + + java.vendorjava.versionvm_namevm_releasevm_vendorjava.vm.namejava.vm.vendorjava.vm.versionos_nameos_versionos_archjava.os.archjava.os.namejava.os.versionsystem_alias Returns (system, release, version) aliased to common + marketing names used for some systems. + + It also does some reordering of the information in some cases + where it would otherwise cause confusion. + + SunOSSolarisIRIX64IRIX (64bit)64bitWindows_platform Helper to format the platform string in a filename + compatible format e.g. "system-version-machine". + cleaned_node Helper to determine the node name of this machine. + _follow_symlinks In case filepath is a symlink, follow it until a + real file is reached. + _syscmd_uname Interface to the system's uname command. + _syscmd_file Interface to the system's file command. + + The function uses the -b option of the file command to have it + omit the filename in its output. Follow the symlinks. It returns + default in case the command should fail. + + WindowsPEMSDOS_default_architecturearchitecturelinkage Queries the given executable (defaults to the Python interpreter + binary) for various architecture information. + + Returns a tuple (bits, linkage) which contains information about + the bit architecture and the linkage format used for the + executable. Both values are returned as strings. + + Values that cannot be determined are returned as given by the + parameter presets. If bits is given as '', the sizeof(pointer) + (or sizeof(long) on Python version < 1.5.2) is used as + indicator for the supported pointer size. + + The function relies on the system's "file" command to do the + actual work. This is available on most if not all Unix + platforms. On some non-Unix platforms where the "file" command + does not exist and the executable is set to the Python interpreter + binary defaults from _default_architecture are used. + + fileoutshared object32-bit32bitN32n32bit64-bitELFPECOFFMS-DOSuname_resultsystem node release version machine processor_uname_cache Fairly portable uname interface. Returns a tuple + of strings (system, node, release, version, machine, processor) + identifying the underlying platform. + + Note that unlike the os.uname function this also returns + possible processor information as an additional tuple entry. + + Entries which cannot be determined are set to ''. + + no_os_unameprocessoruse_syscmd_verPROCESSOR_ARCHITEW6432PROCESSOR_ARCHITECTUREPROCESSOR_IDENTIFIERMicrosoft WindowsMicrosoft6.016bitJavaOpenVMSvms_libgetsyiSYI$_CPUcsidcpu_numberVAX Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. + + An empty string is returned if the value cannot be determined. + + Returns the computer's network name (which may not be fully + qualified) + + An empty string is returned if the value cannot be determined. + + Returns the system's release, e.g. '2.2.0' or 'NT' + + An empty string is returned if the value cannot be determined. + + Returns the system's release version, e.g. '#3 on degas' + + An empty string is returned if the value cannot be determined. + + Returns the machine type, e.g. 'i386' + + An empty string is returned if the value cannot be determined. + + Returns the (true) processor name, e.g. 'amdk6' + + An empty string is returned if the value cannot be + determined. Note that many platforms do not provide this + information or simply return the same value as for machine(), + e.g. NetBSD does this. + + ([\w.+]+)\s*\(#?([^,]+)(?:,\s*([\w ]*)(?:,\s*([\w :]*))?)?\)\s*\[([^\]]+)\]?r'([\w.+]+)\s*'r'\(#?([^,]+)'r'(?:,\s*([\w ]*)'r'(?:,\s*([\w :]*))?)?\)\s*'r'\[([^\]]+)\]?'_sys_version_parserIronPython\s*([\d\.]+)(?: \(([\d\.]+)\))? on (.NET [\d\.]+)r'IronPython\s*'r'([\d\.]+)'r'(?: \(([\d\.]+)\))?'r' on (.NET [\d\.]+)'_ironpython_sys_version_parser([\d.]+)\s*\(IronPython\s*[\d.]+\s*\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)r'([\d.]+)\s*'r'\(IronPython\s*'r'[\d.]+\s*'r'\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'_ironpython26_sys_version_parser([\w.+]+)\s*\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*\[PyPy [^\]]+\]?r'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'r'\[PyPy [^\]]+\]?'_pypy_sys_version_parser_sys_version_cache_sys_version Returns a parsed version of Python's sys.version as tuple + (name, version, branch, revision, buildno, builddate, compiler) + referring to the Python implementation name, version, branch, + revision, build number, build date/time as string and the compiler + identification string. + + Note that unlike the Python sys.version, the returned value + for the Python version will always include the patchlevel (it + defaults to '.0'). + + The function returns empty strings for tuple entries that + cannot be determined. + + sys_version may be given to parse an alternative version + string, e.g. if the version was read from a different Python + interpreter. + + IronPythonfailed to parse IronPython sys.version: %salt_versionbuildnobuilddateJythonfailed to parse Jython sys.version: %sbuildtimePyPyfailed to parse PyPy sys.version: %sfailed to parse CPython sys.version: %sCPythonbranchrevision_mercurial Returns a string identifying the Python implementation. + + Currently, the following implementations are identified: + 'CPython' (C implementation of Python), + 'IronPython' (.NET implementation of Python), + 'Jython' (Java implementation of Python), + 'PyPy' (Python implementation of Python). + + python_version Returns the Python version as string 'major.minor.patchlevel' + + Note that unlike the Python sys.version, the returned value + will always include the patchlevel (it defaults to 0). + + python_version_tuple Returns the Python version as tuple (major, minor, patchlevel) + of strings. + + Note that unlike the Python sys.version, the returned value + will always include the patchlevel (it defaults to 0). + + python_branch Returns a string identifying the Python implementation + branch. + + For CPython this is the SCM branch from which the + Python binary was built. + + If not available, an empty string is returned. + + python_revision Returns a string identifying the Python implementation + revision. + + For CPython this is the SCM revision from which the + Python binary was built. + + If not available, an empty string is returned. + + python_build Returns a tuple (buildno, builddate) stating the Python + build number and date as strings. + + python_compiler Returns a string identifying the compiler used for compiling + Python. + + _platform_cachealiasedterse Returns a single string identifying the underlying platform + with as much useful information as possible (but no more :). + + The output is intended to be human readable rather than + machine parseable. It may look different on different + platforms and this is intended. + + If "aliased" is true, the function will use aliases for + various platforms that report system names which differ from + their common names, e.g. SunOS will be reported as + Solaris. The system_alias() function is used to implement + this. + + Setting terse to true causes the function to return only the + absolute minimum information needed to identify the platform. + + Darwinmacos_releasemacOSrelverslibcnamelibcversion--tersenonaliased--nonaliased#!/usr/bin/env python3# This module is maintained by Marc-Andre Lemburg .# If you find problems, please submit bug reports/patches via the# Python bug tracker (http://bugs.python.org) and assign them to "lemburg".# Still needed:# * support for MS-DOS (PythonDX ?)# * support for Amiga and other still unsupported platforms running Python# * support for additional Linux distributions# Many thanks to all those who helped adding platform-specific# checks (in no particular order):# Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,# Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef# Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg# Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark# Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter, Steve# Dower# History:# # 1.0.8 - changed Windows support to read version from kernel32.dll# 1.0.7 - added DEV_NULL# 1.0.6 - added linux_distribution()# 1.0.5 - fixed Java support to allow running the module on Jython# 1.0.4 - added IronPython support# 1.0.3 - added normalization of Windows system name# 1.0.2 - added more Windows support# 1.0.1 - reformatted to make doc.py happy# 1.0.0 - reformatted a bit and checked into Python CVS# 0.8.0 - added sys.version parser and various new access# APIs (python_version(), python_compiler(), etc.)# 0.7.2 - fixed architecture() to use sizeof(pointer) where available# 0.7.1 - added support for Caldera OpenLinux# 0.7.0 - some fixes for WinCE; untabified the source file# 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and# vms_lib.getsyi() configured# 0.6.1 - added code to prevent 'uname -p' on platforms which are# known not to support it# 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;# did some cleanup of the interfaces - some APIs have changed# 0.5.5 - fixed another type in the MacOS code... should have# used more coffee today ;-)# 0.5.4 - fixed a few typos in the MacOS code# 0.5.3 - added experimental MacOS support; added better popen()# workarounds in _syscmd_ver() -- still not 100% elegant# though# 0.5.2 - fixed uname() to return '' instead of 'unknown' in all# return values (the system uname command tends to return# 'unknown' instead of just leaving the field empty)# 0.5.1 - included code for slackware dist; added exception handlers# to cover up situations where platforms don't have os.popen# (e.g. Mac) or fail on socket.gethostname(); fixed libc# detection RE# 0.5.0 - changed the API names referring to system commands to *syscmd*;# added java_ver(); made syscmd_ver() a private# API (was system_ver() in previous versions) -- use uname()# instead; extended the win32_ver() to also return processor# type information# 0.4.0 - added win32_ver() and modified the platform() output for WinXX# 0.3.4 - fixed a bug in _follow_symlinks()# 0.3.3 - fixed popen() and "file" command invocation bugs# 0.3.2 - added architecture() API and support for it in platform()# 0.3.1 - fixed syscmd_ver() RE to support Windows NT# 0.3.0 - added system alias support# 0.2.3 - removed 'wince' again... oh well.# 0.2.2 - added 'wince' to syscmd_ver() supported platforms# 0.2.1 - added cache logic and changed the platform string format# 0.2.0 - changed the API to use functions instead of module globals# since some action take too long to be run on module import# 0.1.0 - first release# You can always get the latest version of this module at:# http://www.egenix.com/files/python/platform.py# If that URL should fail, try contacting the author.### Globals & Constants# Helper for comparing two version number strings.# Based on the description of the PHP's version_compare():# http://php.net/manual/en/function.version-compare.php# any string not found in this dict, will get 0 assigned# number, will get 100 assigned### Platform specific APIs# parse 'glibc 2.28' as ('glibc', '2.28')# os.confstr() or CS_GNU_LIBC_VERSION value not available# Python 2.2 introduced os.path.realpath(); it is used# here to work around problems with Cygwin not being# able to open symlinks for reading# Examples of VER command output:# Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]# Windows XP: Microsoft Windows XP [Version 5.1.2600]# Windows Vista: Microsoft Windows [Version 6.0.6002]# Note that the "Version" string gets localized on different# Windows versions.# Try some common cmd strings#print('Command %s failed: %s' % (cmd, why))# Parse the output# Strip trailing dots from version and release# Normalize the version and build strings (eliminating additional# zeros)# Strictly, 5.2 client is XP 64-bit, but platform.py historically# has always called it 2003 Server# Server release name lookup will default to client names if necessary# getwindowsversion() reflect the compatibility mode Python is# running under, and so the service pack value is only going to be# valid if the versions match.# VER_NT_SERVER = 3# Canonical name# First try reading the information from an XML file which should# always be present# If that also doesn't work return the default values# Import the needed APIs### System name aliasing# Sun's OS# These releases use the old name SunOS# Modify release (marketing release = SunOS release - 3)# XXX Whatever the new SunOS marketing name is...# IRIX reports IRIX64 on platforms with 64-bit support; yet it# is really a version and not a different platform, since 32-bit# apps are also supported..# In case one of the other tricks# bpo-35516: Don't replace Darwin with macOS since input release and# version arguments can be different than the currently running version.### Various internal helpers# Format the platform string# Cleanup some possible filename obstacles...# No need to report 'unknown' information...# Fold '--'s and remove trailing '-'# No sockets...# Still not working...# XXX Others too ?# "file" output is locale dependent: force the usage of the C locale# to get deterministic behavior.# -b: do not prepend filenames to output lines (brief mode)# With the C locale, the output should be mostly ASCII-compatible.# Decode from Latin-1 to prevent Unicode decode error.### Information about the used architecture# Default values for architecture; non-empty strings override the# defaults given as parameters# Use the sizeof(pointer) as default number of bits if nothing# else is given as default.# Get data from the 'file' system command# "file" command did not return anything; we'll try to provide# some sensible defaults then...# Format not supported# Bits# On Irix only# Linkage# E.g. Windows uses this format# XXX the A.OUT format also falls under this class...### Portable uname() interface# Get some infos from the builtin os.uname API...# Hmm, no there is either no uname or uname has returned#'unknowns'... we'll have to poke around the system then.# Try win32_ver() on win32 platforms# Try to use the PROCESSOR_* environment variables# available on Win XP and later; see# http://support.microsoft.com/kb/888731 and# http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM# WOW64 processes mask the native architecture# Try the 'ver' system command available on some# platforms# Normalize system to what win32_ver() normally returns# (_syscmd_ver() tends to return the vendor name as well)# Under Windows Vista and Windows Server 2008,# Microsoft changed the output of the ver command. The# release is no longer printed. This causes the# system and release to be misidentified.# In case we still don't know anything useful, we'll try to# help ourselves# System specific extensions# OpenVMS seems to have release and version mixed up# Get processor information# Get processor information from the uname system command#If any unknowns still exist, replace them with ''s, which are more portable# normalize name### Direct interfaces to some of the uname() return values### Various APIs for extracting information from sys.version# "version"# "(#buildno"# ", builddate"# ", buildtime)"# "[compiler]"# IronPython covering 2.6 and 2.7# Get the Python version# Try the cache first# Parse it# IronPython# Jython# PyPy# CPython# Add the patchlevel version if missing# Build and cache the result### The Opus Magnum of platform strings :-)# Get uname information and then apply platform specific cosmetics# to it...# macOS (darwin kernel)# MS platforms# check for libc vs. glibc# Java platforms# Generic handler### Command line interface# Default is to print the aliased verbose platform stringb' This module tries to retrieve as much platform-identifying data as + possible. It makes this information available via function APIs. + + If called from the command line, it prints the platform + information concatenated as single string to stdout. The output + format is useable as part of a filename. + +'u' This module tries to retrieve as much platform-identifying data as + possible. It makes this information available via function APIs. + + If called from the command line, it prints the platform + information concatenated as single string to stdout. The output + format is useable as part of a filename. + +'b' + Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com + Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee or royalty is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation or portions thereof, including modifications, + that you make. + + EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, + INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING + FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! + +'u' + Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com + Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee or royalty is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation or portions thereof, including modifications, + that you make. + + EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, + INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING + FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! + +'b'1.0.8'u'1.0.8'b'dev'u'dev'b'RC'u'RC'b'rc'u'rc'b'([0-9]+|[._+-])'u'([0-9]+|[._+-])'b'._+-'u'._+-'b'(__libc_init)|(GLIBC_([0-9.]+))|(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)'b' Tries to determine the libc version that the file executable + (which defaults to the Python interpreter) is linked against. + + Returns a tuple of strings (lib,version) which default to the + given parameters in case the lookup fails. + + Note that the function has intimate knowledge of how different + libc versions add symbols to the executable and thus is probably + only useable for executables compiled using gcc. + + The file is read and scanned in chunks of chunksize bytes. + + 'u' Tries to determine the libc version that the file executable + (which defaults to the Python interpreter) is linked against. + + Returns a tuple of strings (lib,version) which default to the + given parameters in case the lookup fails. + + Note that the function has intimate knowledge of how different + libc versions add symbols to the executable and thus is probably + only useable for executables compiled using gcc. + + The file is read and scanned in chunks of chunksize bytes. + + 'b'CS_GNU_LIBC_VERSION'u'CS_GNU_LIBC_VERSION'b'libc'b'GLIBC'u'libc'b'glibc'u'glibc'b' Normalize the version and build strings and return a single + version string using the format major.minor.build (or patchlevel). + 'u' Normalize the version and build strings and return a single + version string using the format major.minor.build (or patchlevel). + 'b'(?:([\w ]+) ([\w.]+) .*\[.* ([\d.]+)\])'u'(?:([\w ]+) ([\w.]+) .*\[.* ([\d.]+)\])'b'win16'u'win16'b'dos'u'dos'b' Tries to figure out the OS version used and returns + a tuple (system, release, version). + + It uses the "ver" shell command for this which is known + to exists on Windows, DOS. XXX Others too ? + + In case this fails, the given parameters are used as + defaults. + + 'u' Tries to figure out the OS version used and returns + a tuple (system, release, version). + + It uses the "ver" shell command for this which is known + to exists on Windows, DOS. XXX Others too ? + + In case this fails, the given parameters are used as + defaults. + + 'b'ver'u'ver'b'command /c ver'u'command /c ver'b'cmd /c ver'u'cmd /c ver'b'2000'u'2000'b'XP'u'XP'b'2003Server'u'2003Server'b'post2003'u'post2003'b'Vista'u'Vista'b'8.1'u'8.1'b'post8.1'u'post8.1'b'post10'u'post10'b'2008Server'u'2008Server'b'2008ServerR2'u'2008ServerR2'b'2012Server'u'2012Server'b'2012ServerR2'u'2012ServerR2'b'post2012ServerR2'u'post2012ServerR2'b'IoTUAP'u'IoTUAP'b'NanoServer'u'NanoServer'b'WindowsCoreHeadless'u'WindowsCoreHeadless'b'IoTEdgeOS'u'IoTEdgeOS'b'SOFTWARE\Microsoft\Windows NT\CurrentVersion'u'SOFTWARE\Microsoft\Windows NT\CurrentVersion'b'EditionId'u'EditionId'b'{0}.{1}.{2}'u'{0}.{1}.{2}'b'SP{}'u'SP{}'b'Service Pack 'u'Service Pack 'b'SP'u'SP'b'product_type'u'product_type'b'CurrentType'u'CurrentType'b'ProductVersion'u'ProductVersion'b'Power Macintosh'u'Power Macintosh'b' Get macOS version information and return it as tuple (release, + versioninfo, machine) with versioninfo being a tuple (version, + dev_stage, non_release_version). + + Entries which cannot be determined are set to the parameter values + which default to ''. All tuple entries are strings. + 'u' Get macOS version information and return it as tuple (release, + versioninfo, machine) with versioninfo being a tuple (version, + dev_stage, non_release_version). + + Entries which cannot be determined are set to the parameter values + which default to ''. All tuple entries are strings. + 'b' Version interface for Jython. + + Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being + a tuple (vm_name, vm_release, vm_vendor) and osinfo being a + tuple (os_name, os_version, os_arch). + + Values which cannot be determined are set to the defaults + given as parameters (which all default to ''). + + 'u' Version interface for Jython. + + Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being + a tuple (vm_name, vm_release, vm_vendor) and osinfo being a + tuple (os_name, os_version, os_arch). + + Values which cannot be determined are set to the defaults + given as parameters (which all default to ''). + + 'b'java.vendor'u'java.vendor'b'java.version'u'java.version'b'java.vm.name'u'java.vm.name'b'java.vm.vendor'u'java.vm.vendor'b'java.vm.version'u'java.vm.version'b'java.os.arch'u'java.os.arch'b'java.os.name'u'java.os.name'b'java.os.version'u'java.os.version'b' Returns (system, release, version) aliased to common + marketing names used for some systems. + + It also does some reordering of the information in some cases + where it would otherwise cause confusion. + + 'u' Returns (system, release, version) aliased to common + marketing names used for some systems. + + It also does some reordering of the information in some cases + where it would otherwise cause confusion. + + 'b'SunOS'u'SunOS'b'Solaris'u'Solaris'b'IRIX64'u'IRIX64'b'IRIX'u'IRIX'b' (64bit)'u' (64bit)'b'64bit'u'64bit'b'Windows'u'Windows'b' Helper to format the platform string in a filename + compatible format e.g. "system-version-machine". + 'u' Helper to format the platform string in a filename + compatible format e.g. "system-version-machine". + 'b' Helper to determine the node name of this machine. + 'u' Helper to determine the node name of this machine. + 'b' In case filepath is a symlink, follow it until a + real file is reached. + 'u' In case filepath is a symlink, follow it until a + real file is reached. + 'b' Interface to the system's uname command. + 'u' Interface to the system's uname command. + 'b'uname'u'uname'b' Interface to the system's file command. + + The function uses the -b option of the file command to have it + omit the filename in its output. Follow the symlinks. It returns + default in case the command should fail. + + 'u' Interface to the system's file command. + + The function uses the -b option of the file command to have it + omit the filename in its output. Follow the symlinks. It returns + default in case the command should fail. + + 'b'WindowsPE'u'WindowsPE'b'MSDOS'u'MSDOS'b' Queries the given executable (defaults to the Python interpreter + binary) for various architecture information. + + Returns a tuple (bits, linkage) which contains information about + the bit architecture and the linkage format used for the + executable. Both values are returned as strings. + + Values that cannot be determined are returned as given by the + parameter presets. If bits is given as '', the sizeof(pointer) + (or sizeof(long) on Python version < 1.5.2) is used as + indicator for the supported pointer size. + + The function relies on the system's "file" command to do the + actual work. This is available on most if not all Unix + platforms. On some non-Unix platforms where the "file" command + does not exist and the executable is set to the Python interpreter + binary defaults from _default_architecture are used. + + 'u' Queries the given executable (defaults to the Python interpreter + binary) for various architecture information. + + Returns a tuple (bits, linkage) which contains information about + the bit architecture and the linkage format used for the + executable. Both values are returned as strings. + + Values that cannot be determined are returned as given by the + parameter presets. If bits is given as '', the sizeof(pointer) + (or sizeof(long) on Python version < 1.5.2) is used as + indicator for the supported pointer size. + + The function relies on the system's "file" command to do the + actual work. This is available on most if not all Unix + platforms. On some non-Unix platforms where the "file" command + does not exist and the executable is set to the Python interpreter + binary defaults from _default_architecture are used. + + 'b'bit'u'bit'b'shared object'u'shared object'b'32-bit'u'32-bit'b'32bit'u'32bit'b'N32'u'N32'b'n32bit'u'n32bit'b'64-bit'u'64-bit'b'ELF'u'ELF'b'PE'u'PE'b'COFF'u'COFF'b'MS-DOS'u'MS-DOS'b'uname_result'u'uname_result'b'system node release version machine processor'u'system node release version machine processor'b' Fairly portable uname interface. Returns a tuple + of strings (system, node, release, version, machine, processor) + identifying the underlying platform. + + Note that unlike the os.uname function this also returns + possible processor information as an additional tuple entry. + + Entries which cannot be determined are set to ''. + + 'u' Fairly portable uname interface. Returns a tuple + of strings (system, node, release, version, machine, processor) + identifying the underlying platform. + + Note that unlike the os.uname function this also returns + possible processor information as an additional tuple entry. + + Entries which cannot be determined are set to ''. + + 'b'PROCESSOR_ARCHITEW6432'u'PROCESSOR_ARCHITEW6432'b'PROCESSOR_ARCHITECTURE'u'PROCESSOR_ARCHITECTURE'b'PROCESSOR_IDENTIFIER'u'PROCESSOR_IDENTIFIER'b'Microsoft Windows'u'Microsoft Windows'b'Microsoft'u'Microsoft'b'6.0'u'6.0'b'16bit'u'16bit'b'Java'u'Java'b'OpenVMS'u'OpenVMS'b'SYI$_CPU'u'SYI$_CPU'b'VAX'u'VAX'b' Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. + + An empty string is returned if the value cannot be determined. + + 'u' Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. + + An empty string is returned if the value cannot be determined. + + 'b' Returns the computer's network name (which may not be fully + qualified) + + An empty string is returned if the value cannot be determined. + + 'u' Returns the computer's network name (which may not be fully + qualified) + + An empty string is returned if the value cannot be determined. + + 'b' Returns the system's release, e.g. '2.2.0' or 'NT' + + An empty string is returned if the value cannot be determined. + + 'u' Returns the system's release, e.g. '2.2.0' or 'NT' + + An empty string is returned if the value cannot be determined. + + 'b' Returns the system's release version, e.g. '#3 on degas' + + An empty string is returned if the value cannot be determined. + + 'u' Returns the system's release version, e.g. '#3 on degas' + + An empty string is returned if the value cannot be determined. + + 'b' Returns the machine type, e.g. 'i386' + + An empty string is returned if the value cannot be determined. + + 'u' Returns the machine type, e.g. 'i386' + + An empty string is returned if the value cannot be determined. + + 'b' Returns the (true) processor name, e.g. 'amdk6' + + An empty string is returned if the value cannot be + determined. Note that many platforms do not provide this + information or simply return the same value as for machine(), + e.g. NetBSD does this. + + 'u' Returns the (true) processor name, e.g. 'amdk6' + + An empty string is returned if the value cannot be + determined. Note that many platforms do not provide this + information or simply return the same value as for machine(), + e.g. NetBSD does this. + + 'b'([\w.+]+)\s*\(#?([^,]+)(?:,\s*([\w ]*)(?:,\s*([\w :]*))?)?\)\s*\[([^\]]+)\]?'u'([\w.+]+)\s*\(#?([^,]+)(?:,\s*([\w ]*)(?:,\s*([\w :]*))?)?\)\s*\[([^\]]+)\]?'b'IronPython\s*([\d\.]+)(?: \(([\d\.]+)\))? on (.NET [\d\.]+)'u'IronPython\s*([\d\.]+)(?: \(([\d\.]+)\))? on (.NET [\d\.]+)'b'([\d.]+)\s*\(IronPython\s*[\d.]+\s*\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'u'([\d.]+)\s*\(IronPython\s*[\d.]+\s*\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'b'([\w.+]+)\s*\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*\[PyPy [^\]]+\]?'u'([\w.+]+)\s*\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*\[PyPy [^\]]+\]?'b' Returns a parsed version of Python's sys.version as tuple + (name, version, branch, revision, buildno, builddate, compiler) + referring to the Python implementation name, version, branch, + revision, build number, build date/time as string and the compiler + identification string. + + Note that unlike the Python sys.version, the returned value + for the Python version will always include the patchlevel (it + defaults to '.0'). + + The function returns empty strings for tuple entries that + cannot be determined. + + sys_version may be given to parse an alternative version + string, e.g. if the version was read from a different Python + interpreter. + + 'u' Returns a parsed version of Python's sys.version as tuple + (name, version, branch, revision, buildno, builddate, compiler) + referring to the Python implementation name, version, branch, + revision, build number, build date/time as string and the compiler + identification string. + + Note that unlike the Python sys.version, the returned value + for the Python version will always include the patchlevel (it + defaults to '.0'). + + The function returns empty strings for tuple entries that + cannot be determined. + + sys_version may be given to parse an alternative version + string, e.g. if the version was read from a different Python + interpreter. + + 'b'IronPython'u'IronPython'b'failed to parse IronPython sys.version: %s'u'failed to parse IronPython sys.version: %s'b'Jython'u'Jython'b'failed to parse Jython sys.version: %s'u'failed to parse Jython sys.version: %s'b'PyPy'u'PyPy'b'failed to parse PyPy sys.version: %s'u'failed to parse PyPy sys.version: %s'b'failed to parse CPython sys.version: %s'u'failed to parse CPython sys.version: %s'b'CPython'b'_git'u'_git'b'_mercurial'u'_mercurial'b' Returns a string identifying the Python implementation. + + Currently, the following implementations are identified: + 'CPython' (C implementation of Python), + 'IronPython' (.NET implementation of Python), + 'Jython' (Java implementation of Python), + 'PyPy' (Python implementation of Python). + + 'u' Returns a string identifying the Python implementation. + + Currently, the following implementations are identified: + 'CPython' (C implementation of Python), + 'IronPython' (.NET implementation of Python), + 'Jython' (Java implementation of Python), + 'PyPy' (Python implementation of Python). + + 'b' Returns the Python version as string 'major.minor.patchlevel' + + Note that unlike the Python sys.version, the returned value + will always include the patchlevel (it defaults to 0). + + 'u' Returns the Python version as string 'major.minor.patchlevel' + + Note that unlike the Python sys.version, the returned value + will always include the patchlevel (it defaults to 0). + + 'b' Returns the Python version as tuple (major, minor, patchlevel) + of strings. + + Note that unlike the Python sys.version, the returned value + will always include the patchlevel (it defaults to 0). + + 'u' Returns the Python version as tuple (major, minor, patchlevel) + of strings. + + Note that unlike the Python sys.version, the returned value + will always include the patchlevel (it defaults to 0). + + 'b' Returns a string identifying the Python implementation + branch. + + For CPython this is the SCM branch from which the + Python binary was built. + + If not available, an empty string is returned. + + 'u' Returns a string identifying the Python implementation + branch. + + For CPython this is the SCM branch from which the + Python binary was built. + + If not available, an empty string is returned. + + 'b' Returns a string identifying the Python implementation + revision. + + For CPython this is the SCM revision from which the + Python binary was built. + + If not available, an empty string is returned. + + 'u' Returns a string identifying the Python implementation + revision. + + For CPython this is the SCM revision from which the + Python binary was built. + + If not available, an empty string is returned. + + 'b' Returns a tuple (buildno, builddate) stating the Python + build number and date as strings. + + 'u' Returns a tuple (buildno, builddate) stating the Python + build number and date as strings. + + 'b' Returns a string identifying the compiler used for compiling + Python. + + 'u' Returns a string identifying the compiler used for compiling + Python. + + 'b' Returns a single string identifying the underlying platform + with as much useful information as possible (but no more :). + + The output is intended to be human readable rather than + machine parseable. It may look different on different + platforms and this is intended. + + If "aliased" is true, the function will use aliases for + various platforms that report system names which differ from + their common names, e.g. SunOS will be reported as + Solaris. The system_alias() function is used to implement + this. + + Setting terse to true causes the function to return only the + absolute minimum information needed to identify the platform. + + 'u' Returns a single string identifying the underlying platform + with as much useful information as possible (but no more :). + + The output is intended to be human readable rather than + machine parseable. It may look different on different + platforms and this is intended. + + If "aliased" is true, the function will use aliases for + various platforms that report system names which differ from + their common names, e.g. SunOS will be reported as + Solaris. The system_alias() function is used to implement + this. + + Setting terse to true causes the function to return only the + absolute minimum information needed to identify the platform. + + 'b'Darwin'u'Darwin'b'macOS'u'macOS'b'on'u'on'b'terse'u'terse'b'--terse'u'--terse'b'nonaliased'u'nonaliased'b'--nonaliased'u'--nonaliased'u'platform'plistlib.py -- a tool to generate and parse MacOSX .plist files. + +The property list (.plist) file format is a simple XML pickle supporting +basic object types, like dictionaries, lists, numbers and strings. +Usually the top level object is a dictionary. + +To write out a plist file, use the dump(value, file) +function. 'value' is the top level object, 'file' is +a (writable) file object. + +To parse a plist from a file, use the load(file) function, +with a (readable) file object as the only argument. It +returns the top level object (again, usually a dictionary). + +To work with plist data in bytes objects, you can use loads() +and dumps(). + +Values can be strings, integers, floats, booleans, tuples, lists, +dictionaries (but only with string keys), Data, bytes, bytearray, or +datetime.datetime objects. + +Generate Plist example: + + pl = dict( + aString = "Doodah", + aList = ["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, + aDict = dict( + anotherString = "", + aUnicodeValue = "M\xe4ssig, Ma\xdf", + aTrueValue = True, + aFalseValue = False, + ), + someData = b"", + someMoreData = b"" * 10, + aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), + ) + with open(fileName, 'wb') as fp: + dump(pl, fp) + +Parse Plist example: + + with open(fileName, 'rb') as fp: + pl = load(fp) + print(pl["aKey"]) +readPlistwritePlistreadPlistFromByteswritePlistToBytesDataInvalidFileExceptionFMT_XMLFMT_BINARYUIDxml.parsers.expatPlistFormatFMT_XML FMT_BINARY_maybe_openpathOrFile + Read a .plist from a path or file. pathOrFile should either + be a file name, or a readable binary file object. + + This function is deprecated, use load instead. + The readPlist function is deprecated, use load() instead + Write 'value' to a .plist file. 'pathOrFile' may either be a + file name or a (writable) file object. + + This function is deprecated, use dump instead. + The writePlist function is deprecated, use dump() insteadsort_keysskipkeys + Read a plist data from a bytes object. Return the root object. + + This function is deprecated, use loads instead. + The readPlistFromBytes function is deprecated, use loads() instead + Return 'value' as a plist-formatted bytes object. + + This function is deprecated, use dumps instead. + The writePlistToBytes function is deprecated, use dumps() instead + Wrapper for binary data. + + This class is deprecated, use a bytes object instead. + data must be as bytesfromBase64_decode_base64asBase64maxlinelength_encode_base64data must be an intUIDs cannot be >= 2**64UIDs must be positive + +b"""PLISTHEADER[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f"r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]"_controlCharPatmaxbinsize(?P\d\d\d\d)(?:-(?P\d\d)(?:-(?P\d\d)(?:T(?P\d\d)(?::(?P\d\d)(?::(?P\d\d))?)?)?)?)?Z_dateParser_date_from_string_date_to_string%04d-%02d-%02dT%02d:%02d:%02dZ_escapestrings can't contains control characters; use bytes instead"strings can't contains control characters; ""use bytes instead"_PlistParserdict_typecurrent_key_dict_typehandle_begin_elementhandle_end_elementhandle_datahandle_entity_declEntityDeclHandlerParseFileentity_nameis_parameter_entitysystem_idpublic_idnotation_nameXML entity declarations are not supported in plist filesbegin_add_objectunexpected element at line %dCurrentLineNumberbegin_dictend_dictmissing value for key '%s' at line %dend_keyunexpected key at line %dbegin_arrayend_trueend_falseend_integer0Xend_realend_dataend_date_DumbXMLWriterindent_level_indent_levelbegin_elementwriteln<%s>end_elementsimple_element<%s>%s<%s/>_PlistWriterwriteHeader_sort_keys_skipkeyswrite_valuetruefalsewrite_dictwrite_datawrite_byteswrite_arrayunsupported type: %skeys must be strings_is_fmt_xml6xBBQQQoffset_size_ref_sizenum_objectstop_objectoffset_table_offset_read_ints_object_offsets_read_object_get_sizetokenL return the size of the next object.0xF_read_refs + read the object by reference. + + May recursively read sub-objects (content of an array/dict/set) + 0xF00x0FtokenH0x080x090x0f0x22>f0x230x330x400x500x60utf-16be0xA0obj_refs0xD0key_refs_count_to_size_scalars_BinaryPlistWriter_objlist_objtable_objidtable_ref_formatbplist00_write_object_getrefnumoffset_formatsort_version>5xBBBQQQrefnum_write_size>B>BBB>BBH>BBL>BBQ>Bq>BB>BH>BL>BQ>BdrefskeyRefsvalRefsrootItems_is_fmt_binarydetect_FORMATSRead a .plist file. 'fp' should be a readable and binary file object. + Return the unpacked root object (which usually is a dictionary). + Read a .plist file from a bytes object. + Return the unpacked root object (which usually is a dictionary). + Write 'value' to a .plist file. 'fp' should be a writable, + binary file object. + Unsupported format: %rReturn a bytes object with the contents for a .plist file. + # Deprecated functionality# base64.decodebytes just calls binascii.a2b_base64;# it seems overkill to use both base64 and binascii.# End of deprecated functionality# XML support# XML 'header'# Regex to find any control chars, except for \t \n and \r# copied from base64.encodebytes(), with added maxlinelength argument# Contents should conform to a subset of ISO 8601# (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units# may be omitted with # a loss of precision)# convert DOS line endings# convert Mac line endings# escape '&'# escape '<'# escape '>'# Reject plist files with entity declarations to avoid XML vulnerabilies in expat.# Regular plist files don't contain those declerations, and Apple's plutil tool does not# accept them either.# this is the root object# element handlers# plist has fixed encoding of utf-8# XXX: is this test needed?# Also check for alternative XML encodings, this is slightly# overkill because the Apple tools (and plistlib) will not# generate files with these encodings.# expat does not support utf-32#(codecs.BOM_UTF32_BE, "utf-32-be"),#(codecs.BOM_UTF32_LE, "utf-32-le"),# Binary Plist# The basic file format:# HEADER# object...# refid->offset...# TRAILER# The referenced source code also mentions URL (0x0c, 0x0d) and# UUID (0x0e), but neither can be generated using the Cocoa libraries.# int# real# date# timestamp 0 of binary plists corresponds to 1/1/2001# (year of Mac OS X 10.0), instead of 1/1/1970.# data# ascii string# unicode string# UID# used by Key-Archiver plist files# array# tokenH == 0xB0 is documented as 'ordset', but is not actually# implemented in the Apple reference code.# tokenH == 0xC0 is documented as 'set', but sets cannot be used in# plists.# dict# Flattened object list:# Mappings from object->objectid# First dict has (type(object), object) as the key,# second dict is used when object is not hashable and# has id(object) as the key.# Create list of all objects in the plist# Size of object references in serialized containers# depends on the number of objects in the plist.# Write file header# Write object list# Write refnum->object offset table# Write trailer# First check if the object is in the object table, not used for# containers to ensure that two subcontainers with the same contents# will be serialized as distinct values.# Add to objectreference map# And finally recurse into containers# Generic bitsb'plistlib.py -- a tool to generate and parse MacOSX .plist files. + +The property list (.plist) file format is a simple XML pickle supporting +basic object types, like dictionaries, lists, numbers and strings. +Usually the top level object is a dictionary. + +To write out a plist file, use the dump(value, file) +function. 'value' is the top level object, 'file' is +a (writable) file object. + +To parse a plist from a file, use the load(file) function, +with a (readable) file object as the only argument. It +returns the top level object (again, usually a dictionary). + +To work with plist data in bytes objects, you can use loads() +and dumps(). + +Values can be strings, integers, floats, booleans, tuples, lists, +dictionaries (but only with string keys), Data, bytes, bytearray, or +datetime.datetime objects. + +Generate Plist example: + + pl = dict( + aString = "Doodah", + aList = ["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, + aDict = dict( + anotherString = "", + aUnicodeValue = "M\xe4ssig, Ma\xdf", + aTrueValue = True, + aFalseValue = False, + ), + someData = b"", + someMoreData = b"" * 10, + aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), + ) + with open(fileName, 'wb') as fp: + dump(pl, fp) + +Parse Plist example: + + with open(fileName, 'rb') as fp: + pl = load(fp) + print(pl["aKey"]) +'u'plistlib.py -- a tool to generate and parse MacOSX .plist files. + +The property list (.plist) file format is a simple XML pickle supporting +basic object types, like dictionaries, lists, numbers and strings. +Usually the top level object is a dictionary. + +To write out a plist file, use the dump(value, file) +function. 'value' is the top level object, 'file' is +a (writable) file object. + +To parse a plist from a file, use the load(file) function, +with a (readable) file object as the only argument. It +returns the top level object (again, usually a dictionary). + +To work with plist data in bytes objects, you can use loads() +and dumps(). + +Values can be strings, integers, floats, booleans, tuples, lists, +dictionaries (but only with string keys), Data, bytes, bytearray, or +datetime.datetime objects. + +Generate Plist example: + + pl = dict( + aString = "Doodah", + aList = ["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, + aDict = dict( + anotherString = "", + aUnicodeValue = "M\xe4ssig, Ma\xdf", + aTrueValue = True, + aFalseValue = False, + ), + someData = b"", + someMoreData = b"" * 10, + aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), + ) + with open(fileName, 'wb') as fp: + dump(pl, fp) + +Parse Plist example: + + with open(fileName, 'rb') as fp: + pl = load(fp) + print(pl["aKey"]) +'b'readPlist'u'readPlist'b'writePlist'u'writePlist'b'readPlistFromBytes'u'readPlistFromBytes'b'writePlistToBytes'u'writePlistToBytes'b'Data'u'Data'b'InvalidFileException'u'InvalidFileException'b'FMT_XML'u'FMT_XML'b'FMT_BINARY'u'FMT_BINARY'b'UID'u'UID'b'PlistFormat'u'PlistFormat'b'FMT_XML FMT_BINARY'u'FMT_XML FMT_BINARY'b' + Read a .plist from a path or file. pathOrFile should either + be a file name, or a readable binary file object. + + This function is deprecated, use load instead. + 'u' + Read a .plist from a path or file. pathOrFile should either + be a file name, or a readable binary file object. + + This function is deprecated, use load instead. + 'b'The readPlist function is deprecated, use load() instead'u'The readPlist function is deprecated, use load() instead'b' + Write 'value' to a .plist file. 'pathOrFile' may either be a + file name or a (writable) file object. + + This function is deprecated, use dump instead. + 'u' + Write 'value' to a .plist file. 'pathOrFile' may either be a + file name or a (writable) file object. + + This function is deprecated, use dump instead. + 'b'The writePlist function is deprecated, use dump() instead'u'The writePlist function is deprecated, use dump() instead'b' + Read a plist data from a bytes object. Return the root object. + + This function is deprecated, use loads instead. + 'u' + Read a plist data from a bytes object. Return the root object. + + This function is deprecated, use loads instead. + 'b'The readPlistFromBytes function is deprecated, use loads() instead'u'The readPlistFromBytes function is deprecated, use loads() instead'b' + Return 'value' as a plist-formatted bytes object. + + This function is deprecated, use dumps instead. + 'u' + Return 'value' as a plist-formatted bytes object. + + This function is deprecated, use dumps instead. + 'b'The writePlistToBytes function is deprecated, use dumps() instead'u'The writePlistToBytes function is deprecated, use dumps() instead'b' + Wrapper for binary data. + + This class is deprecated, use a bytes object instead. + 'u' + Wrapper for binary data. + + This class is deprecated, use a bytes object instead. + 'b'data must be as bytes'u'data must be as bytes'b'data must be an int'u'data must be an int'b'UIDs cannot be >= 2**64'u'UIDs cannot be >= 2**64'b'UIDs must be positive'u'UIDs must be positive'b' + +'b'[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]'u'[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]'b'(?P\d\d\d\d)(?:-(?P\d\d)(?:-(?P\d\d)(?:T(?P\d\d)(?::(?P\d\d)(?::(?P\d\d))?)?)?)?)?Z'u'(?P\d\d\d\d)(?:-(?P\d\d)(?:-(?P\d\d)(?:T(?P\d\d)(?::(?P\d\d)(?::(?P\d\d))?)?)?)?)?Z'b'day'u'day'b'hour'u'hour'b'minute'u'minute'b'second'u'second'b'%04d-%02d-%02dT%02d:%02d:%02dZ'u'%04d-%02d-%02dT%02d:%02d:%02dZ'b'strings can't contains control characters; use bytes instead'u'strings can't contains control characters; use bytes instead'b'XML entity declarations are not supported in plist files'u'XML entity declarations are not supported in plist files'b'begin_'u'begin_'b'unexpected element at line %d'u'unexpected element at line %d'b'missing value for key '%s' at line %d'u'missing value for key '%s' at line %d'b'unexpected key at line %d'u'unexpected key at line %d'b'0X'u'0X'b'<%s>'u'<%s>'b''u''b'<%s>%s'u'<%s>%s'b'<%s/>'u'<%s/>'b''u''b''u''b'true'u'true'b'false'u'false'b'unsupported type: %s'u'unsupported type: %s'b'keys must be strings'u'keys must be strings'b'6xBBQQQ'u'>6xBBQQQ'b' return the size of the next object.'u' return the size of the next object.'b' + read the object by reference. + + May recursively read sub-objects (content of an array/dict/set) + 'u' + read the object by reference. + + May recursively read sub-objects (content of an array/dict/set) + 'b'>f'u'>f'b'utf-16be'u'utf-16be'b'bplist00'b'>5xBBBQQQ'u'>5xBBBQQQ'b'>B'u'>B'b'>BBB'u'>BBB'b'>BBH'u'>BBH'b'>BBL'u'>BBL'b'>BBQ'u'>BBQ'b'>Bq'u'>Bq'b'>BB'u'>BB'b'>BH'u'>BH'b'>BL'u'>BL'b'>BQ'u'>BQ'b''b'>Bd'u'>Bd'b'Read a .plist file. 'fp' should be a readable and binary file object. + Return the unpacked root object (which usually is a dictionary). + 'u'Read a .plist file. 'fp' should be a readable and binary file object. + Return the unpacked root object (which usually is a dictionary). + 'b'detect'u'detect'b'Read a .plist file from a bytes object. + Return the unpacked root object (which usually is a dictionary). + 'u'Read a .plist file from a bytes object. + Return the unpacked root object (which usually is a dictionary). + 'b'Write 'value' to a .plist file. 'fp' should be a writable, + binary file object. + 'u'Write 'value' to a .plist file. 'fp' should be a writable, + binary file object. + 'b'Unsupported format: %r'u'Unsupported format: %r'b'writer'u'writer'b'Return a bytes object with the contents for a .plist file. + 'u'Return a bytes object with the contents for a .plist file. + 'u'plistlib'CLD_CONTINUEDCLD_DUMPEDCLD_EXITEDCLD_TRAPPEDinodeis_fileposix.DirEntryDirEntryEX_CANTCREATEX_CONFIGEX_DATAERREX_IOERREX_NOHOSTEX_NOINPUTEX_NOPERMEX_NOUSEREX_OKEX_OSERREX_OSFILEEX_PROTOCOLEX_SOFTWAREEX_TEMPFAILEX_UNAVAILABLEEX_USAGEF_LOCKF_OKF_TESTF_TLOCKF_ULOCKNGROUPS_MAXO_ACCMODEO_APPENDO_ASYNCO_CLOEXECO_DIRECTORYO_DSYNCO_EXLOCKO_NDELAYO_NOCTTYO_NOFOLLOWO_NONBLOCKO_RDWRO_SHLOCKO_SYNCPOSIX_SPAWN_CLOSEPOSIX_SPAWN_DUP2POSIX_SPAWN_OPENPRIO_PGRPPRIO_PROCESSPRIO_USERP_ALLP_PGIDP_PIDRTLD_LAZYRTLD_NODELETERTLD_NOLOADR_OKSCHED_FIFOSCHED_OTHERSCHED_RRSEEK_DATASEEK_HOLEST_NOSUIDST_RDONLY308915776TMP_MAXWCONTINUEDWCOREDUMPWEXITEDWIFCONTINUEDWNOWAITWSTOPPEDWSTOPSIGWUNTRACEDW_OKX_OK_COPYFILE_DATAu'This module provides access to operating system functionality that is +standardized by the C Standard and the POSIX standard (a thinly +disguised Unix interface). Refer to the library manual and +corresponding Unix manual entries for more information on calls.'_fcopyfilechrootcloserangeconfstr_namesctermiddevice_encodingdup2fchdirfchmodfchownforkptyfpathconffsyncftruncateget_blockingget_inheritablegetegidgeteuidgetgidgetgrouplistgetgroupsgetloadavggetlogingetpgidgetpgrpgetppidgetprioritygetsidinitgroupskillpglchflagslchmodlockflseekmakedevniceopenptypathconf_namesposix_spawnposix_spawnppreadpreadvpwritepwritevreadvsched_get_priority_maxsched_get_priority_minsched_yieldset_inheritablesetegidseteuidsetgidsetgroupssetpgidsetpgrpsetprioritysetregidsetreuidsetsidsetuidu'stat_result: Result from stat, fstat, or lstat. + +This object may be accessed either as a tuple of + (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) +or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on. + +Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev, +or st_flags, they are available as attributes only. + +See os.stat for more information.'st_atime_nsst_birthtimest_blksizest_blocksst_ctime_nsst_flagsst_genst_gidst_mtime_nsst_nlinkst_rdevos.stat_resultstat_resultu'statvfs_result: Result from statvfs or fstatvfs. + +This object may be accessed either as a tuple of + (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax), +or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on. + +See os.statvfs for more information.'f_bavailf_bfreef_blocksf_bsizef_favailf_ffreef_filesf_flagf_frsizef_fsidf_namemaxos.statvfs_resultstatvfs_resultsysconf_namestcgetpgrptcsetpgrpu'A tuple of (columns, lines) for holding terminal window size'os.terminal_sizeterminal_sizeu'times_result: Result from os.times(). + +This object may be accessed either as a tuple of + (user, system, children_user, children_system, elapsed), +or via the attributes user, system, children_user, children_system, +and elapsed. + +See os.times for more information.'children_systemchildren_userelapsedposix.times_resulttimes_resultttynameu'uname_result: Result from os.uname(). + +This object may be accessed either as a tuple of + (sysname, nodename, release, version, machine), +or via the attributes sysname, nodename, release, version, and machine. + +See os.uname for more information.'nodenameposix.uname_resultwait3wait4writevCommon operations on Posix pathnames. + +Instead of importing this module directly, import os and refer to +this module as os.path. The "os.path" name is an alias for this +module on Posix systems; on other systems (e.g. Windows), +os.path provides the same operations in a manner specific to that +platform, and is an alias to another module (e.g. ntpath). + +Some of this can actually be useful on non-Posix systems too, e.g. +for manipulation of the pathname component of URLs. +/bin:/usr/bin/dev/null_get_sepNormalize case of pathname. Has no effect under PosixJoin two or more pathname components, inserting '/' as needed. + If any component is an absolute path, all previous path components + will be discarded. An empty last part will result in a path that + ends with a separator.Split a pathname. Returns tuple "(head, tail)" where "tail" is + everything after the final slash. Either part may be empty.Split a pathname into drive and path. On Posix, drive is always + empty.Test whether a path is a symbolic linkTest whether a path is a mount pointdev1dev2ino1ino2Expand ~ and ~user constructions. If user or $HOME is unknown, + do nothing.pw_dirgetpwnampwent_varprog_varprogbExpand shell variables of form $var and ${var}. Unknown variables + are left unchanged.\$(\w+|\{[^}]*\})dotdotinitial_slashesnew_compsReturn an absolute path.Return the canonical path of the specified filename, eliminating any +symbolic links encountered in the path._joinrealpathnewpath# Strings representing various path-related bits and pieces.# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.# On MS-DOS this may also turn slashes into backslashes; however, other# normalizations (such as optimizing '../' away) are not allowed# (another function should be defined to do that).# Trivial in Posix, harder on the Mac or MS-DOS.# Join pathnames.# Ignore the previous parts if a part is absolute.# Insert a '/' unless the first part is empty or already ends in '/'.# rest). If the path ends in '/', tail will be empty. If there is no# '/' in the path, head will be empty.# Trailing '/'es are stripped from head unless it is the root.# Split a pathname into a drive specification and the rest of the# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.# Return the tail (basename) part of a path, same as split(path)[1].# Return the head (dirname) part of a path, same as split(path)[0].# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)# It doesn't exist -- so not a mount point. :-)# A symlink can never be a mount point# path/.. on a different device as path# path/.. is the same i-node as path# bpo-10496: if the current user identifier doesn't exist in the# password database, return the path unchanged# bpo-10496: if the user name from the path doesn't exist in the# This expands the forms $variable and ${variable} only.# Non-existent variables are left unchanged.# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.# It should be understood that this may change the meaning of the path# if it contains symbolic links!# POSIX allows one or two initial slashes, but treats three or more# as single slash.# Return a canonical path (i.e. the absolute location of a file on the# filesystem).# Join two paths, normalizing and eliminating any symbolic links# encountered in the second path.# current dir# parent dir# Resolve the symbolic link# Already seen this path# use cached value# The symlink is not resolved, so we must have a symlink loop.# Return already resolved part + rest of the path unchanged.# not resolved symlink# resolved symlink# The paths are not normalized before comparing them (this is the# responsibility of the caller). Any trailing separator is stripped from the# returned path.b'Common operations on Posix pathnames. + +Instead of importing this module directly, import os and refer to +this module as os.path. The "os.path" name is an alias for this +module on Posix systems; on other systems (e.g. Windows), +os.path provides the same operations in a manner specific to that +platform, and is an alias to another module (e.g. ntpath). + +Some of this can actually be useful on non-Posix systems too, e.g. +for manipulation of the pathname component of URLs. +'u'Common operations on Posix pathnames. + +Instead of importing this module directly, import os and refer to +this module as os.path. The "os.path" name is an alias for this +module on Posix systems; on other systems (e.g. Windows), +os.path provides the same operations in a manner specific to that +platform, and is an alias to another module (e.g. ntpath). + +Some of this can actually be useful on non-Posix systems too, e.g. +for manipulation of the pathname component of URLs. +'b'/bin:/usr/bin'u'/bin:/usr/bin'b'/dev/null'u'/dev/null'b'Normalize case of pathname. Has no effect under Posix'u'Normalize case of pathname. Has no effect under Posix'b'Join two or more pathname components, inserting '/' as needed. + If any component is an absolute path, all previous path components + will be discarded. An empty last part will result in a path that + ends with a separator.'u'Join two or more pathname components, inserting '/' as needed. + If any component is an absolute path, all previous path components + will be discarded. An empty last part will result in a path that + ends with a separator.'b'Split a pathname. Returns tuple "(head, tail)" where "tail" is + everything after the final slash. Either part may be empty.'u'Split a pathname. Returns tuple "(head, tail)" where "tail" is + everything after the final slash. Either part may be empty.'b'Split a pathname into drive and path. On Posix, drive is always + empty.'u'Split a pathname into drive and path. On Posix, drive is always + empty.'b'Test whether a path is a symbolic link'u'Test whether a path is a symbolic link'b'Test whether a path is a mount point'u'Test whether a path is a mount point'b'Expand ~ and ~user constructions. If user or $HOME is unknown, + do nothing.'u'Expand ~ and ~user constructions. If user or $HOME is unknown, + do nothing.'b'Expand shell variables of form $var and ${var}. Unknown variables + are left unchanged.'u'Expand shell variables of form $var and ${var}. Unknown variables + are left unchanged.'b'\$(\w+|\{[^}]*\})'u'\$(\w+|\{[^}]*\})'b'Return an absolute path.'u'Return an absolute path.'b'Return the canonical path of the specified filename, eliminating any +symbolic links encountered in the path.'u'Return the canonical path of the specified filename, eliminating any +symbolic links encountered in the path.'u'posixpath'Support to pretty-print lists, tuples, & dictionaries recursively. + +Very simple, but useful, especially in debugging data structures. + +Classes +------- + +PrettyPrinter() + Handle pretty-printing operations onto a stream using a configured + set of formatting parameters. + +Functions +--------- + +pformat() + Format a Python object into a pretty-printed representation. + +pprint() + Pretty-print a Python object to a stream [default is sys.stdout]. + +saferepr() + Generate a 'standard' repr()-like value, but protect against recursive + data structures. + +_types_StringIOisreadableisrecursivesafereprPrettyPrintercompactsort_dictsPretty-print a Python object to a stream [default is sys.stdout].printerFormat a Python object into a pretty-printed representation.Pretty-print a Python objectVersion of repr() which can handle recursive data structures._safe_reprDetermine if saferepr(object) is readable by eval().Determine if object requires a recursive representation._safe_keyHelper function for key functions when sorting unorderable objects. + + The wrapped-object will fallback to a Py2.x style comparison for + unorderable types (sorting first comparing the type name and then by + the obj ids). Does not work recursively, so dict.items() must have + _safe_key applied to both the key and the value. + + _safe_tupleHelper function for comparing 2-tuplesHandle pretty printing operations onto a stream using a set of + configured parameters. + + indent + Number of spaces to indent for each level of nesting. + + width + Attempted maximum number of columns in the output. + + depth + The maximum depth to print out nested structures. + + stream + The desired output stream. If omitted (or false), the standard + output stream available at construction will be used. + + compact + If true, several items will be combined in one line. + + sort_dicts + If true, dict keys are sorted. + + indent must be >= 0depth must be > 0width must be != 0_depth_indent_per_level_compact_sort_dictsallowanceobjid_recursion_recursivemax_width_dispatch_pprint_dict_format_dict_items_pprint_ordered_dict_pprint_list_format_items_pprint_tuple,)endchar_pprint_set({})_pprint_strmax_width1\S*\s*max_width2_pprint_bytesparens_wrap_bytes_repr_pprint_bytearraybytearray(_pprint_mappingproxymappingproxy(, +delimnllast_indexentnext_entmaxlevelsFormat object for a specific context, returning a string + and flags indicating whether the representation is 'readable' + and whether the object represents a recursive construct. + _pprint_default_dict%s(%s, +%s_pprint_counter_pprint_chain_map_pprint_deque])rml], +%smaxlen=%s)_pprint_user_dict_pprint_user_list_pprint_user_string_builtin_scalars{...}kreprkreadablekrecurvreprvreadablevrecur[](%s,)oreproreadableorecur_perfcheck100000perf_countert3_safe_repr:pformat:# Author: Fred L. Drake, Jr.# fdrake@acm.org# This is a simple little module I wrote to make life easier. I didn't# see anything quite like it in the library, though I may have overlooked# something. I wrote this when I was trying to read some heavily nested# tuples with fairly non-descriptive content. This is modeled very much# after Lisp/Scheme - style pretty-printing of lists. If you find it# useful, thank small children who sleep at night.# A list of alternating (non-space, space) strings# drop empty last part# Return triple (repr_string, isreadable, isrecursive).b'Support to pretty-print lists, tuples, & dictionaries recursively. + +Very simple, but useful, especially in debugging data structures. + +Classes +------- + +PrettyPrinter() + Handle pretty-printing operations onto a stream using a configured + set of formatting parameters. + +Functions +--------- + +pformat() + Format a Python object into a pretty-printed representation. + +pprint() + Pretty-print a Python object to a stream [default is sys.stdout]. + +saferepr() + Generate a 'standard' repr()-like value, but protect against recursive + data structures. + +'u'Support to pretty-print lists, tuples, & dictionaries recursively. + +Very simple, but useful, especially in debugging data structures. + +Classes +------- + +PrettyPrinter() + Handle pretty-printing operations onto a stream using a configured + set of formatting parameters. + +Functions +--------- + +pformat() + Format a Python object into a pretty-printed representation. + +pprint() + Pretty-print a Python object to a stream [default is sys.stdout]. + +saferepr() + Generate a 'standard' repr()-like value, but protect against recursive + data structures. + +'b'pprint'u'pprint'b'pformat'u'pformat'b'isreadable'u'isreadable'b'isrecursive'u'isrecursive'b'saferepr'u'saferepr'b'PrettyPrinter'u'PrettyPrinter'b'Pretty-print a Python object to a stream [default is sys.stdout].'u'Pretty-print a Python object to a stream [default is sys.stdout].'b'Format a Python object into a pretty-printed representation.'u'Format a Python object into a pretty-printed representation.'b'Pretty-print a Python object'u'Pretty-print a Python object'b'Version of repr() which can handle recursive data structures.'u'Version of repr() which can handle recursive data structures.'b'Determine if saferepr(object) is readable by eval().'u'Determine if saferepr(object) is readable by eval().'b'Determine if object requires a recursive representation.'u'Determine if object requires a recursive representation.'b'Helper function for key functions when sorting unorderable objects. + + The wrapped-object will fallback to a Py2.x style comparison for + unorderable types (sorting first comparing the type name and then by + the obj ids). Does not work recursively, so dict.items() must have + _safe_key applied to both the key and the value. + + 'u'Helper function for key functions when sorting unorderable objects. + + The wrapped-object will fallback to a Py2.x style comparison for + unorderable types (sorting first comparing the type name and then by + the obj ids). Does not work recursively, so dict.items() must have + _safe_key applied to both the key and the value. + + 'b'Helper function for comparing 2-tuples'u'Helper function for comparing 2-tuples'b'Handle pretty printing operations onto a stream using a set of + configured parameters. + + indent + Number of spaces to indent for each level of nesting. + + width + Attempted maximum number of columns in the output. + + depth + The maximum depth to print out nested structures. + + stream + The desired output stream. If omitted (or false), the standard + output stream available at construction will be used. + + compact + If true, several items will be combined in one line. + + sort_dicts + If true, dict keys are sorted. + + 'u'Handle pretty printing operations onto a stream using a set of + configured parameters. + + indent + Number of spaces to indent for each level of nesting. + + width + Attempted maximum number of columns in the output. + + depth + The maximum depth to print out nested structures. + + stream + The desired output stream. If omitted (or false), the standard + output stream available at construction will be used. + + compact + If true, several items will be combined in one line. + + sort_dicts + If true, dict keys are sorted. + + 'b'indent must be >= 0'u'indent must be >= 0'b'depth must be > 0'u'depth must be > 0'b'width must be != 0'u'width must be != 0'b',)'u',)'b'({'u'({'b'})'u'})'b'\S*\s*'u'\S*\s*'b'bytearray('u'bytearray('b'mappingproxy('u'mappingproxy('b', +'u', +'b'Format object for a specific context, returning a string + and flags indicating whether the representation is 'readable' + and whether the object represents a recursive construct. + 'u'Format object for a specific context, returning a string + and flags indicating whether the representation is 'readable' + and whether the object represents a recursive construct. + 'b'%s(%s, +%s'u'%s(%s, +%s'b'])'u'])'b'], +%smaxlen=%s)'u'], +%smaxlen=%s)'b'{...}'u'{...}'b'[]'u'[]'b'(%s,)'u'(%s,)'b''u''b'_safe_repr:'u'_safe_repr:'b'pformat:'u'pformat:'Event loop using a proactor and related classes. + +A proactor is a "notify-on-completion" multiplexer. Currently a +proactor is only implemented on Windows with IOCP. +BaseProactorEventLoop_set_socket_extrasocknamegetsockname() failed on %rpeername_ProactorBasePipeTransportBaseTransportBase class for pipe and socket transports._set_extra_sock_server_read_fut_write_fut_pending_write_conn_lost_closing_eof_writtenfd=read=write=write_bufsize=EOF writtenFatal error on pipe transport%r: %s_force_close_empty_waiterget_write_buffer_size_ProactorReadPipeTransportReadTransportTransport for read pipes._pending_data_paused_loop_reading%r pauses reading_data_received%r resumes reading_eof_received%r received EOFkeep_openFatal error: protocol.eof_received() call failed.BufferedProtocol_feed_data_to_buffered_protoFatal error: protocol.buffer_updated() call failed.'Fatal error: protocol.buffer_updated() ''call failed.'_proactorFatal read error on pipe transportRead error on pipe transport while closing_ProactorBaseWritePipeTransportWriteTransportTransport for write pipes.data argument must be a bytes-like object, not "data argument must be a bytes-like object, "write_eof() already calledunable to write; sendfile is in progresssocket.send() raised exception._loop_writing_maybe_pause_protocol_maybe_resume_protocolFatal write error on pipe transportcan_write_eof_make_empty_waiterEmpty waiter is already set_reset_empty_waiter_ProactorWritePipeTransport_pipe_closed_ProactorDatagramTransportmax_sizedata argument must be bytes-like object (%r)Invalid address: must be None or socket.sendto() raised exception.error_receivedFatal write error on datagram transportdatagram_received_ProactorDuplexPipeTransportTransport for duplex pipes._ProactorSocketTransportTransport for connected sockets.proactorUsing proactor: %s_self_reading_future_accept_futuresset_loop_make_self_pipemain_thread_csock_make_duplex_pipe_transport_stop_accept_futures_close_self_pipenot a regular filefsize0xffff_ffffend_pos_ssock_loop_self_readingError on reading from the event loop self pipecsockFail to write a null byte into the self-pipe socket"Fail to write a null byte into the ""self-pipe socket"%r got a new connection from %r: %rAccept failed on a socketAccept failed on socket %r# UDP sockets may not have a peer name# None or bytearray.# Set when close() called.# only wake up the waiter when connection_made() has been called# XXX If there is a pending overlapped read on the other# end then it may fail with ERROR_NETNAME_DELETED if we# just close our end. First calling shutdown() seems to# cure it, but maybe using DisconnectEx() would be better.# bpo-33694: Don't cancel self._read_fut because cancelling an# overlapped WSASend() loss silently data with the current proactor# implementation.# If CancelIoEx() fails with ERROR_NOT_FOUND, it means that WSASend()# completed (even if HasOverlappedIoCompleted() returns 0), but# Overlapped.cancel() currently silently ignores the ERROR_NOT_FOUND# error. Once the overlapped is ignored, the IOCP loop will ignores the# completion I/O event and so not read the result of the overlapped# WSARecv().# Call the protocol methode after calling _loop_reading(),# since the protocol can decide to pause reading again.# Don't call any protocol method while reading is paused.# The protocol will be called on resume_reading().# deliver data later in "finally" clause# the future will be replaced by next proactor.recv call# since close() has been called we ignore any read data# we got end-of-file so no need to reschedule a new read# bpo-33694: buffer_updated() has currently no fast path because of# a data loss issue caused by overlapped WSASend() cancellation.# reschedule a new read# Observable states:# 1. IDLE: _write_fut and _buffer both None# 2. WRITING: _write_fut set; _buffer None# 3. BACKED UP: _write_fut set; _buffer a bytearray# We always copy the data, so the caller can't modify it# while we're still waiting for the I/O to happen.# IDLE -> WRITING# Pass a copy, except if it's already immutable.# WRITING -> BACKED UP# Make a mutable copy which we can extend.# BACKED UP# Append to buffer (also copies).# XXX most likely self._force_close() has been called, and# it has set self._write_fut to None.# Now that we've reduced the buffer size, tell the# protocol to resume writing if it was paused. Note that# we do this last since the callback is called immediately# and it may add more data to the buffer (even causing the# protocol to be paused again).# the transport has been closed# We don't need to call _protocol.connection_made() since our base# constructor does it for us.# The base constructor sets _buffer = None, so we set it here# Ensure that what we buffer is immutable.# No current write operations are active, kick one off# else: A write operation is already kicked off# We are in a _loop_writing() done callback, get the result# The connection has been closed# convenient alias# socket file descriptor => Future# wakeup fd can only be installed to a file descriptor from the main thread# We want connection_lost() to be called when other end closes# Call these methods before closing the event loop (before calling# BaseEventLoop.close), because they can schedule callbacks with# call_soon(), which is forbidden when the event loop is closed.# Close the event loop# empty file# A self-socket, really. :-)# may raise# When we scheduled this Future, we assigned it to# _self_reading_future. If it's not there now, something has# tried to cancel the loop while this callback was still in the# queue (see windows_events.ProactorEventLoop.run_forever). In# that case stop here instead of continuing to schedule a new# iteration.# _close_self_pipe() has been called, stop waiting for data# This may be called from a different thread, possibly after# _close_self_pipe() has been called or even while it is# running. Guard for self._csock being None or closed. When# a socket is closed, send() raises OSError (with errno set to# EBADF, but let's not rely on the exact error code).# Events are processed in the IocpProactor._poll() methodb'Event loop using a proactor and related classes. + +A proactor is a "notify-on-completion" multiplexer. Currently a +proactor is only implemented on Windows with IOCP. +'u'Event loop using a proactor and related classes. + +A proactor is a "notify-on-completion" multiplexer. Currently a +proactor is only implemented on Windows with IOCP. +'b'BaseProactorEventLoop'u'BaseProactorEventLoop'b'sockname'u'sockname'b'getsockname() failed on %r'u'getsockname() failed on %r'b'peername'u'peername'b'Base class for pipe and socket transports.'u'Base class for pipe and socket transports.'b'fd='u'fd='b'read='u'read='b'write='u'write='b'write_bufsize='u'write_bufsize='b'EOF written'u'EOF written'b'pipe'u'pipe'b'Fatal error on pipe transport'u'Fatal error on pipe transport'b'%r: %s'u'%r: %s'b'Transport for read pipes.'u'Transport for read pipes.'b'%r pauses reading'u'%r pauses reading'b'%r resumes reading'u'%r resumes reading'b'%r received EOF'u'%r received EOF'b'Fatal error: protocol.eof_received() call failed.'u'Fatal error: protocol.eof_received() call failed.'b'Fatal error: protocol.buffer_updated() call failed.'u'Fatal error: protocol.buffer_updated() call failed.'b'Fatal read error on pipe transport'u'Fatal read error on pipe transport'b'Read error on pipe transport while closing'u'Read error on pipe transport while closing'b'Transport for write pipes.'u'Transport for write pipes.'b'data argument must be a bytes-like object, not 'u'data argument must be a bytes-like object, not 'b'write_eof() already called'u'write_eof() already called'b'unable to write; sendfile is in progress'u'unable to write; sendfile is in progress'b'socket.send() raised exception.'u'socket.send() raised exception.'b'Fatal write error on pipe transport'u'Fatal write error on pipe transport'b'Empty waiter is already set'u'Empty waiter is already set'b'data argument must be bytes-like object (%r)'u'data argument must be bytes-like object (%r)'b'Invalid address: must be None or 'u'Invalid address: must be None or 'b'socket.sendto() raised exception.'u'socket.sendto() raised exception.'b'Fatal write error on datagram transport'u'Fatal write error on datagram transport'b'Transport for duplex pipes.'u'Transport for duplex pipes.'b'Transport for connected sockets.'u'Transport for connected sockets.'b'Using proactor: %s'u'Using proactor: %s'b'not a regular file'u'not a regular file'b'Error on reading from the event loop self pipe'u'Error on reading from the event loop self pipe'b'loop'u'loop'b'Fail to write a null byte into the self-pipe socket'u'Fail to write a null byte into the self-pipe socket'b'%r got a new connection from %r: %r'u'%r got a new connection from %r: %r'b'Accept failed on a socket'u'Accept failed on a socket'b'Accept failed on socket %r'u'Accept failed on socket %r'u'asyncio.proactor_events'u'proactor_events'Implements ProcessPoolExecutor. + +The following diagram and text describe the data-flow through the system: + +|======================= In-process =====================|== Out-of-process ==| + ++----------+ +----------+ +--------+ +-----------+ +---------+ +| | => | Work Ids | | | | Call Q | | Process | +| | +----------+ | | +-----------+ | Pool | +| | | ... | | | | ... | +---------+ +| | | 6 | => | | => | 5, call() | => | | +| | | 7 | | | | ... | | | +| Process | | ... | | Local | +-----------+ | Process | +| Pool | +----------+ | Worker | | #1..n | +| Executor | | Thread | | | +| | +----------- + | | +-----------+ | | +| | <=> | Work Items | <=> | | <= | Result Q | <= | | +| | +------------+ | | +-----------+ | | +| | | 6: call() | | | | ... | | | +| | | future | | | | 4, result | | | +| | | ... | | | | 3, except | | | ++----------+ +------------+ +--------+ +-----------+ +---------+ + +Executor.submit() called: +- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict +- adds the id of the _WorkItem to the "Work Ids" queue + +Local worker thread: +- reads work ids from the "Work Ids" queue and looks up the corresponding + WorkItem from the "Work Items" dict: if the work item has been cancelled then + it is simply removed from the dict, otherwise it is repackaged as a + _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q" + until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because + calls placed in the "Call Q" can no longer be cancelled with Future.cancel(). +- reads _ResultItems from "Result Q", updates the future stored in the + "Work Items" dict and deletes the dict entry + +Process #1..n: +- reads _CallItems from "Call Q", executes the calls, and puts the resulting + _ResultItems in "Result Q" +_baseFullmultiprocessing.queues_threads_wakeups_global_shutdown_ThreadWakeup_reader_writer_python_exitthread_wakeupEXTRA_QUEUED_CALLS_MAX_WINDOWS_WORKERS_RemoteTraceback_ExceptionWithTraceback +""" +%s"""_rebuild_exc_WorkItem_ResultItemwork_id_CallItem_SafeQueueSafe Queue set exception to the future object linked to a jobpending_work_items_on_queue_feeder_error +""" +{}"""work_item_get_chunks Iterates over zip()ed iterables in chunks. _process_chunk Processes a chunk of an iterable passed to map. + + Runs the function passed to map() on a chunk of the + iterable passed to map. + + This function is run in a separate process. + + _sendback_resultresult_queueSafely send back the given result or exception_process_workercall_queueEvaluates calls from call_queue and places the results in result_queue. + + This worker is run in a separate process. + + Args: + call_queue: A ctx.Queue of _CallItems that will be read and + evaluated by the worker. + result_queue: A ctx.Queue of _ResultItems that will written + to by the worker. + initializer: A callable initializer, or None + initargs: A tuple of args for the initializer + Exception in initializer:call_item_add_call_item_to_queuework_idsFills call_queue with _WorkItems from pending_work_items. + + This function never blocks. + + Args: + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids + are consumed and the corresponding _WorkItems from + pending_work_items are transformed into _CallItems and put in + call_queue. + call_queue: A multiprocessing.Queue that will be filled with _CallItems + derived from _WorkItems. + _queue_management_workerexecutor_referencework_ids_queueManages the communication between this process and the worker processes. + + This function is run in a local thread. + + Args: + executor_reference: A weakref.ref to the ProcessPoolExecutor that owns + this thread. Used to determine if the ProcessPoolExecutor has been + garbage collected and that this function can exit. + process: A list of the ctx.Process instances used as + workers. + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). + call_queue: A ctx.Queue that will be filled with _CallItems + derived from _WorkItems for processing by the process workers. + result_queue: A ctx.SimpleQueue of _ResultItems generated by the + process workers. + thread_wakeup: A _ThreadWakeup to allow waking up the + queue_manager_thread from the main Thread and avoid deadlocks + caused by permanently locked queues. + shutting_down_shutdown_threadshutdown_workern_children_aliven_children_to_stopn_sentinels_sentresult_readerwakeup_readerreadersworker_sentinelscauseis_brokenresult_itemA child process terminated abruptly, the process pool is not usable anymore'A child process terminated ''abruptly, the process pool is not ''usable anymore'_brokenBrokenProcessPoolA process in the process pool was terminated abruptly while the future was running or pending."A process in the process pool was ""terminated abruptly while the future was ""running or pending."bpe +''' +_system_limits_checked_system_limited_check_system_limitsSC_SEM_NSEMS_MAXnsems_maxsystem provides too few semaphores (%d available, 256 necessary)"system provides too few semaphores (%d"" available, 256 necessary)"_chain_from_iterable_of_lists + Specialized implementation of itertools.chain.from_iterable. + Each item in *iterable* should be a list. This function is + careful not to keep references to yielded objects. + + Raised when a process in a ProcessPoolExecutor terminated abruptly + while a future was in the running state. + max_workersmp_contextInitializes a new ProcessPoolExecutor instance. + + Args: + max_workers: The maximum number of processes that can be used to + execute the given calls. If None or not given then as many + worker processes will be created as the machine has processors. + mp_context: A multiprocessing context to launch the workers. This + object should provide SimpleQueue, Queue and Process. + initializer: A callable used to initialize worker processes. + initargs: A tuple of arguments to pass to the initializer. + _max_workersmax_workers must be greater than 0max_workers must be <= _mp_contextinitializer must be a callable_initializer_initargs_queue_management_thread_processes_shutdown_lock_queue_count_pending_work_itemsqueue_size_call_queue_ignore_epipe_result_queue_work_ids_queue_management_thread_wakeup_start_queue_management_threadweakref_cbExecutor collected: triggering callback for QueueManager wakeup'Executor collected: triggering callback for'' QueueManager wakeup'_adjust_process_countQueueManagerThreaddescriptor 'submit' of 'ProcessPoolExecutor' object needs an argument"descriptor 'submit' of 'ProcessPoolExecutor' object "cannot schedule new futures after shutdowncannot schedule new futures after interpreter shutdown'cannot schedule new futures after ''interpreter shutdown'Returns an iterator equivalent to map(fn, iter). + + Args: + fn: A callable that will take as many arguments as there are + passed iterables. + timeout: The maximum number of seconds to wait. If None, then there + is no limit on the wait time. + chunksize: If greater than one, the iterables will be chopped into + chunks of size chunksize and submitted to the process pool. + If set to one, the items in the list will be sent one at a time. + + Returns: + An iterator equivalent to: map(func, *iterables) but the calls may + be evaluated out-of-order. + + Raises: + TimeoutError: If the entire result iterator could not be generated + before the given timeout. + Exception: If fn(*args) raises for any values. + chunksize must be >= 1.# Workers are created as daemon threads and processes. This is done to allow the# interpreter to exit when there are still idle processes in a# ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,# allowing workers to die with the interpreter has two undesirable properties:# - The workers would still be running during interpreter shutdown,# meaning that they would fail in unpredictable ways.# - The workers could be killed while evaluating a work item, which could# be bad if the callable being evaluated has external side-effects e.g.# writing to a file.# To work around this problem, an exit handler is installed which tells the# workers to exit when their work queues are empty and then waits until the# threads/processes finish.# Controls how many more calls than processes will be queued in the call queue.# A smaller number will mean that processes spend more time idle waiting for# work while a larger number will make Future.cancel() succeed less frequently# (Futures in the call queue cannot be cancelled).# On Windows, WaitForMultipleObjects is used to wait for processes to finish.# It can wait on, at most, 63 objects. There is an overhead of two objects:# - the result queue reader# - the thread wakeup reader# Hack to embed stringification of remote traceback in local traceback# work_item can be None if another process terminated. In this case,# the queue_manager_thread fails all work_items with BrokenProcessPool# The parent will notice that the process stopped and# mark the pool broken# Wake up queue management thread# Liberate the resource as soon as possible, to avoid holding onto# open files or shared memory that is not needed anymore# This is an upper bound on the number of children alive.# Send the right number of sentinels, to make sure all children are# properly terminated.# Release the queue's resources as soon as possible.# If .join() is not called on the created processes then# some ctx.Queue methods may deadlock on Mac OS X.# Wait for a result to be ready in the result_queue while checking# that all worker processes are still running, or for a wake up# signal send. The wake up signals come either from new tasks being# submitted, from the executor being shutdown/gc-ed, or from the# shutdown of the python interpreter.# Mark the process pool broken so that submits fail right now.# All futures in flight must be marked failed# Delete references to object. See issue16284# Terminate remaining workers forcibly: the queues or their# locks may be in a dirty state and block forever.# Clean shutdown of a worker using its PID# (avoids marking the executor broken)# work_item can be None if another process terminated (see above)# Delete reference to result_item# Check whether we should start shutting down.# No more work items can be added if:# - The interpreter is shutting down OR# - The executor that owns this worker has been collected OR# - The executor that owns this worker has been shutdown.# Flag the executor as shutting down as early as possible if it# is not gc-ed yet.# Since no new work items can be added, it is safe to shutdown# this thread if there are no pending work items.# This is not a problem: we will eventually be woken up (in# result_queue.get()) and be able to send a sentinel again.# sysconf not available or setting not available# indetermined limit, assume that limit is determined# by available memory only# minimum number of semaphores available# according to POSIX# Management thread# Map of pids to processes# Shutdown is a two-step process.# Create communication channels for the executor# Make the call queue slightly larger than the number of processes to# prevent the worker processes from idling. But don't make it too big# because futures in the call queue cannot be cancelled.# Killed worker processes can produce spurious "broken pipe"# tracebacks in the queue's own worker thread. But we detect killed# processes anyway, so silence the tracebacks.# _ThreadWakeup is a communication channel used to interrupt the wait# of the main loop of queue_manager_thread from another thread (e.g.# when calling executor.submit or executor.shutdown). We do not use the# _result_queue to send the wakeup signal to the queue_manager_thread# as it could result in a deadlock if a worker process dies with the# _result_queue write lock still acquired.# When the executor gets garbarge collected, the weakref callback# will wake up the queue management thread so that it can terminate# if there is no pending work item.# Start the processes so that their sentinels are known.# To reduce the risk of opening too many files, remove references to# objects that use file descriptors.b'Implements ProcessPoolExecutor. + +The following diagram and text describe the data-flow through the system: + +|======================= In-process =====================|== Out-of-process ==| + ++----------+ +----------+ +--------+ +-----------+ +---------+ +| | => | Work Ids | | | | Call Q | | Process | +| | +----------+ | | +-----------+ | Pool | +| | | ... | | | | ... | +---------+ +| | | 6 | => | | => | 5, call() | => | | +| | | 7 | | | | ... | | | +| Process | | ... | | Local | +-----------+ | Process | +| Pool | +----------+ | Worker | | #1..n | +| Executor | | Thread | | | +| | +----------- + | | +-----------+ | | +| | <=> | Work Items | <=> | | <= | Result Q | <= | | +| | +------------+ | | +-----------+ | | +| | | 6: call() | | | | ... | | | +| | | future | | | | 4, result | | | +| | | ... | | | | 3, except | | | ++----------+ +------------+ +--------+ +-----------+ +---------+ + +Executor.submit() called: +- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict +- adds the id of the _WorkItem to the "Work Ids" queue + +Local worker thread: +- reads work ids from the "Work Ids" queue and looks up the corresponding + WorkItem from the "Work Items" dict: if the work item has been cancelled then + it is simply removed from the dict, otherwise it is repackaged as a + _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q" + until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because + calls placed in the "Call Q" can no longer be cancelled with Future.cancel(). +- reads _ResultItems from "Result Q", updates the future stored in the + "Work Items" dict and deletes the dict entry + +Process #1..n: +- reads _CallItems from "Call Q", executes the calls, and puts the resulting + _ResultItems in "Result Q" +'u'Implements ProcessPoolExecutor. + +The following diagram and text describe the data-flow through the system: + +|======================= In-process =====================|== Out-of-process ==| + ++----------+ +----------+ +--------+ +-----------+ +---------+ +| | => | Work Ids | | | | Call Q | | Process | +| | +----------+ | | +-----------+ | Pool | +| | | ... | | | | ... | +---------+ +| | | 6 | => | | => | 5, call() | => | | +| | | 7 | | | | ... | | | +| Process | | ... | | Local | +-----------+ | Process | +| Pool | +----------+ | Worker | | #1..n | +| Executor | | Thread | | | +| | +----------- + | | +-----------+ | | +| | <=> | Work Items | <=> | | <= | Result Q | <= | | +| | +------------+ | | +-----------+ | | +| | | 6: call() | | | | ... | | | +| | | future | | | | 4, result | | | +| | | ... | | | | 3, except | | | ++----------+ +------------+ +--------+ +-----------+ +---------+ + +Executor.submit() called: +- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict +- adds the id of the _WorkItem to the "Work Ids" queue + +Local worker thread: +- reads work ids from the "Work Ids" queue and looks up the corresponding + WorkItem from the "Work Items" dict: if the work item has been cancelled then + it is simply removed from the dict, otherwise it is repackaged as a + _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q" + until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because + calls placed in the "Call Q" can no longer be cancelled with Future.cancel(). +- reads _ResultItems from "Result Q", updates the future stored in the + "Work Items" dict and deletes the dict entry + +Process #1..n: +- reads _CallItems from "Call Q", executes the calls, and puts the resulting + _ResultItems in "Result Q" +'b' +""" +%s"""'u' +""" +%s"""'b'Safe Queue set exception to the future object linked to a job'u'Safe Queue set exception to the future object linked to a job'b' +""" +{}"""'u' +""" +{}"""'b' Iterates over zip()ed iterables in chunks. 'u' Iterates over zip()ed iterables in chunks. 'b' Processes a chunk of an iterable passed to map. + + Runs the function passed to map() on a chunk of the + iterable passed to map. + + This function is run in a separate process. + + 'u' Processes a chunk of an iterable passed to map. + + Runs the function passed to map() on a chunk of the + iterable passed to map. + + This function is run in a separate process. + + 'b'Safely send back the given result or exception'u'Safely send back the given result or exception'b'Evaluates calls from call_queue and places the results in result_queue. + + This worker is run in a separate process. + + Args: + call_queue: A ctx.Queue of _CallItems that will be read and + evaluated by the worker. + result_queue: A ctx.Queue of _ResultItems that will written + to by the worker. + initializer: A callable initializer, or None + initargs: A tuple of args for the initializer + 'u'Evaluates calls from call_queue and places the results in result_queue. + + This worker is run in a separate process. + + Args: + call_queue: A ctx.Queue of _CallItems that will be read and + evaluated by the worker. + result_queue: A ctx.Queue of _ResultItems that will written + to by the worker. + initializer: A callable initializer, or None + initargs: A tuple of args for the initializer + 'b'Exception in initializer:'u'Exception in initializer:'b'Fills call_queue with _WorkItems from pending_work_items. + + This function never blocks. + + Args: + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids + are consumed and the corresponding _WorkItems from + pending_work_items are transformed into _CallItems and put in + call_queue. + call_queue: A multiprocessing.Queue that will be filled with _CallItems + derived from _WorkItems. + 'u'Fills call_queue with _WorkItems from pending_work_items. + + This function never blocks. + + Args: + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids + are consumed and the corresponding _WorkItems from + pending_work_items are transformed into _CallItems and put in + call_queue. + call_queue: A multiprocessing.Queue that will be filled with _CallItems + derived from _WorkItems. + 'b'Manages the communication between this process and the worker processes. + + This function is run in a local thread. + + Args: + executor_reference: A weakref.ref to the ProcessPoolExecutor that owns + this thread. Used to determine if the ProcessPoolExecutor has been + garbage collected and that this function can exit. + process: A list of the ctx.Process instances used as + workers. + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). + call_queue: A ctx.Queue that will be filled with _CallItems + derived from _WorkItems for processing by the process workers. + result_queue: A ctx.SimpleQueue of _ResultItems generated by the + process workers. + thread_wakeup: A _ThreadWakeup to allow waking up the + queue_manager_thread from the main Thread and avoid deadlocks + caused by permanently locked queues. + 'u'Manages the communication between this process and the worker processes. + + This function is run in a local thread. + + Args: + executor_reference: A weakref.ref to the ProcessPoolExecutor that owns + this thread. Used to determine if the ProcessPoolExecutor has been + garbage collected and that this function can exit. + process: A list of the ctx.Process instances used as + workers. + pending_work_items: A dict mapping work ids to _WorkItems e.g. + {5: <_WorkItem...>, 6: <_WorkItem...>, ...} + work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). + call_queue: A ctx.Queue that will be filled with _CallItems + derived from _WorkItems for processing by the process workers. + result_queue: A ctx.SimpleQueue of _ResultItems generated by the + process workers. + thread_wakeup: A _ThreadWakeup to allow waking up the + queue_manager_thread from the main Thread and avoid deadlocks + caused by permanently locked queues. + 'b'A child process terminated abruptly, the process pool is not usable anymore'u'A child process terminated abruptly, the process pool is not usable anymore'b'A process in the process pool was terminated abruptly while the future was running or pending.'u'A process in the process pool was terminated abruptly while the future was running or pending.'b' +''' +'u' +''' +'b'SC_SEM_NSEMS_MAX'u'SC_SEM_NSEMS_MAX'b'system provides too few semaphores (%d available, 256 necessary)'u'system provides too few semaphores (%d available, 256 necessary)'b' + Specialized implementation of itertools.chain.from_iterable. + Each item in *iterable* should be a list. This function is + careful not to keep references to yielded objects. + 'u' + Specialized implementation of itertools.chain.from_iterable. + Each item in *iterable* should be a list. This function is + careful not to keep references to yielded objects. + 'b' + Raised when a process in a ProcessPoolExecutor terminated abruptly + while a future was in the running state. + 'u' + Raised when a process in a ProcessPoolExecutor terminated abruptly + while a future was in the running state. + 'b'Initializes a new ProcessPoolExecutor instance. + + Args: + max_workers: The maximum number of processes that can be used to + execute the given calls. If None or not given then as many + worker processes will be created as the machine has processors. + mp_context: A multiprocessing context to launch the workers. This + object should provide SimpleQueue, Queue and Process. + initializer: A callable used to initialize worker processes. + initargs: A tuple of arguments to pass to the initializer. + 'u'Initializes a new ProcessPoolExecutor instance. + + Args: + max_workers: The maximum number of processes that can be used to + execute the given calls. If None or not given then as many + worker processes will be created as the machine has processors. + mp_context: A multiprocessing context to launch the workers. This + object should provide SimpleQueue, Queue and Process. + initializer: A callable used to initialize worker processes. + initargs: A tuple of arguments to pass to the initializer. + 'b'max_workers must be greater than 0'u'max_workers must be greater than 0'b'max_workers must be <= 'u'max_workers must be <= 'b'initializer must be a callable'u'initializer must be a callable'b'Executor collected: triggering callback for QueueManager wakeup'u'Executor collected: triggering callback for QueueManager wakeup'b'QueueManagerThread'u'QueueManagerThread'b'descriptor 'submit' of 'ProcessPoolExecutor' object needs an argument'u'descriptor 'submit' of 'ProcessPoolExecutor' object needs an argument'b'cannot schedule new futures after shutdown'u'cannot schedule new futures after shutdown'b'cannot schedule new futures after interpreter shutdown'u'cannot schedule new futures after interpreter shutdown'b'Returns an iterator equivalent to map(fn, iter). + + Args: + fn: A callable that will take as many arguments as there are + passed iterables. + timeout: The maximum number of seconds to wait. If None, then there + is no limit on the wait time. + chunksize: If greater than one, the iterables will be chopped into + chunks of size chunksize and submitted to the process pool. + If set to one, the items in the list will be sent one at a time. + + Returns: + An iterator equivalent to: map(func, *iterables) but the calls may + be evaluated out-of-order. + + Raises: + TimeoutError: If the entire result iterator could not be generated + before the given timeout. + Exception: If fn(*args) raises for any values. + 'u'Returns an iterator equivalent to map(fn, iter). + + Args: + fn: A callable that will take as many arguments as there are + passed iterables. + timeout: The maximum number of seconds to wait. If None, then there + is no limit on the wait time. + chunksize: If greater than one, the iterables will be chopped into + chunks of size chunksize and submitted to the process pool. + If set to one, the items in the list will be sent one at a time. + + Returns: + An iterator equivalent to: map(func, *iterables) but the calls may + be evaluated out-of-order. + + Raises: + TimeoutError: If the entire result iterator could not be generated + before the given timeout. + Exception: If fn(*args) raises for any values. + 'b'chunksize must be >= 1.'u'chunksize must be >= 1.'u'concurrent.futures.process'u'futures.process'u'process'ORIGINAL_DIR + Return process object representing the current process + _current_process + Return list of process objects corresponding to live child processes + _cleanup + Return process object representing the parent process + _parent_process_popen + Process objects represent activity that is run in a separate process + + The class is analogous to `threading.Thread` + group argument must be None for now_process_counter_identity_config_parent_pid_parent_nameprocess object is closed + Method to be run in sub-process; can be overridden in sub-class + + Start child process + cannot start a process twicecan only start a process object created by current processdaemonic processes are not allowed to have children + Terminate process; sends SIGTERM signal or uses TerminateProcess() + + Terminate process; sends SIGKILL signal or uses TerminateProcess() + + Wait until child process terminates + can only join a child processcan only join a started process + Return whether process is alive + can only test a child process + Close the Process object. + + This method releases resources held by the Process object. It is + an error to call this method if the child process is still running. + Cannot close a process while it is still running. You should first call join() or terminate()."Cannot close a process while it is still running. ""You should first call join() or terminate()." + Return whether process is a daemon + daemonic + Set whether process is a daemon + process has already started + Set authorization key of process + AuthenticationStringexitcode + Return exit code of process or `None` if it has yet to stop + + Return identifier (PID) of process or `None` if it has yet to start + + Return a file descriptor (Unix) or handle (Windows) suitable for + waiting for process termination. + process not startedstoppedpid=%sparent=%s_exitcode_to_nameexitcode=%sold_process_ParentProcess_HAVE_THREAD_NATIVE_ID_set_native_id_finalizer_registry_run_after_forkerschild process calling self.run()_exit_functionProcess %s: +_shutdownprocess exiting with exitcode %d_flush_std_streamsPickling an AuthenticationString object is disallowed for security reasons'Pickling an AuthenticationString object is ''disallowed for security reasons' + Wait until parent process terminates + _MainProcess/mpsemprefixSIG# Module providing the `Process` class which emulates `threading.Thread`# multiprocessing/process.py# check for processes which have finished# The `Process` class# Avoid a refcycle if the target function holds an indirect# reference to the process object (see bpo-30775)# delay finalization of the old process object until after# _run_after_forkers() is executed# We subclass bytes to avoid accidental transmission of auth keys over network# Create object representing the parent process# Create object representing the main process# Note that some versions of FreeBSD only allow named# semaphores to have names of up to 14 characters. Therefore# we choose a short prefix.# On MacOSX in a sandbox it may be necessary to use a# different prefix -- see #19478.# Everything in self._config will be inherited by descendant# processes.# Give names to some return codes# For debug and leak testingb'BaseProcess'u'BaseProcess'b'current_process'u'current_process'b'active_children'u'active_children'b'parent_process'u'parent_process'b' + Return process object representing the current process + 'u' + Return process object representing the current process + 'b' + Return list of process objects corresponding to live child processes + 'u' + Return list of process objects corresponding to live child processes + 'b' + Return process object representing the parent process + 'u' + Return process object representing the parent process + 'b' + Process objects represent activity that is run in a separate process + + The class is analogous to `threading.Thread` + 'u' + Process objects represent activity that is run in a separate process + + The class is analogous to `threading.Thread` + 'b'group argument must be None for now'u'group argument must be None for now'b'process object is closed'u'process object is closed'b' + Method to be run in sub-process; can be overridden in sub-class + 'u' + Method to be run in sub-process; can be overridden in sub-class + 'b' + Start child process + 'u' + Start child process + 'b'cannot start a process twice'u'cannot start a process twice'b'can only start a process object created by current process'u'can only start a process object created by current process'b'daemonic processes are not allowed to have children'u'daemonic processes are not allowed to have children'b' + Terminate process; sends SIGTERM signal or uses TerminateProcess() + 'u' + Terminate process; sends SIGTERM signal or uses TerminateProcess() + 'b' + Terminate process; sends SIGKILL signal or uses TerminateProcess() + 'u' + Terminate process; sends SIGKILL signal or uses TerminateProcess() + 'b' + Wait until child process terminates + 'u' + Wait until child process terminates + 'b'can only join a child process'u'can only join a child process'b'can only join a started process'u'can only join a started process'b' + Return whether process is alive + 'u' + Return whether process is alive + 'b'can only test a child process'u'can only test a child process'b' + Close the Process object. + + This method releases resources held by the Process object. It is + an error to call this method if the child process is still running. + 'u' + Close the Process object. + + This method releases resources held by the Process object. It is + an error to call this method if the child process is still running. + 'b'Cannot close a process while it is still running. You should first call join() or terminate().'u'Cannot close a process while it is still running. You should first call join() or terminate().'b' + Return whether process is a daemon + 'u' + Return whether process is a daemon + 'b' + Set whether process is a daemon + 'u' + Set whether process is a daemon + 'b'process has already started'u'process has already started'b'authkey'u'authkey'b' + Set authorization key of process + 'u' + Set authorization key of process + 'b' + Return exit code of process or `None` if it has yet to stop + 'u' + Return exit code of process or `None` if it has yet to stop + 'b' + Return identifier (PID) of process or `None` if it has yet to start + 'u' + Return identifier (PID) of process or `None` if it has yet to start + 'b' + Return a file descriptor (Unix) or handle (Windows) suitable for + waiting for process termination. + 'u' + Return a file descriptor (Unix) or handle (Windows) suitable for + waiting for process termination. + 'b'process not started'u'process not started'b'started'u'started'b'initial'u'initial'b'stopped'u'stopped'b'pid=%s'u'pid=%s'b'parent=%s'u'parent=%s'b'exitcode=%s'u'exitcode=%s'b'child process calling self.run()'u'child process calling self.run()'b'Process %s: +'u'Process %s: +'b'process exiting with exitcode %d'u'process exiting with exitcode %d'b'Pickling an AuthenticationString object is disallowed for security reasons'u'Pickling an AuthenticationString object is disallowed for security reasons'b' + Wait until parent process terminates + 'u' + Wait until parent process terminates + 'b'/mp'u'/mp'b'semprefix'u'semprefix'b'SIG'u'SIG'Abstract Protocol base classes.DatagramProtocolSubprocessProtocolCommon base class for protocol interfaces. + + Usually user implements protocols that derived from BaseProtocol + like Protocol or ProcessProtocol. + + The only case when BaseProtocol should be implemented directly is + write-only transport like write pipe + Called when a connection is made. + + The argument is the transport representing the pipe connection. + To receive data, wait for data_received() calls. + When the connection is closed, connection_lost() is called. + Called when the connection is lost or closed. + + The argument is an exception object or None (the latter + meaning a regular EOF is received or the connection was + aborted or closed). + Called when the transport's buffer goes over the high-water mark. + + Pause and resume calls are paired -- pause_writing() is called + once when the buffer goes strictly over the high-water mark + (even if subsequent writes increases the buffer size even + more), and eventually resume_writing() is called once when the + buffer size reaches the low-water mark. + + Note that if the buffer size equals the high-water mark, + pause_writing() is not called -- it must go strictly over. + Conversely, resume_writing() is called when the buffer size is + equal or lower than the low-water mark. These end conditions + are important to ensure that things go as expected when either + mark is zero. + + NOTE: This is the only Protocol callback that is not called + through EventLoop.call_soon() -- if it were, it would have no + effect when it's most needed (when the app keeps writing + without yielding until pause_writing() is called). + Called when the transport's buffer drains below the low-water mark. + + See pause_writing() for details. + Interface for stream protocol. + + The user should implement this interface. They can inherit from + this class but don't need to. The implementations here do + nothing (they don't raise exceptions). + + When the user wants to requests a transport, they pass a protocol + factory to a utility function (e.g., EventLoop.create_connection()). + + When the connection is made successfully, connection_made() is + called with a suitable transport object. Then data_received() + will be called 0 or more times with data (bytes) received from the + transport; finally, connection_lost() will be called exactly once + with either an exception object or None as an argument. + + State machine of calls: + + start -> CM [-> DR*] [-> ER?] -> CL -> end + + * CM: connection_made() + * DR: data_received() + * ER: eof_received() + * CL: connection_lost() + Called when some data is received. + + The argument is a bytes object. + Called when the other end calls write_eof() or equivalent. + + If this returns a false value (including None), the transport + will close itself. If it returns a true value, closing the + transport is up to the protocol. + Interface for stream protocol with manual buffer control. + + Important: this has been added to asyncio in Python 3.7 + *on a provisional basis*! Consider it as an experimental API that + might be changed or removed in Python 3.8. + + Event methods, such as `create_server` and `create_connection`, + accept factories that return protocols that implement this interface. + + The idea of BufferedProtocol is that it allows to manually allocate + and control the receive buffer. Event loops can then use the buffer + provided by the protocol to avoid unnecessary data copies. This + can result in noticeable performance improvement for protocols that + receive big amounts of data. Sophisticated protocols can allocate + the buffer only once at creation time. + + State machine of calls: + + start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end + + * CM: connection_made() + * GB: get_buffer() + * BU: buffer_updated() + * ER: eof_received() + * CL: connection_lost() + get_bufferCalled to allocate a new receive buffer. + + *sizehint* is a recommended minimal size for the returned + buffer. When set to -1, the buffer size can be arbitrary. + + Must return an object that implements the + :ref:`buffer protocol `. + It is an error to return a zero-sized buffer. + buffer_updatedCalled when the buffer was updated with the received data. + + *nbytes* is the total number of bytes that were written to + the buffer. + Interface for datagram protocol.Called when some datagram is received.Called when a send or receive operation raises an OSError. + + (Other than BlockingIOError or InterruptedError.) + Interface for protocol for subprocess calls.Called when the subprocess writes data into stdout/stderr pipe. + + fd is int file descriptor. + data is bytes object. + Called when a file descriptor associated with the child process is + closed. + + fd is the int file descriptor that was closed. + Called when subprocess has exited.data_lenbuf_lenget_buffer() returned an empty bufferb'Abstract Protocol base classes.'u'Abstract Protocol base classes.'b'BaseProtocol'u'BaseProtocol'b'Protocol'u'Protocol'b'DatagramProtocol'u'DatagramProtocol'b'SubprocessProtocol'u'SubprocessProtocol'b'BufferedProtocol'u'BufferedProtocol'b'Common base class for protocol interfaces. + + Usually user implements protocols that derived from BaseProtocol + like Protocol or ProcessProtocol. + + The only case when BaseProtocol should be implemented directly is + write-only transport like write pipe + 'u'Common base class for protocol interfaces. + + Usually user implements protocols that derived from BaseProtocol + like Protocol or ProcessProtocol. + + The only case when BaseProtocol should be implemented directly is + write-only transport like write pipe + 'b'Called when a connection is made. + + The argument is the transport representing the pipe connection. + To receive data, wait for data_received() calls. + When the connection is closed, connection_lost() is called. + 'u'Called when a connection is made. + + The argument is the transport representing the pipe connection. + To receive data, wait for data_received() calls. + When the connection is closed, connection_lost() is called. + 'b'Called when the connection is lost or closed. + + The argument is an exception object or None (the latter + meaning a regular EOF is received or the connection was + aborted or closed). + 'u'Called when the connection is lost or closed. + + The argument is an exception object or None (the latter + meaning a regular EOF is received or the connection was + aborted or closed). + 'b'Called when the transport's buffer goes over the high-water mark. + + Pause and resume calls are paired -- pause_writing() is called + once when the buffer goes strictly over the high-water mark + (even if subsequent writes increases the buffer size even + more), and eventually resume_writing() is called once when the + buffer size reaches the low-water mark. + + Note that if the buffer size equals the high-water mark, + pause_writing() is not called -- it must go strictly over. + Conversely, resume_writing() is called when the buffer size is + equal or lower than the low-water mark. These end conditions + are important to ensure that things go as expected when either + mark is zero. + + NOTE: This is the only Protocol callback that is not called + through EventLoop.call_soon() -- if it were, it would have no + effect when it's most needed (when the app keeps writing + without yielding until pause_writing() is called). + 'u'Called when the transport's buffer goes over the high-water mark. + + Pause and resume calls are paired -- pause_writing() is called + once when the buffer goes strictly over the high-water mark + (even if subsequent writes increases the buffer size even + more), and eventually resume_writing() is called once when the + buffer size reaches the low-water mark. + + Note that if the buffer size equals the high-water mark, + pause_writing() is not called -- it must go strictly over. + Conversely, resume_writing() is called when the buffer size is + equal or lower than the low-water mark. These end conditions + are important to ensure that things go as expected when either + mark is zero. + + NOTE: This is the only Protocol callback that is not called + through EventLoop.call_soon() -- if it were, it would have no + effect when it's most needed (when the app keeps writing + without yielding until pause_writing() is called). + 'b'Called when the transport's buffer drains below the low-water mark. + + See pause_writing() for details. + 'u'Called when the transport's buffer drains below the low-water mark. + + See pause_writing() for details. + 'b'Interface for stream protocol. + + The user should implement this interface. They can inherit from + this class but don't need to. The implementations here do + nothing (they don't raise exceptions). + + When the user wants to requests a transport, they pass a protocol + factory to a utility function (e.g., EventLoop.create_connection()). + + When the connection is made successfully, connection_made() is + called with a suitable transport object. Then data_received() + will be called 0 or more times with data (bytes) received from the + transport; finally, connection_lost() will be called exactly once + with either an exception object or None as an argument. + + State machine of calls: + + start -> CM [-> DR*] [-> ER?] -> CL -> end + + * CM: connection_made() + * DR: data_received() + * ER: eof_received() + * CL: connection_lost() + 'u'Interface for stream protocol. + + The user should implement this interface. They can inherit from + this class but don't need to. The implementations here do + nothing (they don't raise exceptions). + + When the user wants to requests a transport, they pass a protocol + factory to a utility function (e.g., EventLoop.create_connection()). + + When the connection is made successfully, connection_made() is + called with a suitable transport object. Then data_received() + will be called 0 or more times with data (bytes) received from the + transport; finally, connection_lost() will be called exactly once + with either an exception object or None as an argument. + + State machine of calls: + + start -> CM [-> DR*] [-> ER?] -> CL -> end + + * CM: connection_made() + * DR: data_received() + * ER: eof_received() + * CL: connection_lost() + 'b'Called when some data is received. + + The argument is a bytes object. + 'u'Called when some data is received. + + The argument is a bytes object. + 'b'Called when the other end calls write_eof() or equivalent. + + If this returns a false value (including None), the transport + will close itself. If it returns a true value, closing the + transport is up to the protocol. + 'u'Called when the other end calls write_eof() or equivalent. + + If this returns a false value (including None), the transport + will close itself. If it returns a true value, closing the + transport is up to the protocol. + 'b'Interface for stream protocol with manual buffer control. + + Important: this has been added to asyncio in Python 3.7 + *on a provisional basis*! Consider it as an experimental API that + might be changed or removed in Python 3.8. + + Event methods, such as `create_server` and `create_connection`, + accept factories that return protocols that implement this interface. + + The idea of BufferedProtocol is that it allows to manually allocate + and control the receive buffer. Event loops can then use the buffer + provided by the protocol to avoid unnecessary data copies. This + can result in noticeable performance improvement for protocols that + receive big amounts of data. Sophisticated protocols can allocate + the buffer only once at creation time. + + State machine of calls: + + start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end + + * CM: connection_made() + * GB: get_buffer() + * BU: buffer_updated() + * ER: eof_received() + * CL: connection_lost() + 'u'Interface for stream protocol with manual buffer control. + + Important: this has been added to asyncio in Python 3.7 + *on a provisional basis*! Consider it as an experimental API that + might be changed or removed in Python 3.8. + + Event methods, such as `create_server` and `create_connection`, + accept factories that return protocols that implement this interface. + + The idea of BufferedProtocol is that it allows to manually allocate + and control the receive buffer. Event loops can then use the buffer + provided by the protocol to avoid unnecessary data copies. This + can result in noticeable performance improvement for protocols that + receive big amounts of data. Sophisticated protocols can allocate + the buffer only once at creation time. + + State machine of calls: + + start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end + + * CM: connection_made() + * GB: get_buffer() + * BU: buffer_updated() + * ER: eof_received() + * CL: connection_lost() + 'b'Called to allocate a new receive buffer. + + *sizehint* is a recommended minimal size for the returned + buffer. When set to -1, the buffer size can be arbitrary. + + Must return an object that implements the + :ref:`buffer protocol `. + It is an error to return a zero-sized buffer. + 'u'Called to allocate a new receive buffer. + + *sizehint* is a recommended minimal size for the returned + buffer. When set to -1, the buffer size can be arbitrary. + + Must return an object that implements the + :ref:`buffer protocol `. + It is an error to return a zero-sized buffer. + 'b'Called when the buffer was updated with the received data. + + *nbytes* is the total number of bytes that were written to + the buffer. + 'u'Called when the buffer was updated with the received data. + + *nbytes* is the total number of bytes that were written to + the buffer. + 'b'Interface for datagram protocol.'u'Interface for datagram protocol.'b'Called when some datagram is received.'u'Called when some datagram is received.'b'Called when a send or receive operation raises an OSError. + + (Other than BlockingIOError or InterruptedError.) + 'u'Called when a send or receive operation raises an OSError. + + (Other than BlockingIOError or InterruptedError.) + 'b'Interface for protocol for subprocess calls.'u'Interface for protocol for subprocess calls.'b'Called when the subprocess writes data into stdout/stderr pipe. + + fd is int file descriptor. + data is bytes object. + 'u'Called when the subprocess writes data into stdout/stderr pipe. + + fd is int file descriptor. + data is bytes object. + 'b'Called when a file descriptor associated with the child process is + closed. + + fd is the int file descriptor that was closed. + 'u'Called when a file descriptor associated with the child process is + closed. + + fd is the int file descriptor that was closed. + 'b'Called when subprocess has exited.'u'Called when subprocess has exited.'b'get_buffer() returned an empty buffer'u'get_buffer() returned an empty buffer'u'asyncio.protocols'u'protocols'u'This module provides access to the Unix password database. +It is available on all Unix versions. + +Password database entries are reported as 7-tuples containing the following +items from the password database (see `'), in order: +pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell. +The uid and gid items are integers, all others are strings. An +exception is raised if the entry asked for cannot be found.'getpwallu'pwd.struct_passwd: Results from getpw*() routines. + +This object may be accessed either as a tuple of + (pw_name,pw_passwd,pw_uid,pw_gid,pw_gecos,pw_dir,pw_shell) +or via the object attributes as named in the above tuple.'pw_gecospw_gidpw_namepw_passwdpw_shellpw_uidpwd.struct_passwdstruct_passwdRoutine to "compile" a .py file to a .pyc file. + +This module has intimate knowledge of the format of .pyc files. +PyCompileErrorPycInvalidationModeException raised when an error occurs while attempting to + compile the file. + + To raise this exception, use + + raise PyCompileError(exc_type,exc_value,file[,msg]) + + where + + exc_type: exception type to be used in error message + type name can be accesses as class variable + 'exc_type_name' + + exc_value: exception value to be used in error message + can be accesses as class variable 'exc_value' + + file: name of file being compiled to be used in error message + can be accesses as class variable 'file' + + msg: string message to be written as error message + If no value is given, a default exception message will be + given, consistent with 'standard' py_compile output. + message (or default) can be accesses as class variable + 'msg' + + exc_type_nametbtextFile ""File "%s"Sorry: %s: %sTIMESTAMPCHECKED_HASHUNCHECKED_HASH_get_default_invalidation_modeSOURCE_DATE_EPOCHcfiledfiledoraiseinvalidation_modeByte-compile one Python source file to Python bytecode. + + :param file: The source file name. + :param cfile: The target byte compiled file name. When not given, this + defaults to the PEP 3147/PEP 488 location. + :param dfile: Purported file name, i.e. the file name that shows up in + error messages. Defaults to the source file name. + :param doraise: Flag indicating whether or not an exception should be + raised when a compile error is found. If an exception occurs and this + flag is set to False, a string indicating the nature of the exception + will be printed, and the function will return to the caller. If an + exception occurs and this flag is set to True, a PyCompileError + exception will be raised. + :param optimize: The optimization level for the compiler. Valid values + are -1, 0, 1 and 2. A value of -1 means to use the optimization + level of the current interpreter, as given by -O command line options. + :param invalidation_mode: + :param quiet: Return full output with False or 0, errors only with 1, + and no output with 2. + + :return: Path to the resulting byte compiled file. + + Note that it isn't necessary to byte-compile Python modules for + execution efficiency -- Python itself byte-compiles a module when + it is loaded, and if it can, writes out the bytecode to the + corresponding .pyc file. + + However, if a Python installation is shared between users, it is a + good idea to byte-compile all modules upon installation, since + other users may not be able to write in the source directories, + and thus they won't be able to write the .pyc file, and then + they would be byte-compiling every module each time it is loaded. + This can slow down program start-up considerably. + + See compileall.py for a script/module that uses this module to + byte-compile all installed files (or all files in selected + directories). + + Do note that FileExistsError is raised if cfile ends up pointing at a + non-regular file or symlink. Because the compilation uses a file renaming, + the resulting file would be regular and thus not the same type of file as + it was previously. + {} is a symlink and will be changed into a regular file if import writes a byte-compiled file to it'{} is a symlink and will be changed into a regular file if ''import writes a byte-compiled file to it'{} is a non-regular file and will be changed into a regular one if import writes a byte-compiled file to it'{} is a non-regular file and will be changed into a regular ''one if import writes a byte-compiled file to it'py_excsource_statsCompile several source files. + + The files named in 'args' (or on the command line, if 'args' is + not specified) are compiled and the resulting bytecode is cached + in the normal manner. This function does not search a directory + structure to locate source files; it only compiles files named + explicitly. If '-' is the only parameter in args, the list of + files is taken from standard input. + + # return value to indicate at least one failureb'Routine to "compile" a .py file to a .pyc file. + +This module has intimate knowledge of the format of .pyc files. +'u'Routine to "compile" a .py file to a .pyc file. + +This module has intimate knowledge of the format of .pyc files. +'b'compile'u'compile'b'PyCompileError'u'PyCompileError'b'PycInvalidationMode'u'PycInvalidationMode'b'Exception raised when an error occurs while attempting to + compile the file. + + To raise this exception, use + + raise PyCompileError(exc_type,exc_value,file[,msg]) + + where + + exc_type: exception type to be used in error message + type name can be accesses as class variable + 'exc_type_name' + + exc_value: exception value to be used in error message + can be accesses as class variable 'exc_value' + + file: name of file being compiled to be used in error message + can be accesses as class variable 'file' + + msg: string message to be written as error message + If no value is given, a default exception message will be + given, consistent with 'standard' py_compile output. + message (or default) can be accesses as class variable + 'msg' + + 'u'Exception raised when an error occurs while attempting to + compile the file. + + To raise this exception, use + + raise PyCompileError(exc_type,exc_value,file[,msg]) + + where + + exc_type: exception type to be used in error message + type name can be accesses as class variable + 'exc_type_name' + + exc_value: exception value to be used in error message + can be accesses as class variable 'exc_value' + + file: name of file being compiled to be used in error message + can be accesses as class variable 'file' + + msg: string message to be written as error message + If no value is given, a default exception message will be + given, consistent with 'standard' py_compile output. + message (or default) can be accesses as class variable + 'msg' + + 'b'File ""'u'File ""'b'File "%s"'u'File "%s"'b'Sorry: %s: %s'u'Sorry: %s: %s'b'SOURCE_DATE_EPOCH'u'SOURCE_DATE_EPOCH'b'Byte-compile one Python source file to Python bytecode. + + :param file: The source file name. + :param cfile: The target byte compiled file name. When not given, this + defaults to the PEP 3147/PEP 488 location. + :param dfile: Purported file name, i.e. the file name that shows up in + error messages. Defaults to the source file name. + :param doraise: Flag indicating whether or not an exception should be + raised when a compile error is found. If an exception occurs and this + flag is set to False, a string indicating the nature of the exception + will be printed, and the function will return to the caller. If an + exception occurs and this flag is set to True, a PyCompileError + exception will be raised. + :param optimize: The optimization level for the compiler. Valid values + are -1, 0, 1 and 2. A value of -1 means to use the optimization + level of the current interpreter, as given by -O command line options. + :param invalidation_mode: + :param quiet: Return full output with False or 0, errors only with 1, + and no output with 2. + + :return: Path to the resulting byte compiled file. + + Note that it isn't necessary to byte-compile Python modules for + execution efficiency -- Python itself byte-compiles a module when + it is loaded, and if it can, writes out the bytecode to the + corresponding .pyc file. + + However, if a Python installation is shared between users, it is a + good idea to byte-compile all modules upon installation, since + other users may not be able to write in the source directories, + and thus they won't be able to write the .pyc file, and then + they would be byte-compiling every module each time it is loaded. + This can slow down program start-up considerably. + + See compileall.py for a script/module that uses this module to + byte-compile all installed files (or all files in selected + directories). + + Do note that FileExistsError is raised if cfile ends up pointing at a + non-regular file or symlink. Because the compilation uses a file renaming, + the resulting file would be regular and thus not the same type of file as + it was previously. + 'u'Byte-compile one Python source file to Python bytecode. + + :param file: The source file name. + :param cfile: The target byte compiled file name. When not given, this + defaults to the PEP 3147/PEP 488 location. + :param dfile: Purported file name, i.e. the file name that shows up in + error messages. Defaults to the source file name. + :param doraise: Flag indicating whether or not an exception should be + raised when a compile error is found. If an exception occurs and this + flag is set to False, a string indicating the nature of the exception + will be printed, and the function will return to the caller. If an + exception occurs and this flag is set to True, a PyCompileError + exception will be raised. + :param optimize: The optimization level for the compiler. Valid values + are -1, 0, 1 and 2. A value of -1 means to use the optimization + level of the current interpreter, as given by -O command line options. + :param invalidation_mode: + :param quiet: Return full output with False or 0, errors only with 1, + and no output with 2. + + :return: Path to the resulting byte compiled file. + + Note that it isn't necessary to byte-compile Python modules for + execution efficiency -- Python itself byte-compiles a module when + it is loaded, and if it can, writes out the bytecode to the + corresponding .pyc file. + + However, if a Python installation is shared between users, it is a + good idea to byte-compile all modules upon installation, since + other users may not be able to write in the source directories, + and thus they won't be able to write the .pyc file, and then + they would be byte-compiling every module each time it is loaded. + This can slow down program start-up considerably. + + See compileall.py for a script/module that uses this module to + byte-compile all installed files (or all files in selected + directories). + + Do note that FileExistsError is raised if cfile ends up pointing at a + non-regular file or symlink. Because the compilation uses a file renaming, + the resulting file would be regular and thus not the same type of file as + it was previously. + 'b'{} is a symlink and will be changed into a regular file if import writes a byte-compiled file to it'u'{} is a symlink and will be changed into a regular file if import writes a byte-compiled file to it'b'{} is a non-regular file and will be changed into a regular one if import writes a byte-compiled file to it'u'{} is a non-regular file and will be changed into a regular one if import writes a byte-compiled file to it'b''u''b'Compile several source files. + + The files named in 'args' (or on the command line, if 'args' is + not specified) are compiled and the resulting bytecode is cached + in the normal manner. This function does not search a directory + structure to locate source files; it only compiles files named + explicitly. If '-' is the only parameter in args, the list of + files is taken from standard input. + + 'u'Compile several source files. + + The files named in 'args' (or on the command line, if 'args' is + not specified) are compiled and the resulting bytecode is cached + in the normal manner. This function does not search a directory + structure to locate source files; it only compiles files named + explicitly. If '-' is the only parameter in args, the list of + files is taken from standard input. + + 'u'py_compile'Generate Python documentation in HTML or text for interactive use. + +At the Python interactive prompt, calling help(thing) on a Python object +documents the object, and calling help() starts up an interactive +help session. + +Or, at the shell command line outside of Python: + +Run "pydoc " to show documentation on something. may be +the name of a function, module, package, or a dotted reference to a +class or function within a module or module in a package. If the +argument contains a path segment delimiter (e.g. slash on Unix, +backslash on Windows) it is treated as the path to a Python source file. + +Run "pydoc -k " to search for a keyword in the synopsis lines +of all available modules. + +Run "pydoc -n " to start an HTTP server with the given +hostname (default: localhost) on the local machine. + +Run "pydoc -p " to start an HTTP server on the given port on the +local machine. Port number 0 can be used to get an arbitrary unused port. + +Run "pydoc -b" to start an HTTP server on an arbitrary unused port and +open a Web browser to interactively browse documentation. Combine with +the -n and -p options to control the hostname and port used. + +Run "pydoc -w " to write out the HTML documentation for a module +to a file named ".html". + +Module docs for core modules are assumed to be in + + https://docs.python.org/X.Y/library/ + +This can be overridden by setting the PYTHONDOCS environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. +26 February 2001Guido van Rossum, for an excellent programming language. +Tommy Burnette, the original creator of manpy. +Paul Prescod, for all his work on onlinehelp. +Richard Chamberlain, for the first implementation of textdoc. +__credits__ReprpathdirsConvert sys.path into a list of absolute, existing, unique paths.normdirsnormdirGet the doc string or comments for an object.^ * +splitdocSplit a doc string into a synopsis line (if any) and the rest.classnameGet a class name and qualify it with a module name if necessary.isdataCheck if an object is of a type that probably means it's data.Do a series of global replacements on a string.cramOmit part of a string if needed to make it fit in a maximum length.pre at 0x[0-9a-f]{6,16}(>+)$_re_stripidstripidRemove the hexadecimal id from a Python object representation._is_bound_method + Returns True if fn is a bound method, regardless of whether + fn was implemented in Python or in C. + allmethodscl_split_listSplit sequence s via predicate, and return pair ([true], [false]). + + The return value is a 2-tuple of lists, + ([x for x in s if predicate(x)], + [x for x in s if not predicate(x)]) + visiblenameDecide whether to show documentation on a variable.Wrap inspect.classify_class_attrs, with fixup for data descriptors.data descriptorreadonly propertysort_attributesSort the attrs list in-place by _fields and then alphabetically by namefield_orderkeyfuncispackageGuess whether a path refers to a package directory.source_synopsissynopsisGet the one-line summary out of a module file.lastupdateloader_cls__temp__ErrorDuringImportErrors that occurred while trying to import something to document it.problem in %s - %s: %simportfileImport a Python source file or compiled file given its path.is_bytecodesafeimportforceloadImport a module; handle errors; return None if the module isn't found. + + If the module *is* found but an exception occurs, it's wrapped in an + ErrorDuringImport exception and reraised. Unlike __import__, if a + package path is specified, the module at the end of the path is returned, + not the package at the beginning. If the optional 'forceload' argument + is 1, we reload the module from disk (unless it's a dynamic extension).subsDocPYTHONDOCShttps://docs.python.org/%d.%d/librarydocumentGenerate documentation for an object.docmoduledocclassdocroutinedocdatadocotherRaise an exception for unimplemented types.don't know how to document object%s of type %sdocpropertygetdoclocget_pathstdlibReturn the location of module docs or None(built-in)doclocsite-packagesxml.etreetest.pydoc_modhttp://https://%s/%sHTMLReprClass for safely making an HTML representation of a Python object.maxlistmaxtuplemaxdictmaxstringmaxotherrepr1repr_repr_stringtestrepr((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)\1repr_strrepr_instance<%s instance>repr_unicodeHTMLDocFormatter class for HTML documentation._repr_instancepageFormat an HTML page. +Python: %s + + +%s +fgcolbgcolFormat a page heading. + + +
 
+ 
%s
%s
+ preludemarginaliagapFormat a section with a heading.

+ + + + + + + + +
 
+%s
%s%s
%s
%s%s%s
bigsectionFormat a section with a big heading.%spreformatFormat literal preformatted text. + +
+multicolumnFormat a list of items into a multi-column list.rows%s
grey%snamelinkMake a link for an identifier, given name-to-URL mappings.
%sclasslinkMake a link for a class.%smodulelinkMake a link for a module.%smodpkglinkmodpkginfoMake a link for a module or package to display in an index.shadowed%s.%s.html%s.html%s (package)filelinkMake a link to source file.%smarkupMark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.here\b((http|ftp)://\S+[\w/]|RFC[- ]?(\d+)|PEP[- ]?(\d+)|(self\.)?(\w+))r'\b((http|ftp)://\S+[\w/]|'r'RFC[- ]?(\d+)|'r'PEP[- ]?(\d+)|'r'(self\.)?(\w+))'rfcpepselfdothttp://www.rfc-editor.org/rfc/rfc%d.txthttp://www.python.org/dev/peps/pep-%04d/self.self.%sformattreeProduce HTML for a class tree as given by inspect.getclasstree().

+
+%s
+
+%s
+Produce HTML documentation for a module object.links%slinkedname%sRevision: version %s
Module Reference#ffffff#7799eeindex
cdict.html#fdict#-%s

%s

+modpkgsPackage Contents#aa55ccModulesclasslistClasses#ee77aaFunctions#eeaa77#55aa55AuthorCreditsProduce HTML documentation for a class object.realnameHorizontalRuleneedonemaybe
+
Method resolution order:
+
%s
+
+spillmdictspilldescriptorsspilldata
%s
+
%s
%s%s
+thisclassinheriteddefined hereinherited from %s:
+Methods %sClass methods %sStatic methods %sReadonly properties %sData descriptors %sData and other attributes %sclass %s%s = class %sdeclargspec%s
 
#000000#ffc8d8Format an argument default value as text.Produce HTML documentation for a function or method object.noteskipdocsimclass from method of %s instance unbound %s methodasync asyncqualifier%s%sreallink%s = %s%s lambda (...)%s
%s
+
%s
%s
%s
+Produce html documentation for a data descriptor.
%s
+
%s
+Produce HTML documentation for a data object.%s = lhsGenerate an HTML index for a directory of modules.TextReprClass for safely making a text representation of a Python object.TextDocFormatter class for text documentation.boldFormat a string in bold by overstriking.Indent text by prepending a given prefix to each line.Format a section with a given heading.clean_contentsRender in text a class tree as returned by inspect.getclasstree().Produce text documentation for a given module object.synop - MODULE REFERENCE + +The following documentation is automatically generated from the Python +source files. It may be incomplete, incorrect or include features that +are considered implementation detail and may vary between Python +implementations. When in doubt, consult the module reference at the +location listed above. +DESCRIPTIONmodpkgs_names (package)PACKAGE CONTENTSsubmodulesSUBMODULESCLASSESFUNCTIONSDATAAUTHORCREDITSFILEProduce text documentation for a given class object.makenameclass = class Method resolution order:subclassesno_of_subclassesMAX_SUBCLASSES_TO_DISPLAYBuilt-in subclasses:subclassname ... and other subclassesMethods %s: +Class methods %s: +Static methods %s: +Readonly properties %s: +Data descriptors %s: +Data and other attributes %s: + | Produce text documentation for a function or method object. = lambda Produce text documentation for a data descriptor.Produce text documentation for a data object.chop_PlainTextDocSubclass of TextDoc which overrides string stylingThe first time this is called, determine what kind of pager to use.getpagerDecide what method to use for paging through text.plainpagerMANPAGERPAGERuse_pagertempfilepagerTERMdumbemacspipepagermore <(less) 2>/dev/nulllessmore "%s"ttypagerRemove boldface formatting from text..Page through text by feeding it to another program.Page through text by invoking a program on a temporary file.TemporaryDirectorytempdirpydoc.out_escape_stdoutPage through text on a text terminal.ttytcgetattrsetcbreakgetcharLINESinc-- more -- tcsetattrTCSAFLUSHSimply print unformatted text. This is the ultimate fallback.describeProduce a short description of the given thing.built-in module package built-in function getset descriptor %s.%s.%smember descriptor %s.%s.%sfunction method locateLocate an object by name or dotted path, importing as necessary.nextmoduleplaintextGiven an object or a path to an object, get the object and its name.No Python documentation found for %r. +Use help() to get the interactive help utility. +Use help(str) for help on the str class.render_docPython Library Documentation: %srendererRender text documentation, given an object or a path to an object. in module Display text documentation, given an object or a path to an object.writedocWrite HTML documentation to a file in the current directory.wrotewritedocsWrite out HTML documentation for all modules in a directory tree.HelperBOOLEANwhile forCLASSES SPECIALMETHODSBASICMETHODSbreak continue whilenonlocal NAMESPACESTRUTHVALUEMODULESSEQUENCEMETHODSCOMPARISONglobal NAMESPACESEXCEPTIONSbreak continue if TRUTHVALUECONTEXTMANAGERS EXCEPTIONS yield_strprefixesSTRINGS<<<>OPERATORSUNARY+=-=*=/=%=&=|=^=<<=>>=**=//=AUGMENTEDASSIGNMENTBITWISECOMPLEX_symbols_inverseOPERATORS FORMATTINGPOWERTUPLES LISTS FUNCTIONSATTRIBUTES FLOAT MODULES OBJECTSSLICINGS DICTIONARYLITERALSdef classPRIVATENAMESPRIVATENAMES SPECIALMETHODSBACKQUOTESTUPLES FUNCTIONS CALLSLISTS SUBSCRIPTS SLICINGSsymbolssymbols_STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS ''FUNCTIONS CLASSES MODULES FILES inspect'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'str UNICODE SEQUENCES STRINGMETHODS ''FORMATTING TYPES'string-methodsSTRINGS FORMATTINGSTRINGMETHODSformatstringsFORMATTINGencodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'encodings unicode SEQUENCES STRINGMETHODS 'INTEGER FLOAT COMPLEX TYPESNUMBERSintegersint rangeINTEGERfloatingfloat mathimaginarycomplex cmathtypesseqSTRINGMETHODS FORMATTING range LISTSSEQUENCESDICTIONARIESMAPPINGStypesfunctionsdef TYPEStypesmethodsclass def CLASSES TYPESMETHODSbltin-code-objectscompile FUNCTIONS TYPESCODEOBJECTSbltin-type-objectstypes TYPESTYPEOBJECTSFRAMEOBJECTSTRACEBACKSbltin-null-objectbltin-ellipsis-objectSLICINGSspecialattrsSPECIALATTRIBUTESclass SPECIALMETHODS PRIVATENAMEStypesmodulesPACKAGESoperator-summarylambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES'lambda or and not in is BOOLEAN ''COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER ''UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES ''LISTS DICTIONARIES'EXPRESSIONSPRECEDENCEOBJECTSspecialnamesBASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS NUMBERMETHODS CLASSES'BASICMETHODS ATTRIBUTEMETHODS ''CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS ''NUMBERMETHODS CLASSES'SPECIALMETHODScustomizationhash repr str SPECIALMETHODSattribute-accessATTRIBUTES SPECIALMETHODSATTRIBUTEMETHODScallable-typesCALLS SPECIALMETHODSCALLABLEMETHODSsequence-typesSEQUENCES SEQUENCEMETHODS SPECIALMETHODS'SEQUENCES SEQUENCEMETHODS ''SPECIALMETHODS'MAPPINGS SPECIALMETHODSMAPPINGMETHODSnumeric-typesNUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'NUMBERS AUGMENTEDASSIGNMENT 'NUMBERMETHODSexecmodelNAMESPACES DYNAMICFEATURES EXCEPTIONSEXECUTIONnamingglobal nonlocal ASSIGNMENT DELETION DYNAMICFEATURESNAMESPACESdynamic-featuresDYNAMICFEATURESSCOPINGFRAMEStry except finally raiseconversionsCONVERSIONSidentifierskeywords SPECIALIDENTIFIERSIDENTIFIERSid-classesSPECIALIDENTIFIERSatom-identifiersatom-literalsSTRINGS NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'STRINGS NUMBERS TUPLELITERALS ''LISTLITERALS DICTIONARYLITERALS'LITERALSTUPLESexprlistsTUPLES LITERALSTUPLELITERALStypesseq-mutableLISTLITERALSLISTSlistsLISTS LITERALStypesmappingDICTIONARYLITERALSDICTIONARIES LITERALSattribute-referencesgetattr hasattr setattr ATTRIBUTEMETHODSATTRIBUTESsubscriptionsSUBSCRIPTSslicingscallsCALLSunaryBINARYshiftingSHIFTINGbitwisecomparisonsEXPRESSIONS BASICMETHODSbooleansEXPRESSIONS TRUTHVALUEASSERTIONassignmentASSIGNMENTaugassignDELETIONRETURNINGIMPORTINGCONDITIONALcompoundfor while break continueLOOPINGif while and or not BASICMETHODSDEBUGGINGcontext-managersCONTEXTMANAGERS<%s.%s instance>_GoInteractive +You are now leaving help and returning to the Python interpreter. +If you want to ask for help on a particular object directly from the +interpreter, you can type "help(object)". Executing "help('string')" +has the same effect as typing a particular string at the help> prompt. +help> Read one line, using input() when appropriate.listkeywordslistsymbolslisttopicslistmodulesmodules showsymbolHelp on %s:showtopic +Welcome to Python {0}'s help utility! + +If this is your first time using Python, you should definitely check out +the tutorial on the Internet at https://docs.python.org/{0}/tutorial/. + +Enter the name of any module, keyword, or topic to get help on writing +Python programs and using Python modules. To quit this help utility and +return to the interpreter, just type "quit". + +To get a list of available modules, keywords, symbols, or topics, type +"modules", "keywords", "symbols", or "topics". Each module also comes +with a one-line summary of what it does; to list the modules whose name +or summary contain a given string such as "spam", type "modules spam". +colw +Here is a list of the Python keywords. Enter any keyword to get more help. + + +Here is a list of the punctuation symbols which Python assigns special meaning +to. Enter any symbol to get more help. + + +Here is a list of available topics. Enter any topic name to get more help. + +more_xrefspydoc_data.topicspydoc_data +Sorry, topic and keyword documentation is not available because the +module "pydoc_data.topics" could not be found. +no documentation found for %s +xrefsRelated help topics: wrapped_text +%s +_gettopicReturn unbuffered tuple of (topic, xrefs). + + If an error occurs here, the exception is caught and displayed by + the url handler. + + This function duplicates the showtopic method but returns its + result directly so it can be formatted for display in an html page. + could not find topic +Here is a list of modules whose name or summary contains '{}'. +If there are any, enter a module name to get more help. + +apropos +Please wait a moment while I gather a list of all available modules... + +.__init__ModuleScanner +Enter any module name to get more help. Or, type "modules spam" to search +for modules whose name or summary contain the string "spam". +An interruptible scanner that searches module synopses.completerPrint all the one-line module summaries that contain a substring._start_serverurlhandlerStart an HTTP server thread on a specific port. + + Start an HTML/text server thread, so HTML or text documents can be + browsed dynamically and interactively with a Web browser. Example use: + + >>> import time + >>> import pydoc + + Define a URL handler. To determine what the client is asking + for, check the URL and content_type. + + Then get or generate some text or HTML code and return it. + + >>> def my_url_handler(url, content_type): + ... text = 'the URL sent was: (%s, %s)' % (url, content_type) + ... return text + + Start server thread on port 0. + If you use port 0, the server will pick a random port number. + You can then use serverthread.port to get the port number. + + >>> port = 0 + >>> serverthread = pydoc._start_server(my_url_handler, port) + + Check that the server is really started. If it is, open browser + and get first page. Use serverthread.url as the starting page. + + >>> if serverthread.serving: + ... import webbrowser + + The next two lines are commented out so a browser doesn't open if + doctest is run on this module. + + #... webbrowser.open(serverthread.url) + #True + + Let the server do its thing. We just need to monitor its status. + Use time.sleep so the loop doesn't hog the CPU. + + >>> starttime = time.monotonic() + >>> timeout = 1 #seconds + + This is a short timeout for testing purposes. + + >>> while serverthread.serving: + ... time.sleep(.01) + ... if serverthread.serving and time.monotonic() - starttime > timeout: + ... serverthread.stop() + ... break + + Print any errors that may have occurred. + + >>> print(serverthread.error) + None + DocHandlerBaseHTTPRequestHandlerdo_GETProcess a request from an HTML browser. + + The URL received is in self.path. + Get an HTML page from self.urlhandler and send it. + content_typesend_responsesend_header%s; charset=UTF-8end_headerswfilelog_messageDocServerHTTPServerserve_until_quitrdhandle_requestserver_closeserver_activateServerThreadservingStart the server.MessageClassdocsvrdocserverserver_porthttp://%s:%d/Stop the server and this thread nicely.01_url_handlerThe pydoc url handler for use with the pydoc server. + + If the content_type is 'text/css', the _pydoc.css style + sheet is read and returned if it exits. + + If the content_type is 'text/html', then the result of + get_html_page(url) is returned. + _HTMLDocpydoc_data/_pydoc.csscss_pathcss_link +Pydoc: %s + +%s%s
%s
+html_navbar%s [%s, %s] +
+ Python %s
%s +
+
+ +
+
+ + +
  +
+ + +
+
+
+ html_indexModule Index page.bltinlinkIndex of Modules

Built-in Modules

pydoc by Ka-Ping Yee<ping@lfw.org>'

pydoc by Ka-Ping Yee''<ping@lfw.org>'Index of Moduleshtml_searchSearch results page.search_resultSearch Resultskey = %s
Search Resultshtml_topicsIndex of topic texts available.%sINDEXTopicshtml_keywordsIndex of keywords.Keywordshtml_topicpageTopic or keyword help page.htmlhelpKEYWORDTOPIC

%s
html_getobjcould not find objecthtml_errorError#bb0000Error - %sget_html_pageGenerate an HTML page for url.complete_urlsearch?keytopic?keyget?keybad pydoc urlpath_hereunknown content type %r for url %sopen_browserStart the enhanced pydoc Web server and open a Web browser. + + Use port '0' to start the server on an arbitrary port. + Set open_browser to False to suppress opening a browser. + webbrowserserverthreadServer commands: [b]rowser, [q]uitserver_help_msgServer ready atserver> Server stoppedispath_get_revised_pathgiven_pathEnsures current directory is on returned path, and argv0 directory is not + + Exception: argv0 dir is left alone if it's also pydoc's directory. + + Returns a new path entry list, or None if no adjustment is needed. + stdlib_dirscript_dirrevised_path_adjust_cli_sys_pathEnsures current directory is on sys.path, and __main__ directory is not. + + Exception: __main__ dir is left alone if it's also pydoc's directory. + cliCommand-line interface (looks at sys.argv to decide what to do).BadUsagebk:n:p:wwritingstart_serverfile %r does not existpydoc - the Python documentation tool + +{cmd} ... + Show text documentation on something. may be the name of a + Python keyword, topic, function, module, or package, or a dotted + reference to a class or function within a module or module in a + package. If contains a '{sep}', it is used as the path to a + Python source file to document. If name is 'keywords', 'topics', + or 'modules', a listing of these things is displayed. + +{cmd} -k + Search for a keyword in the synopsis lines of all available modules. + +{cmd} -n + Start an HTTP server with the given hostname (default: localhost). + +{cmd} -p + Start an HTTP server on the given port on the local machine. Port + number 0 can be used to get an arbitrary unused port. + +{cmd} -b + Start an HTTP server on an arbitrary unused port and open a Web browser + to interactively browse documentation. This option can be used in + combination with -n and/or -p. + +{cmd} -w ... + Write out the HTML documentation for a module to a file in the current + directory. If contains a '{sep}', it is treated as a filename; if + it names a directory, documentation is written for all the contents. +# Known bugs that can't be fixed here:# - synopsis() cannot be prevented from clobbering existing# loaded modules.# - If the __file__ attribute on a module is a relative path and# the current directory is changed with os.chdir(), an incorrect# path will be displayed.# --------------------------------------------------------- common routines# The behaviour of %p is implementation-dependent in terms of case.# all your base are belong to us# Certain special names are redundant or internal.# XXX Remove __initializing__?# Private names are hidden, but special names are displayed.# Namedtuples have public fields and methods with a single leading underscore# only document that which the programmer exported in __all__# This allows data descriptors to be ordered according# to a _fields attribute if present.# ----------------------------------------------------- module manipulation# Look for binary suffixes first, falling back to source.# Now handle the choice.# Must be a source file.# module can't be opened, so skip it# text modules can be directly examined# Must be a binary module, which has to be imported.# XXX We probably don't need to pass in the loader here.# Cache the result.# If forceload is 1 and the module has been previously loaded from# disk, we always have to reload the module. Checking the file's# mtime isn't good enough (e.g. the module could contain a class# that inherits from another module that has changed).# Remove the module from sys.modules and re-import to try# and avoid problems with partially loaded modules.# Also remove any submodules because they won't appear# in the newly loaded module's namespace if they're already# in sys.modules.# Prevent garbage collection.# Did the error occur before or after the module was found?# An error occurred while executing the imported module.# A SyntaxError occurred before we could execute the module.# No such module in the path.# Some other error occurred during the importing process.# ---------------------------------------------------- formatter base class# 'try' clause is to attempt to handle the possibility that inspect# identifies something in a way that pydoc itself has issues handling;# think 'super' and how it is a descriptor (which raises the exception# by lacking a __name__ attribute) and an instance.# -------------------------------------------- HTML documentation generator# Backslashes are only literal in the string and are never# needed to make any special characters, so show a raw string.# ------------------------------------------- HTML formatting utilities# Create a link for methods like 'self.method(...)'# and use for attributes like 'self.attr'# ---------------------------------------------- type-specific routines# ignore the passed-in name# if __all__ exists, believe it. Otherwise use old heuristic.# Cute little class to pump out a horizontal rule between sections.# List the mro, if non-trivial.# Some descriptors may meet a failure in their __get__.# (bug #1785)# The value may not be hashable (e.g., a data attr with# a dict or list value).# Pump out the attrs, segregated by kind.# XXX lambda's won't usually have func_annotations['return']# since the syntax doesn't support but it is possible.# So removing parentheses isn't truly safe.# remove parentheses# ignore a module if its name contains a surrogate character# -------------------------------------------- text documentation generator# ------------------------------------------- text formatting utilities# Detect submodules as sometimes created by C extensions# List the built-in subclasses, if any:# --------------------------------------------------------- user interfaces# pipes completely broken in Windows# We've hereby abandoned whatever text hasn't been written,# but the pager is still in control of the terminal.# Ignore broken pipes caused by quitting the pager program.# Ignore ctl-c like the pager itself does. Otherwise the pager is# left running and the terminal is in raw mode and unusable.# Escape non-encodable characters to avoid encoding errors later# --------------------------------------- interactive interpreter interface# If the passed object is a piece of data or an instance,# document its available methods instead of its value.# These dictionaries map a topic name to either an alias, or a tuple# (label, seealso-items). The "label" is the label of the corresponding# section in the .rst file under Doc/ and an index into the dictionary# in pydoc_data/topics.py.# CAUTION: if you change one of these dictionaries, be sure to adapt the# list of needed labels in Doc/tools/extensions/pyspecific.py and# regenerate the pydoc_data/topics.py file by running# make pydoc-topics# in Doc/ and copying the output file into the Lib/ directory.# Either add symbols to this dictionary or to the symbols dictionary# directly: Whichever is easier. They are merged later.# Make sure significant trailing quoting marks of literals don't# get deleted while cleaning input# special case these keywords since they are objects too# raised by tests for bad coding cookies or BOM# ignore problems during import# --------------------------------------- enhanced Web browser interface# Don't log messages.# explicitly break a reference cycle: DocServer.callback# has indirectly a reference to ServerThread.# Wait until thread.serving is True to make sure we are# really up before returning.# scan for modules# format page# try topics first, then objects.# try objects first, then topics.# Catch any errors and display them in an error page.# Errors outside the url handler are caught by the server.# -------------------------------------------------- command-line interface# Scripts may get the current directory in their path by default if they're# run with the -m switch, or directly from the current directory.# The interactive prompt also allows imports from the current directory.# Accordingly, if the current directory is already present, don't make# any changes to the given_path# Otherwise, add the current directory to the given path, and remove the# script directory (as long as the latter isn't also pydoc's directory.# Note: the tests only cover _get_revised_path, not _adjust_cli_path itselfb'Generate Python documentation in HTML or text for interactive use. + +At the Python interactive prompt, calling help(thing) on a Python object +documents the object, and calling help() starts up an interactive +help session. + +Or, at the shell command line outside of Python: + +Run "pydoc " to show documentation on something. may be +the name of a function, module, package, or a dotted reference to a +class or function within a module or module in a package. If the +argument contains a path segment delimiter (e.g. slash on Unix, +backslash on Windows) it is treated as the path to a Python source file. + +Run "pydoc -k " to search for a keyword in the synopsis lines +of all available modules. + +Run "pydoc -n " to start an HTTP server with the given +hostname (default: localhost) on the local machine. + +Run "pydoc -p " to start an HTTP server on the given port on the +local machine. Port number 0 can be used to get an arbitrary unused port. + +Run "pydoc -b" to start an HTTP server on an arbitrary unused port and +open a Web browser to interactively browse documentation. Combine with +the -n and -p options to control the hostname and port used. + +Run "pydoc -w " to write out the HTML documentation for a module +to a file named ".html". + +Module docs for core modules are assumed to be in + + https://docs.python.org/X.Y/library/ + +This can be overridden by setting the PYTHONDOCS environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. +'u'Generate Python documentation in HTML or text for interactive use. + +At the Python interactive prompt, calling help(thing) on a Python object +documents the object, and calling help() starts up an interactive +help session. + +Or, at the shell command line outside of Python: + +Run "pydoc " to show documentation on something. may be +the name of a function, module, package, or a dotted reference to a +class or function within a module or module in a package. If the +argument contains a path segment delimiter (e.g. slash on Unix, +backslash on Windows) it is treated as the path to a Python source file. + +Run "pydoc -k " to search for a keyword in the synopsis lines +of all available modules. + +Run "pydoc -n " to start an HTTP server with the given +hostname (default: localhost) on the local machine. + +Run "pydoc -p " to start an HTTP server on the given port on the +local machine. Port number 0 can be used to get an arbitrary unused port. + +Run "pydoc -b" to start an HTTP server on an arbitrary unused port and +open a Web browser to interactively browse documentation. Combine with +the -n and -p options to control the hostname and port used. + +Run "pydoc -w " to write out the HTML documentation for a module +to a file named ".html". + +Module docs for core modules are assumed to be in + + https://docs.python.org/X.Y/library/ + +This can be overridden by setting the PYTHONDOCS environment variable +to a different URL or to a local directory containing the Library +Reference Manual pages. +'b'26 February 2001'u'26 February 2001'b'Guido van Rossum, for an excellent programming language. +Tommy Burnette, the original creator of manpy. +Paul Prescod, for all his work on onlinehelp. +Richard Chamberlain, for the first implementation of textdoc. +'u'Guido van Rossum, for an excellent programming language. +Tommy Burnette, the original creator of manpy. +Paul Prescod, for all his work on onlinehelp. +Richard Chamberlain, for the first implementation of textdoc. +'b'Convert sys.path into a list of absolute, existing, unique paths.'u'Convert sys.path into a list of absolute, existing, unique paths.'b'Get the doc string or comments for an object.'u'Get the doc string or comments for an object.'b'^ * +'u'^ * +'b'Split a doc string into a synopsis line (if any) and the rest.'u'Split a doc string into a synopsis line (if any) and the rest.'b'Get a class name and qualify it with a module name if necessary.'u'Get a class name and qualify it with a module name if necessary.'b'Check if an object is of a type that probably means it's data.'u'Check if an object is of a type that probably means it's data.'b'Do a series of global replacements on a string.'u'Do a series of global replacements on a string.'b'Omit part of a string if needed to make it fit in a maximum length.'u'Omit part of a string if needed to make it fit in a maximum length.'b' at 0x[0-9a-f]{6,16}(>+)$'u' at 0x[0-9a-f]{6,16}(>+)$'b'Remove the hexadecimal id from a Python object representation.'u'Remove the hexadecimal id from a Python object representation.'b' + Returns True if fn is a bound method, regardless of whether + fn was implemented in Python or in C. + 'u' + Returns True if fn is a bound method, regardless of whether + fn was implemented in Python or in C. + 'b'Split sequence s via predicate, and return pair ([true], [false]). + + The return value is a 2-tuple of lists, + ([x for x in s if predicate(x)], + [x for x in s if not predicate(x)]) + 'u'Split sequence s via predicate, and return pair ([true], [false]). + + The return value is a 2-tuple of lists, + ([x for x in s if predicate(x)], + [x for x in s if not predicate(x)]) + 'b'Decide whether to show documentation on a variable.'u'Decide whether to show documentation on a variable.'b'__credits__'u'__credits__'b'__date__'u'__date__'b'__version__'u'__version__'b'Wrap inspect.classify_class_attrs, with fixup for data descriptors.'u'Wrap inspect.classify_class_attrs, with fixup for data descriptors.'b'data descriptor'u'data descriptor'b'readonly property'u'readonly property'b'Sort the attrs list in-place by _fields and then alphabetically by name'u'Sort the attrs list in-place by _fields and then alphabetically by name'b'Guess whether a path refers to a package directory.'u'Guess whether a path refers to a package directory.'b'r"""'u'r"""'b'Get the one-line summary out of a module file.'u'Get the one-line summary out of a module file.'b'__temp__'u'__temp__'b'Errors that occurred while trying to import something to document it.'u'Errors that occurred while trying to import something to document it.'b'problem in %s - %s: %s'u'problem in %s - %s: %s'b'Import a Python source file or compiled file given its path.'u'Import a Python source file or compiled file given its path.'b'Import a module; handle errors; return None if the module isn't found. + + If the module *is* found but an exception occurs, it's wrapped in an + ErrorDuringImport exception and reraised. Unlike __import__, if a + package path is specified, the module at the end of the path is returned, + not the package at the beginning. If the optional 'forceload' argument + is 1, we reload the module from disk (unless it's a dynamic extension).'u'Import a module; handle errors; return None if the module isn't found. + + If the module *is* found but an exception occurs, it's wrapped in an + ErrorDuringImport exception and reraised. Unlike __import__, if a + package path is specified, the module at the end of the path is returned, + not the package at the beginning. If the optional 'forceload' argument + is 1, we reload the module from disk (unless it's a dynamic extension).'b'PYTHONDOCS'u'PYTHONDOCS'b'https://docs.python.org/%d.%d/library'u'https://docs.python.org/%d.%d/library'b'Generate documentation for an object.'u'Generate documentation for an object.'b'Raise an exception for unimplemented types.'u'Raise an exception for unimplemented types.'b'don't know how to document object%s of type %s'u'don't know how to document object%s of type %s'b'stdlib'u'stdlib'b'Return the location of module docs or None'u'Return the location of module docs or None'b'(built-in)'u'(built-in)'b'gc'b'zipimport'b'site-packages'u'site-packages'b'xml.etree'b'test.pydoc_mod'u'test.pydoc_mod'b'http://'u'http://'b'https://'u'https://'b'%s/%s'u'%s/%s'b'Class for safely making an HTML representation of a Python object.'u'Class for safely making an HTML representation of a Python object.'b'repr_'u'repr_'b'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)'u'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)'b'\1'u'\1'b'<%s instance>'u'<%s instance>'b'Formatter class for HTML documentation.'u'Formatter class for HTML documentation.'b'Format an HTML page.'u'Format an HTML page.'b' +Python: %s + + +%s +'u' +Python: %s + + +%s +'b'Format a page heading.'u'Format a page heading.'b' + + +
 
+ 
%s
%s
+ 'u' + + +
 
+ 
%s
%s
+ 'b'Format a section with a heading.'u'Format a section with a heading.'b''u''b''u''b'

+ + + + 'u'

+

 
+%s
+ + + 'b' + + +'u' + + +'b' +'u' +'b' +
 
+%s
%s%s
%s
%s%s
%s
%s%s
%s%s%s
'u' +%s'b'Format a section with a big heading.'u'Format a section with a big heading.'b'%s'u'%s'b'Format literal preformatted text.'u'Format literal preformatted text.'b' + +'u' + +'b'
+'u'
+'b'Format a list of items into a multi-column list.'u'Format a list of items into a multi-column list.'b''u''b'%s
'u'%s
'b'%s'u'%s'b'Make a link for an identifier, given name-to-URL mappings.'u'Make a link for an identifier, given name-to-URL mappings.'b'%s'u'%s'b'Make a link for a class.'u'Make a link for a class.'b'%s'u'%s'b'Make a link for a module.'u'Make a link for a module.'b'%s'u'%s'b'Make a link for a module or package to display in an index.'u'Make a link for a module or package to display in an index.'b'%s.%s.html'u'%s.%s.html'b'%s.html'u'%s.html'b'%s (package)'u'%s (package)'b'Make a link to source file.'u'Make a link to source file.'b'%s'u'%s'b'Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.'u'Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.'b'\b((http|ftp)://\S+[\w/]|RFC[- ]?(\d+)|PEP[- ]?(\d+)|(self\.)?(\w+))'u'\b((http|ftp)://\S+[\w/]|RFC[- ]?(\d+)|PEP[- ]?(\d+)|(self\.)?(\w+))'b'http://www.rfc-editor.org/rfc/rfc%d.txt'u'http://www.rfc-editor.org/rfc/rfc%d.txt'b'http://www.python.org/dev/peps/pep-%04d/'u'http://www.python.org/dev/peps/pep-%04d/'b'self.'u'self.'b'self.%s'u'self.%s'b'Produce HTML for a class tree as given by inspect.getclasstree().'u'Produce HTML for a class tree as given by inspect.getclasstree().'b'

'u'
'b' +
'u' +'b'
+%s
+'u'
+%s
+'b'
+%s
+'u'
+%s
+'b'Produce HTML documentation for a module object.'u'Produce HTML documentation for a module object.'b'%s'u'%s'b'%s'u'%s'b'Revision: 'u'Revision: 'b'version %s'u'version %s'b'
Module Reference'u'
Module Reference'b'#ffffff'u'#ffffff'b'#7799ee'u'#7799ee'b'index
'u'index
'b'.html#'u'.html#'b'#-'u'#-'b'%s'u'%s'b'

%s

+'u'

%s

+'b'Package Contents'u'Package Contents'b'#aa55cc'u'#aa55cc'b'Modules'u'Modules'b'Classes'u'Classes'b'#ee77aa'u'#ee77aa'b'Functions'u'Functions'b'#eeaa77'u'#eeaa77'b'#55aa55'u'#55aa55'b'Author'u'Author'b'Credits'u'Credits'b'Produce HTML documentation for a class object.'u'Produce HTML documentation for a class object.'b'
+'u'
+'b'
Method resolution order:
+'u'
Method resolution order:
+'b'
%s
+'u'
%s
+'b'
+'u'
+'b'
%s
+'u'
%s
+'b'
%s'u'
%s'b'
%s%s
+'u'
%s%s
+'b'defined here'u'defined here'b'inherited from %s'u'inherited from %s'b':
+'u':
+'b'Methods %s'u'Methods %s'b'Class methods %s'u'Class methods %s'b'Static methods %s'u'Static methods %s'b'Readonly properties %s'u'Readonly properties %s'b'Data descriptors %s'u'Data descriptors %s'b'Data and other attributes %s'u'Data and other attributes %s'b'class %s'u'class %s'b'%s = class %s'u'%s = class %s'b'%s
 
'u'%s
 
'b'#000000'u'#000000'b'#ffc8d8'u'#ffc8d8'b'Format an argument default value as text.'u'Format an argument default value as text.'b'Produce HTML documentation for a function or method object.'u'Produce HTML documentation for a function or method object.'b' from 'u' from 'b' method of %s instance'u' method of %s instance'b' unbound %s method'u' unbound %s method'b'async 'u'async 'b'%s'u'%s'b'%s'u'%s'b'%s = %s'u'%s = %s'b'%s lambda 'u'%s lambda 'b'(...)'u'(...)'b'%s'u'%s'b'
%s
+'u'
%s
+'b'
%s
'u'
%s
'b'
%s
%s
+'u'
%s
%s
+'b'Produce html documentation for a data descriptor.'u'Produce html documentation for a data descriptor.'b'
%s
+'u'
%s
+'b'
%s
+'u'
%s
+'b'Produce HTML documentation for a data object.'u'Produce HTML documentation for a data object.'b'%s = 'u'%s = 'b'Generate an HTML index for a directory of modules.'u'Generate an HTML index for a directory of modules.'b'Class for safely making a text representation of a Python object.'u'Class for safely making a text representation of a Python object.'b'Formatter class for text documentation.'u'Formatter class for text documentation.'b'Format a string in bold by overstriking.'u'Format a string in bold by overstriking.'u' 'b'Indent text by prepending a given prefix to each line.'u'Indent text by prepending a given prefix to each line.'b'Format a section with a given heading.'u'Format a section with a given heading.'b'Render in text a class tree as returned by inspect.getclasstree().'u'Render in text a class tree as returned by inspect.getclasstree().'b'Produce text documentation for a given module object.'u'Produce text documentation for a given module object.'b' - 'u' - 'b'MODULE REFERENCE'u'MODULE REFERENCE'b' + +The following documentation is automatically generated from the Python +source files. It may be incomplete, incorrect or include features that +are considered implementation detail and may vary between Python +implementations. When in doubt, consult the module reference at the +location listed above. +'u' + +The following documentation is automatically generated from the Python +source files. It may be incomplete, incorrect or include features that +are considered implementation detail and may vary between Python +implementations. When in doubt, consult the module reference at the +location listed above. +'b'DESCRIPTION'u'DESCRIPTION'b' (package)'u' (package)'b'PACKAGE CONTENTS'u'PACKAGE CONTENTS'b'SUBMODULES'u'SUBMODULES'b'CLASSES'u'CLASSES'b'FUNCTIONS'u'FUNCTIONS'b'DATA'u'DATA'b'AUTHOR'u'AUTHOR'b'CREDITS'u'CREDITS'b'FILE'u'FILE'b'Produce text documentation for a given class object.'u'Produce text documentation for a given class object.'b'class 'u'class 'b' = class 'u' = class 'b'Method resolution order:'u'Method resolution order:'b'Built-in subclasses:'u'Built-in subclasses:'b' ... and 'u' ... and 'b' other subclasses'u' other subclasses'b'Methods %s: +'u'Methods %s: +'b'Class methods %s: +'u'Class methods %s: +'b'Static methods %s: +'u'Static methods %s: +'b'Readonly properties %s: +'u'Readonly properties %s: +'b'Data descriptors %s: +'u'Data descriptors %s: +'b'Data and other attributes %s: +'u'Data and other attributes %s: +'b' | 'u' | 'b'Produce text documentation for a function or method object.'u'Produce text documentation for a function or method object.'b' = 'u' = 'b' lambda 'u' lambda 'b'Produce text documentation for a data descriptor.'u'Produce text documentation for a data descriptor.'b'Produce text documentation for a data object.'u'Produce text documentation for a data object.'b'Subclass of TextDoc which overrides string styling'u'Subclass of TextDoc which overrides string styling'b'The first time this is called, determine what kind of pager to use.'u'The first time this is called, determine what kind of pager to use.'b'Decide what method to use for paging through text.'u'Decide what method to use for paging through text.'b'isatty'u'isatty'b'MANPAGER'u'MANPAGER'b'PAGER'u'PAGER'b'TERM'u'TERM'b'dumb'u'dumb'b'emacs'u'emacs'b'more <'u'more <'b'system'u'system'b'(less) 2>/dev/null'u'(less) 2>/dev/null'b'less'u'less'b'more "%s"'u'more "%s"'b'more'u'more'b'Remove boldface formatting from text.'u'Remove boldface formatting from text.'b'.'u'.'b'Page through text by feeding it to another program.'u'Page through text by feeding it to another program.'b'Page through text by invoking a program on a temporary file.'u'Page through text by invoking a program on a temporary file.'b'pydoc.out'u'pydoc.out'b'Page through text on a text terminal.'u'Page through text on a text terminal.'b'LINES'u'LINES'b'-- more --'u'-- more --'b' 'u' 'b''u''b'Simply print unformatted text. This is the ultimate fallback.'u'Simply print unformatted text. This is the ultimate fallback.'b'Produce a short description of the given thing.'u'Produce a short description of the given thing.'b'built-in module 'u'built-in module 'b'package 'u'package 'b'built-in function 'u'built-in function 'b'getset descriptor %s.%s.%s'u'getset descriptor %s.%s.%s'b'member descriptor %s.%s.%s'u'member descriptor %s.%s.%s'b'function 'u'function 'b'method 'u'method 'b'Locate an object by name or dotted path, importing as necessary.'u'Locate an object by name or dotted path, importing as necessary.'b'Given an object or a path to an object, get the object and its name.'u'Given an object or a path to an object, get the object and its name.'b'No Python documentation found for %r. +Use help() to get the interactive help utility. +Use help(str) for help on the str class.'u'No Python documentation found for %r. +Use help() to get the interactive help utility. +Use help(str) for help on the str class.'b'Python Library Documentation: %s'u'Python Library Documentation: %s'b'Render text documentation, given an object or a path to an object.'u'Render text documentation, given an object or a path to an object.'b' in module 'u' in module 'b'Display text documentation, given an object or a path to an object.'u'Display text documentation, given an object or a path to an object.'b'Write HTML documentation to a file in the current directory.'u'Write HTML documentation to a file in the current directory.'b'wrote'u'wrote'b'Write out HTML documentation for all modules in a directory tree.'u'Write out HTML documentation for all modules in a directory tree.'b'BOOLEAN'u'BOOLEAN'b'while for'u'while for'b'CLASSES SPECIALMETHODS'u'CLASSES SPECIALMETHODS'b'BASICMETHODS'u'BASICMETHODS'b'break continue while'u'break continue while'b'nonlocal NAMESPACES'u'nonlocal NAMESPACES'b'TRUTHVALUE'u'TRUTHVALUE'b'MODULES'u'MODULES'b'SEQUENCEMETHODS'u'SEQUENCEMETHODS'b'COMPARISON'u'COMPARISON'b'global NAMESPACES'u'global NAMESPACES'b'EXCEPTIONS'u'EXCEPTIONS'b'break continue if TRUTHVALUE'u'break continue if TRUTHVALUE'b'CONTEXTMANAGERS EXCEPTIONS yield'u'CONTEXTMANAGERS EXCEPTIONS yield'b'STRINGS'u'STRINGS'b'<<'u'<<'b'<>'u'<>'b'OPERATORS'u'OPERATORS'b'UNARY'u'UNARY'b'+='u'+='b'-='u'-='b'*='u'*='b'/='u'/='b'%='u'%='b'&='u'&='b'|='u'|='b'^='u'^='b'<<='u'<<='b'>>='u'>>='b'**='u'**='b'//='u'//='b'AUGMENTEDASSIGNMENT'u'AUGMENTEDASSIGNMENT'b'BITWISE'u'BITWISE'u'j'u'J'b'COMPLEX'u'COMPLEX'b'OPERATORS FORMATTING'u'OPERATORS FORMATTING'b'POWER'u'POWER'b'TUPLES LISTS FUNCTIONS'u'TUPLES LISTS FUNCTIONS'b'ATTRIBUTES FLOAT MODULES OBJECTS'u'ATTRIBUTES FLOAT MODULES OBJECTS'b'SLICINGS DICTIONARYLITERALS'u'SLICINGS DICTIONARYLITERALS'b'def class'u'def class'b'PRIVATENAMES'u'PRIVATENAMES'b'PRIVATENAMES SPECIALMETHODS'u'PRIVATENAMES SPECIALMETHODS'b'BACKQUOTES'u'BACKQUOTES'b'TUPLES FUNCTIONS CALLS'u'TUPLES FUNCTIONS CALLS'b'LISTS SUBSCRIPTS SLICINGS'u'LISTS SUBSCRIPTS SLICINGS'b'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'u'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'b'TYPES'u'TYPES'b'strings'u'strings'b'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'u'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'b'string-methods'u'string-methods'b'STRINGS FORMATTING'u'STRINGS FORMATTING'b'STRINGMETHODS'u'STRINGMETHODS'b'formatstrings'u'formatstrings'b'FORMATTING'u'FORMATTING'b'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'u'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'b'UNICODE'u'UNICODE'b'numbers'b'INTEGER FLOAT COMPLEX TYPES'u'INTEGER FLOAT COMPLEX TYPES'b'NUMBERS'u'NUMBERS'b'integers'u'integers'b'int range'u'int range'b'INTEGER'u'INTEGER'b'floating'u'floating'b'float math'u'float math'b'FLOAT'u'FLOAT'b'imaginary'u'imaginary'b'complex cmath'u'complex cmath'b'typesseq'u'typesseq'b'STRINGMETHODS FORMATTING range LISTS'u'STRINGMETHODS FORMATTING range LISTS'b'SEQUENCES'u'SEQUENCES'b'DICTIONARIES'u'DICTIONARIES'b'MAPPINGS'u'MAPPINGS'b'typesfunctions'u'typesfunctions'b'def TYPES'u'def TYPES'b'typesmethods'u'typesmethods'b'class def CLASSES TYPES'u'class def CLASSES TYPES'b'METHODS'u'METHODS'b'bltin-code-objects'u'bltin-code-objects'b'compile FUNCTIONS TYPES'u'compile FUNCTIONS TYPES'b'CODEOBJECTS'u'CODEOBJECTS'b'bltin-type-objects'u'bltin-type-objects'b'types TYPES'u'types TYPES'b'TYPEOBJECTS'u'TYPEOBJECTS'b'FRAMEOBJECTS'u'FRAMEOBJECTS'b'TRACEBACKS'u'TRACEBACKS'b'bltin-null-object'u'bltin-null-object'b'NONE'u'NONE'b'bltin-ellipsis-object'u'bltin-ellipsis-object'b'SLICINGS'u'SLICINGS'b'specialattrs'u'specialattrs'b'SPECIALATTRIBUTES'u'SPECIALATTRIBUTES'b'class SPECIALMETHODS PRIVATENAMES'u'class SPECIALMETHODS PRIVATENAMES'b'typesmodules'u'typesmodules'b'PACKAGES'u'PACKAGES'b'operator-summary'u'operator-summary'b'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES'u'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES'b'EXPRESSIONS'u'EXPRESSIONS'b'PRECEDENCE'u'PRECEDENCE'b'objects'u'objects'b'OBJECTS'u'OBJECTS'b'specialnames'u'specialnames'b'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS NUMBERMETHODS CLASSES'u'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS NUMBERMETHODS CLASSES'b'SPECIALMETHODS'u'SPECIALMETHODS'b'customization'u'customization'b'hash repr str SPECIALMETHODS'u'hash repr str SPECIALMETHODS'b'attribute-access'u'attribute-access'b'ATTRIBUTES SPECIALMETHODS'u'ATTRIBUTES SPECIALMETHODS'b'ATTRIBUTEMETHODS'u'ATTRIBUTEMETHODS'b'callable-types'u'callable-types'b'CALLS SPECIALMETHODS'u'CALLS SPECIALMETHODS'b'CALLABLEMETHODS'u'CALLABLEMETHODS'b'sequence-types'u'sequence-types'b'SEQUENCES SEQUENCEMETHODS SPECIALMETHODS'u'SEQUENCES SEQUENCEMETHODS SPECIALMETHODS'b'MAPPINGS SPECIALMETHODS'u'MAPPINGS SPECIALMETHODS'b'MAPPINGMETHODS'u'MAPPINGMETHODS'b'numeric-types'u'numeric-types'b'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'u'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'b'NUMBERMETHODS'u'NUMBERMETHODS'b'execmodel'u'execmodel'b'NAMESPACES DYNAMICFEATURES EXCEPTIONS'u'NAMESPACES DYNAMICFEATURES EXCEPTIONS'b'EXECUTION'u'EXECUTION'b'naming'u'naming'b'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'u'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'b'NAMESPACES'u'NAMESPACES'b'dynamic-features'u'dynamic-features'b'DYNAMICFEATURES'u'DYNAMICFEATURES'b'SCOPING'u'SCOPING'b'FRAMES'u'FRAMES'b'try except finally raise'u'try except finally raise'b'conversions'u'conversions'b'CONVERSIONS'u'CONVERSIONS'b'identifiers'u'identifiers'b'keywords SPECIALIDENTIFIERS'u'keywords SPECIALIDENTIFIERS'b'IDENTIFIERS'u'IDENTIFIERS'b'id-classes'u'id-classes'b'SPECIALIDENTIFIERS'u'SPECIALIDENTIFIERS'b'atom-identifiers'u'atom-identifiers'b'atom-literals'u'atom-literals'b'STRINGS NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'u'STRINGS NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'b'LITERALS'u'LITERALS'b'TUPLES'u'TUPLES'b'exprlists'u'exprlists'b'TUPLES LITERALS'u'TUPLES LITERALS'b'TUPLELITERALS'u'TUPLELITERALS'b'typesseq-mutable'u'typesseq-mutable'b'LISTLITERALS'u'LISTLITERALS'b'LISTS'u'LISTS'b'lists'u'lists'b'LISTS LITERALS'u'LISTS LITERALS'b'typesmapping'u'typesmapping'b'DICTIONARYLITERALS'u'DICTIONARYLITERALS'b'DICTIONARIES LITERALS'u'DICTIONARIES LITERALS'b'attribute-references'u'attribute-references'b'getattr hasattr setattr ATTRIBUTEMETHODS'u'getattr hasattr setattr ATTRIBUTEMETHODS'b'ATTRIBUTES'u'ATTRIBUTES'b'subscriptions'u'subscriptions'b'SUBSCRIPTS'u'SUBSCRIPTS'b'slicings'u'slicings'b'calls'u'calls'b'CALLS'u'CALLS'b'power'u'power'b'unary'u'unary'b'BINARY'u'BINARY'b'shifting'u'shifting'b'SHIFTING'u'SHIFTING'b'bitwise'u'bitwise'b'comparisons'u'comparisons'b'EXPRESSIONS BASICMETHODS'u'EXPRESSIONS BASICMETHODS'b'booleans'u'booleans'b'EXPRESSIONS TRUTHVALUE'u'EXPRESSIONS TRUTHVALUE'b'ASSERTION'u'ASSERTION'b'assignment'u'assignment'b'ASSIGNMENT'u'ASSIGNMENT'b'augassign'u'augassign'b'DELETION'u'DELETION'b'RETURNING'u'RETURNING'b'IMPORTING'u'IMPORTING'b'CONDITIONAL'u'CONDITIONAL'b'compound'u'compound'b'for while break continue'u'for while break continue'b'LOOPING'u'LOOPING'b'if while and or not BASICMETHODS'u'if while and or not BASICMETHODS'b'debugger'u'debugger'b'pdb'b'DEBUGGING'u'DEBUGGING'b'context-managers'u'context-managers'b'CONTEXTMANAGERS'u'CONTEXTMANAGERS'b'<%s.%s instance>'u'<%s.%s instance>'b' +You are now leaving help and returning to the Python interpreter. +If you want to ask for help on a particular object directly from the +interpreter, you can type "help(object)". Executing "help('string')" +has the same effect as typing a particular string at the help> prompt. +'u' +You are now leaving help and returning to the Python interpreter. +If you want to ask for help on a particular object directly from the +interpreter, you can type "help(object)". Executing "help('string')" +has the same effect as typing a particular string at the help> prompt. +'b'help> 'u'help> 'b'Read one line, using input() when appropriate.'u'Read one line, using input() when appropriate.'b'symbols'u'symbols'b'topics'u'topics'b'modules'u'modules'b'modules 'u'modules 'b'Help on %s:'u'Help on %s:'b' +Welcome to Python {0}'s help utility! + +If this is your first time using Python, you should definitely check out +the tutorial on the Internet at https://docs.python.org/{0}/tutorial/. + +Enter the name of any module, keyword, or topic to get help on writing +Python programs and using Python modules. To quit this help utility and +return to the interpreter, just type "quit". + +To get a list of available modules, keywords, symbols, or topics, type +"modules", "keywords", "symbols", or "topics". Each module also comes +with a one-line summary of what it does; to list the modules whose name +or summary contain a given string such as "spam", type "modules spam". +'u' +Welcome to Python {0}'s help utility! + +If this is your first time using Python, you should definitely check out +the tutorial on the Internet at https://docs.python.org/{0}/tutorial/. + +Enter the name of any module, keyword, or topic to get help on writing +Python programs and using Python modules. To quit this help utility and +return to the interpreter, just type "quit". + +To get a list of available modules, keywords, symbols, or topics, type +"modules", "keywords", "symbols", or "topics". Each module also comes +with a one-line summary of what it does; to list the modules whose name +or summary contain a given string such as "spam", type "modules spam". +'b' +Here is a list of the Python keywords. Enter any keyword to get more help. + +'u' +Here is a list of the Python keywords. Enter any keyword to get more help. + +'b' +Here is a list of the punctuation symbols which Python assigns special meaning +to. Enter any symbol to get more help. + +'u' +Here is a list of the punctuation symbols which Python assigns special meaning +to. Enter any symbol to get more help. + +'b' +Here is a list of available topics. Enter any topic name to get more help. + +'u' +Here is a list of available topics. Enter any topic name to get more help. + +'b' +Sorry, topic and keyword documentation is not available because the +module "pydoc_data.topics" could not be found. +'u' +Sorry, topic and keyword documentation is not available because the +module "pydoc_data.topics" could not be found. +'b'no documentation found for %s +'u'no documentation found for %s +'b'Related help topics: 'u'Related help topics: 'b' +%s +'u' +%s +'b'Return unbuffered tuple of (topic, xrefs). + + If an error occurs here, the exception is caught and displayed by + the url handler. + + This function duplicates the showtopic method but returns its + result directly so it can be formatted for display in an html page. + 'u'Return unbuffered tuple of (topic, xrefs). + + If an error occurs here, the exception is caught and displayed by + the url handler. + + This function duplicates the showtopic method but returns its + result directly so it can be formatted for display in an html page. + 'b'could not find topic'u'could not find topic'b' +Here is a list of modules whose name or summary contains '{}'. +If there are any, enter a module name to get more help. + +'u' +Here is a list of modules whose name or summary contains '{}'. +If there are any, enter a module name to get more help. + +'b' +Please wait a moment while I gather a list of all available modules... + +'u' +Please wait a moment while I gather a list of all available modules... + +'b'.__init__'u'.__init__'b' +Enter any module name to get more help. Or, type "modules spam" to search +for modules whose name or summary contain the string "spam". +'u' +Enter any module name to get more help. Or, type "modules spam" to search +for modules whose name or summary contain the string "spam". +'b'An interruptible scanner that searches module synopses.'u'An interruptible scanner that searches module synopses.'b'Print all the one-line module summaries that contain a substring.'u'Print all the one-line module summaries that contain a substring.'b'Start an HTTP server thread on a specific port. + + Start an HTML/text server thread, so HTML or text documents can be + browsed dynamically and interactively with a Web browser. Example use: + + >>> import time + >>> import pydoc + + Define a URL handler. To determine what the client is asking + for, check the URL and content_type. + + Then get or generate some text or HTML code and return it. + + >>> def my_url_handler(url, content_type): + ... text = 'the URL sent was: (%s, %s)' % (url, content_type) + ... return text + + Start server thread on port 0. + If you use port 0, the server will pick a random port number. + You can then use serverthread.port to get the port number. + + >>> port = 0 + >>> serverthread = pydoc._start_server(my_url_handler, port) + + Check that the server is really started. If it is, open browser + and get first page. Use serverthread.url as the starting page. + + >>> if serverthread.serving: + ... import webbrowser + + The next two lines are commented out so a browser doesn't open if + doctest is run on this module. + + #... webbrowser.open(serverthread.url) + #True + + Let the server do its thing. We just need to monitor its status. + Use time.sleep so the loop doesn't hog the CPU. + + >>> starttime = time.monotonic() + >>> timeout = 1 #seconds + + This is a short timeout for testing purposes. + + >>> while serverthread.serving: + ... time.sleep(.01) + ... if serverthread.serving and time.monotonic() - starttime > timeout: + ... serverthread.stop() + ... break + + Print any errors that may have occurred. + + >>> print(serverthread.error) + None + 'u'Start an HTTP server thread on a specific port. + + Start an HTML/text server thread, so HTML or text documents can be + browsed dynamically and interactively with a Web browser. Example use: + + >>> import time + >>> import pydoc + + Define a URL handler. To determine what the client is asking + for, check the URL and content_type. + + Then get or generate some text or HTML code and return it. + + >>> def my_url_handler(url, content_type): + ... text = 'the URL sent was: (%s, %s)' % (url, content_type) + ... return text + + Start server thread on port 0. + If you use port 0, the server will pick a random port number. + You can then use serverthread.port to get the port number. + + >>> port = 0 + >>> serverthread = pydoc._start_server(my_url_handler, port) + + Check that the server is really started. If it is, open browser + and get first page. Use serverthread.url as the starting page. + + >>> if serverthread.serving: + ... import webbrowser + + The next two lines are commented out so a browser doesn't open if + doctest is run on this module. + + #... webbrowser.open(serverthread.url) + #True + + Let the server do its thing. We just need to monitor its status. + Use time.sleep so the loop doesn't hog the CPU. + + >>> starttime = time.monotonic() + >>> timeout = 1 #seconds + + This is a short timeout for testing purposes. + + >>> while serverthread.serving: + ... time.sleep(.01) + ... if serverthread.serving and time.monotonic() - starttime > timeout: + ... serverthread.stop() + ... break + + Print any errors that may have occurred. + + >>> print(serverthread.error) + None + 'b'Process a request from an HTML browser. + + The URL received is in self.path. + Get an HTML page from self.urlhandler and send it. + 'u'Process a request from an HTML browser. + + The URL received is in self.path. + Get an HTML page from self.urlhandler and send it. + 'b'%s; charset=UTF-8'u'%s; charset=UTF-8'b'Start the server.'u'Start the server.'b'http://%s:%d/'u'http://%s:%d/'b'Stop the server and this thread nicely'u'Stop the server and this thread nicely'b'The pydoc url handler for use with the pydoc server. + + If the content_type is 'text/css', the _pydoc.css style + sheet is read and returned if it exits. + + If the content_type is 'text/html', then the result of + get_html_page(url) is returned. + 'u'The pydoc url handler for use with the pydoc server. + + If the content_type is 'text/css', the _pydoc.css style + sheet is read and returned if it exits. + + If the content_type is 'text/html', then the result of + get_html_page(url) is returned. + 'b'pydoc_data/_pydoc.css'u'pydoc_data/_pydoc.css'b''u''b' +Pydoc: %s + +%s%s
%s
+'u' +Pydoc: %s + +%s%s
%s
+'b'%s [%s, %s]'u'%s [%s, %s]'b' +
+ Python %s
%s +
+
+ +
+
+ + +
  +
+ + +
+
+
+ 'u' +
+ Python %s
%s +
+
+ +
+
+ + +
  +
+ + +
+
+
+ 'b'Module Index page.'u'Module Index page.'b'Index of Modules'u'Index of Modules'b'

'u'

'b'Built-in Modules'u'Built-in Modules'b'

pydoc by Ka-Ping Yee<ping@lfw.org>'u'

pydoc by Ka-Ping Yee<ping@lfw.org>'b'Index of Modules'u'Index of Modules'b'Search results page.'u'Search results page.'b'Search Results'u'Search Results'b'key = %s'u'key = %s'b'
'u'
'b'Search Results'u'Search Results'b'Index of topic texts available.'u'Index of topic texts available.'b'%s'u'%s'b'INDEX'u'INDEX'b'Topics'u'Topics'b'Index of keywords.'u'Index of keywords.'b'Keywords'u'Keywords'b'Topic or keyword help page.'u'Topic or keyword help page.'b'KEYWORD'u'KEYWORD'b'TOPIC'u'TOPIC'b'

%s
'u'
%s
'b'could not find object'u'could not find object'b'Error'u'Error'b'#bb0000'u'#bb0000'b'Error - %s'u'Error - %s'b'Generate an HTML page for url.'u'Generate an HTML page for url.'b'search?key'u'search?key'b'topic?key'u'topic?key'b'get?key'u'get?key'b'bad pydoc url'u'bad pydoc url'b'unknown content type %r for url %s'u'unknown content type %r for url %s'b'Start the enhanced pydoc Web server and open a Web browser. + + Use port '0' to start the server on an arbitrary port. + Set open_browser to False to suppress opening a browser. + 'u'Start the enhanced pydoc Web server and open a Web browser. + + Use port '0' to start the server on an arbitrary port. + Set open_browser to False to suppress opening a browser. + 'b'Server commands: [b]rowser, [q]uit'u'Server commands: [b]rowser, [q]uit'b'Server ready at'u'Server ready at'b'server> 'u'server> 'b'Server stopped'u'Server stopped'b'Ensures current directory is on returned path, and argv0 directory is not + + Exception: argv0 dir is left alone if it's also pydoc's directory. + + Returns a new path entry list, or None if no adjustment is needed. + 'u'Ensures current directory is on returned path, and argv0 directory is not + + Exception: argv0 dir is left alone if it's also pydoc's directory. + + Returns a new path entry list, or None if no adjustment is needed. + 'b'Ensures current directory is on sys.path, and __main__ directory is not. + + Exception: __main__ dir is left alone if it's also pydoc's directory. + 'u'Ensures current directory is on sys.path, and __main__ directory is not. + + Exception: __main__ dir is left alone if it's also pydoc's directory. + 'b'Command-line interface (looks at sys.argv to decide what to do).'u'Command-line interface (looks at sys.argv to decide what to do).'b'bk:n:p:w'u'bk:n:p:w'b'file %r does not exist'u'file %r does not exist'b'pydoc - the Python documentation tool + +{cmd} ... + Show text documentation on something. may be the name of a + Python keyword, topic, function, module, or package, or a dotted + reference to a class or function within a module or module in a + package. If contains a '{sep}', it is used as the path to a + Python source file to document. If name is 'keywords', 'topics', + or 'modules', a listing of these things is displayed. + +{cmd} -k + Search for a keyword in the synopsis lines of all available modules. + +{cmd} -n + Start an HTTP server with the given hostname (default: localhost). + +{cmd} -p + Start an HTTP server on the given port on the local machine. Port + number 0 can be used to get an arbitrary unused port. + +{cmd} -b + Start an HTTP server on an arbitrary unused port and open a Web browser + to interactively browse documentation. This option can be used in + combination with -n and/or -p. + +{cmd} -w ... + Write out the HTML documentation for a module to a file in the current + directory. If contains a '{sep}', it is treated as a filename; if + it names a directory, documentation is written for all the contents. +'u'pydoc - the Python documentation tool + +{cmd} ... + Show text documentation on something. may be the name of a + Python keyword, topic, function, module, or package, or a dotted + reference to a class or function within a module or module in a + package. If contains a '{sep}', it is used as the path to a + Python source file to document. If name is 'keywords', 'topics', + or 'modules', a listing of these things is displayed. + +{cmd} -k + Search for a keyword in the synopsis lines of all available modules. + +{cmd} -n + Start an HTTP server with the given hostname (default: localhost). + +{cmd} -p + Start an HTTP server on the given port on the local machine. Port + number 0 can be used to get an arbitrary unused port. + +{cmd} -b + Start an HTTP server on an arbitrary unused port and open a Web browser + to interactively browse documentation. This option can be used in + combination with -n and/or -p. + +{cmd} -w ... + Write out the HTML documentation for a module to a file in the current + directory. If contains a '{sep}', it is treated as a filename; if + it names a directory, documentation is written for all the contents. +'u'pydoc'u'expat_2.4.7'EXPAT_VERSIONErrorStringu'ExpatError.__weakref__'xml.parsers.expat.ExpatErrorExpatErroru'xmlparser.AttlistDeclHandler'AttlistDeclHandleru'xmlparser.CharacterDataHandler'u'xmlparser.CommentHandler'u'xmlparser.CurrentByteIndex'CurrentByteIndexu'xmlparser.CurrentColumnNumber'CurrentColumnNumberu'xmlparser.CurrentLineNumber'u'xmlparser.DefaultHandler'DefaultHandleru'xmlparser.DefaultHandlerExpand'u'xmlparser.ElementDeclHandler'ElementDeclHandleru'xmlparser.EndCdataSectionHandler'EndCdataSectionHandleru'xmlparser.EndDoctypeDeclHandler'EndDoctypeDeclHandleru'xmlparser.EndElementHandler'u'xmlparser.EndNamespaceDeclHandler'u'xmlparser.EntityDeclHandler'u'xmlparser.ErrorByteIndex'ErrorByteIndexu'xmlparser.ErrorCode'ErrorCodeu'xmlparser.ErrorColumnNumber'u'xmlparser.ErrorLineNumber'ExternalEntityParserCreateu'xmlparser.ExternalEntityRefHandler'ExternalEntityRefHandlerGetBaseGetInputContextu'xmlparser.NotStandaloneHandler'NotStandaloneHandleru'xmlparser.NotationDeclHandler'NotationDeclHandleru'xmlparser.ProcessingInstructionHandler'SetBaseSetParamEntityParsingu'xmlparser.SkippedEntityHandler'SkippedEntityHandleru'xmlparser.StartCdataSectionHandler'StartCdataSectionHandleru'xmlparser.StartDoctypeDeclHandler'StartDoctypeDeclHandleru'xmlparser.StartElementHandler'u'xmlparser.StartNamespaceDeclHandler'u'xmlparser.UnparsedEntityDeclHandler'UnparsedEntityDeclHandlerUseForeignDTDu'xmlparser.XmlDeclHandler'XmlDeclHandleru'XML parser'u'xmlparser.buffer_size'u'xmlparser.buffer_text'u'xmlparser.buffer_used'buffer_usedu'xmlparser.namespace_prefixes'namespace_prefixesu'xmlparser.ordered_attributes'u'xmlparser.specified_attributes'pyexpat.xmlparserXMLParserTypeXML_PARAM_ENTITY_PARSING_ALWAYSXML_PARAM_ENTITY_PARSING_NEVERXML_PARAM_ENTITY_PARSING_UNLESS_STANDALONEu'Python wrapper for Expat parser.'u'/Users/pwntester/.pyenv/versions/3.8.13/lib/python3.8/lib-dynload/pyexpat.cpython-38-darwin.so'u'pyexpat'u'parsing aborted'XML_ERROR_ABORTEDu'asynchronous entity'XML_ERROR_ASYNC_ENTITYu'reference to external entity in attribute'XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REFu'reference to invalid character number'XML_ERROR_BAD_CHAR_REFu'reference to binary entity'XML_ERROR_BINARY_ENTITY_REFu'cannot change setting once parsing has begun'XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSINGu'duplicate attribute'XML_ERROR_DUPLICATE_ATTRIBUTEu'entity declared in parameter entity'XML_ERROR_ENTITY_DECLARED_IN_PEu'error in processing external entity reference'XML_ERROR_EXTERNAL_ENTITY_HANDLINGu'requested feature requires XML_DTD support in Expat'XML_ERROR_FEATURE_REQUIRES_XML_DTDu'parsing finished'XML_ERROR_FINISHEDu'incomplete markup in parameter entity'XML_ERROR_INCOMPLETE_PEu'encoding specified in XML declaration is incorrect'XML_ERROR_INCORRECT_ENCODINGu'not well-formed (invalid token)'XML_ERROR_INVALID_TOKENu'junk after document element'XML_ERROR_JUNK_AFTER_DOC_ELEMENTu'XML or text declaration not at start of entity'XML_ERROR_MISPLACED_XML_PIu'document is not standalone'XML_ERROR_NOT_STANDALONEu'parser not suspended'XML_ERROR_NOT_SUSPENDEDu'no element found'XML_ERROR_NO_ELEMENTSu'out of memory'XML_ERROR_NO_MEMORYu'illegal parameter entity reference'XML_ERROR_PARAM_ENTITY_REFu'partial character'XML_ERROR_PARTIAL_CHARu'illegal character(s) in public id'XML_ERROR_PUBLICIDu'recursive entity reference'XML_ERROR_RECURSIVE_ENTITY_REFu'parser suspended'XML_ERROR_SUSPENDEDu'cannot suspend in external parameter entity'XML_ERROR_SUSPEND_PEu'syntax error'XML_ERROR_SYNTAXu'mismatched tag'XML_ERROR_TAG_MISMATCHu'text declaration not well-formed'XML_ERROR_TEXT_DECLu'unbound prefix'XML_ERROR_UNBOUND_PREFIXu'unclosed CDATA section'XML_ERROR_UNCLOSED_CDATA_SECTIONu'unclosed token'XML_ERROR_UNCLOSED_TOKENu'must not undeclare prefix'XML_ERROR_UNDECLARING_PREFIXu'undefined entity'XML_ERROR_UNDEFINED_ENTITYu'unexpected parser state - please send a bug report'XML_ERROR_UNEXPECTED_STATEu'unknown encoding'XML_ERROR_UNKNOWN_ENCODINGu'XML declaration not well-formed'XML_ERROR_XML_DECLu'Constants used to describe error conditions.'u'pyexpat.errors'pyexpat.errorsexpat_CAPIu'sizeof(XML_Char)'u'sizeof(XML_LChar)'u'XML_DTD'u'XML_CONTEXT_BYTES'u'XML_NS'u'XML_BLAP_MAX_AMP'u'XML_BLAP_ACT_THRES'featuresXML_CQUANT_NONEXML_CQUANT_OPTXML_CQUANT_PLUSXML_CQUANT_REPXML_CTYPE_ANYXML_CTYPE_CHOICEXML_CTYPE_EMPTYXML_CTYPE_MIXEDXML_CTYPE_NAMEXML_CTYPE_SEQu'Constants used to interpret content model information.'u'pyexpat.model'pyexpat.modelnative_encodingExport the Python grammar and symbols._GRAMMAR_FILEPatternGrammar.txt_PATTERN_GRAMMAR_FILEInitializer. + + Creates an attribute for each grammar symbol (nonterminal), + whose value is the symbol's type (an int >= 256). + lib2to3python_grammar_no_print_statementpython_grammar_no_print_and_exec_statement# The grammar fileb'Export the Python grammar and symbols.'u'Export the Python grammar and symbols.'b'PatternGrammar.txt'u'PatternGrammar.txt'b'Initializer. + + Creates an attribute for each grammar symbol (nonterminal), + whose value is the symbol's type (an int >= 256). + 'u'Initializer. + + Creates an attribute for each grammar symbol (nonterminal), + whose value is the symbol's type (an int >= 256). + 'b'lib2to3'b'print'u'print'u'lib2to3.pygram'u'pygram' +Python parse tree definitions. + +This is a very concrete parse tree; we need to keep every token and +even the comments and whitespace between tokens. + +There's also a pattern matching implementation here. +0x7FFFFFFFBase + Abstract base class for Node and Leaf. + + This provides some default functionality and boilerplate using the + template pattern. + + A node may be a subnode of at most one parent. + was_changedConstructor that prevents Base from being instantiated.Cannot instantiate Base + Compare two nodes for equality. + + This calls the method _eq(). + + Compare two nodes for equality. + + This is called by __eq__ and __ne__. It is only called if the two nodes + have the same type. This must be implemented by the concrete subclass. + Nodes should be considered equal if they have the same structure, + ignoring the prefix string and other context information. + + Return a cloned (deep) copy of self. + + This must be implemented by the concrete subclass. + post_order + Return a post-order iterator for the tree. + + This must be implemented by the concrete subclass. + pre_order + Return a pre-order iterator for the tree. + + This must be implemented by the concrete subclass. + Replace this node with a new one in the parent.l_childrenget_linenoReturn the line number which generated the invocant node. + Remove the node from the tree. Returns the position of the node in its + parent's children before it was removed. + next_sibling + The node immediately following the invocant in their parent's children + list. If the invocant does not have a next sibling, it is None + + The node immediately preceding the invocant in their parent's children + list. If the invocant does not have a previous sibling, it is None. + get_suffix + Return the string immediately following the invocant node. This is + effectively equivalent to node.next_sibling.prefix + next_sibConcrete implementation for interior nodes.fixers_applied + Initializer. + + Takes a type constant (a symbol number >= 256), a sequence of + child nodes, and an optional context keyword argument. + + As a side effect, the parent pointers of the children are updated. + Return a canonical string representation.%s(%s, %r)__unicode__ + Return a pretty string representation. + + This reproduces the input source exactly. + Compare two nodes for equality.Return a cloned (deep) copy of self.Return a post-order iterator for the tree.Return a pre-order iterator for the tree. + The whitespace and comments preceding this node in the input. + set_child + Equivalent to 'node.children[i] = child'. This method also sets the + child's parent attribute appropriately. + + Equivalent to 'node.children.insert(i, child)'. This method also sets + the child's parent attribute appropriately. + append_child + Equivalent to 'node.children.append(child)'. This method also sets the + child's parent attribute appropriately. + Concrete implementation for leaf nodes. + Initializer. + + Takes a type constant (a token number < 256), a string value, and an + optional context keyword argument. + %s(%r, %r) + The whitespace and comments preceding this token in the input. + grraw_node + Convert raw node information to a Node or Leaf instance. + + This is passed to the parser driver which calls it whenever a reduction of a + grammar rule produces a new complete node, so that the tree is build + strictly bottom-up. + BasePattern + A pattern is a tree matching pattern. + + It looks for a specific node type (token or symbol), and + optionally for a specific content. + + This is an abstract base class. There are three concrete + subclasses: + + - LeafPattern matches a single leaf node; + - NodePattern matches a single node (usually non-leaf); + - WildcardPattern matches a sequence of nodes of variable length. + Constructor that prevents BasePattern from being instantiated.Cannot instantiate BasePattern + A subclass can define this as a hook for optimizations. + + Returns either self or another node with the same effect. + + Does this pattern exactly match a node? + + Returns True if it matches, False if not. + + If results is not None, it must be a dict which will be + updated with the nodes matching named subpatterns. + + Default implementation for non-wildcard patterns. + _submatchmatch_seq + Does this pattern exactly match a sequence of nodes? + + Default implementation for non-wildcard patterns. + generate_matches + Generator yielding all matches for this pattern. + + Default implementation for non-wildcard patterns. + + Initializer. Takes optional type, content, and name. + + The type, if given must be a token type (< 256). If not given, + this matches any *leaf* node; the content may still be required. + + The content, if given, must be a string. + + If a name is given, the matching node is stored in the results + dict under that key. + Override match() to insist on a leaf node. + Match the pattern's content to the node's children. + + This assumes the node type matches and self.content is not None. + + Returns True if it matches, False if not. + + If results is not None, it must be a dict which will be + updated with the nodes matching named subpatterns. + + When returning False, the results dict may still be updated. + wildcards + Initializer. Takes optional type, content, and name. + + The type, if given, must be a symbol type (>= 256). If the + type is None this matches *any* single node (leaf or not), + except if content is not None, in which it only matches + non-leaf nodes that also match the content pattern. + + The content, if not None, must be a sequence of Patterns that + must match the node's children exactly. If the content is + given, the type must not be None. + + If a name is given, the matching node is stored in the results + dict under that key. + + A wildcard pattern can match zero or more nodes. + + This has all the flexibility needed to implement patterns like: + + .* .+ .? .{m,n} + (a b c | d e | f) + (...)* (...)+ (...)? (...){m,n} + + except it always uses non-greedy matching. + + Initializer. + + Args: + content: optional sequence of subsequences of patterns; + if absent, matches one node; + if present, each subsequence is an alternative [*] + min: optional minimum number of times to match, default 0 + max: optional maximum number of times to match, default HUGE + name: optional name assigned to this match + + [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is + equivalent to (a b c | d e | f g h); if content is None, + this is equivalent to '.' in regular expression terms. + The min and max parameters work as follows: + min=0, max=maxint: .* + min=1, max=maxint: .+ + min=0, max=1: .? + min=1, max=1: . + If content is not None, replace the dot with the parenthesized + list of alternatives, e.g. (a b c | d e | f g h)* + Optimize certain stacked wildcard patterns.Does this pattern exactly match a node?Does this pattern exactly match a sequence of nodes? + Generator yielding matches for a sequence of nodes. + + Args: + nodes: sequence of nodes + + Yields: + (count, results) tuples where: + count: the match comprises nodes[:count]; + results: dict containing named submatches. + bare_name_bare_name_matchessave_stderr_recursive_matches_iterative_matchesHelper to iteratively yield the matches.nodelennew_resultsc0r0r1Special optimized matcher for bare_name.Helper to recursively yield the matches. + Initializer. + + The argument is either a pattern or None. If it is None, this + only matches an empty sequence (effectively '$' in regex + lingo). If it is not None, this matches whenever the argument + pattern doesn't have any matches. + + Generator yielding matches for a sequence of patterns and nodes. + + Args: + patterns: a sequence of patterns + nodes: a sequence of nodes + + Yields: + (count, results) tuples where: + count: the entire sequence of patterns matches nodes[:count]; + results: dict containing named submatches. + # maximum repeat count, default max# Default values for instance variables# int: token number (< 256) or symbol number (>= 256)# Parent node pointer, or None# Tuple of subnodes# Can't use index(); we need to test by identity# Whitespace and comments preceding this token in the input# Line where this token starts in the input# Column where this token tarts in the input# If there's exactly one child, return that child instead of# creating a new node.# Defaults for instance variables# Node type (token if < 256, symbol if >= 256)# Optional content matching pattern# Optional name used to store match in results dict# Protect against alterations# Check sanity of alternatives# Can't have zero alternatives# Can have empty alternatives# Shortcut for special case (see __init__.__doc__)# The reason for this is that hitting the recursion limit usually# results in some ugly messages about how RuntimeErrors are being# ignored. We only have to do this on CPython, though, because other# implementations don't have this nasty bug in the first place.# We fall back to the iterative pattern matching scheme if the recursive# scheme hits the recursion limit.# generate matches that use just one alt from self.content# for each match, iterate down the nodes# stop if the entire set of nodes has been matched# We never match a node in its entirety# We only match an empty sequence of nodes in its entirety# Return a match if there is an empty sequence# Return a match if the argument pattern has no matchesb' +Python parse tree definitions. + +This is a very concrete parse tree; we need to keep every token and +even the comments and whitespace between tokens. + +There's also a pattern matching implementation here. +'u' +Python parse tree definitions. + +This is a very concrete parse tree; we need to keep every token and +even the comments and whitespace between tokens. + +There's also a pattern matching implementation here. +'b' + Abstract base class for Node and Leaf. + + This provides some default functionality and boilerplate using the + template pattern. + + A node may be a subnode of at most one parent. + 'u' + Abstract base class for Node and Leaf. + + This provides some default functionality and boilerplate using the + template pattern. + + A node may be a subnode of at most one parent. + 'b'Constructor that prevents Base from being instantiated.'u'Constructor that prevents Base from being instantiated.'b'Cannot instantiate Base'u'Cannot instantiate Base'b' + Compare two nodes for equality. + + This calls the method _eq(). + 'u' + Compare two nodes for equality. + + This calls the method _eq(). + 'b' + Compare two nodes for equality. + + This is called by __eq__ and __ne__. It is only called if the two nodes + have the same type. This must be implemented by the concrete subclass. + Nodes should be considered equal if they have the same structure, + ignoring the prefix string and other context information. + 'u' + Compare two nodes for equality. + + This is called by __eq__ and __ne__. It is only called if the two nodes + have the same type. This must be implemented by the concrete subclass. + Nodes should be considered equal if they have the same structure, + ignoring the prefix string and other context information. + 'b' + Return a cloned (deep) copy of self. + + This must be implemented by the concrete subclass. + 'u' + Return a cloned (deep) copy of self. + + This must be implemented by the concrete subclass. + 'b' + Return a post-order iterator for the tree. + + This must be implemented by the concrete subclass. + 'u' + Return a post-order iterator for the tree. + + This must be implemented by the concrete subclass. + 'b' + Return a pre-order iterator for the tree. + + This must be implemented by the concrete subclass. + 'u' + Return a pre-order iterator for the tree. + + This must be implemented by the concrete subclass. + 'b'Replace this node with a new one in the parent.'u'Replace this node with a new one in the parent.'b'Return the line number which generated the invocant node.'u'Return the line number which generated the invocant node.'b' + Remove the node from the tree. Returns the position of the node in its + parent's children before it was removed. + 'u' + Remove the node from the tree. Returns the position of the node in its + parent's children before it was removed. + 'b' + The node immediately following the invocant in their parent's children + list. If the invocant does not have a next sibling, it is None + 'u' + The node immediately following the invocant in their parent's children + list. If the invocant does not have a next sibling, it is None + 'b' + The node immediately preceding the invocant in their parent's children + list. If the invocant does not have a previous sibling, it is None. + 'u' + The node immediately preceding the invocant in their parent's children + list. If the invocant does not have a previous sibling, it is None. + 'b' + Return the string immediately following the invocant node. This is + effectively equivalent to node.next_sibling.prefix + 'u' + Return the string immediately following the invocant node. This is + effectively equivalent to node.next_sibling.prefix + 'b'Concrete implementation for interior nodes.'u'Concrete implementation for interior nodes.'b' + Initializer. + + Takes a type constant (a symbol number >= 256), a sequence of + child nodes, and an optional context keyword argument. + + As a side effect, the parent pointers of the children are updated. + 'u' + Initializer. + + Takes a type constant (a symbol number >= 256), a sequence of + child nodes, and an optional context keyword argument. + + As a side effect, the parent pointers of the children are updated. + 'b'Return a canonical string representation.'u'Return a canonical string representation.'b'%s(%s, %r)'u'%s(%s, %r)'b' + Return a pretty string representation. + + This reproduces the input source exactly. + 'u' + Return a pretty string representation. + + This reproduces the input source exactly. + 'b'Compare two nodes for equality.'u'Compare two nodes for equality.'b'Return a cloned (deep) copy of self.'u'Return a cloned (deep) copy of self.'b'Return a post-order iterator for the tree.'u'Return a post-order iterator for the tree.'b'Return a pre-order iterator for the tree.'u'Return a pre-order iterator for the tree.'b' + The whitespace and comments preceding this node in the input. + 'u' + The whitespace and comments preceding this node in the input. + 'b' + Equivalent to 'node.children[i] = child'. This method also sets the + child's parent attribute appropriately. + 'u' + Equivalent to 'node.children[i] = child'. This method also sets the + child's parent attribute appropriately. + 'b' + Equivalent to 'node.children.insert(i, child)'. This method also sets + the child's parent attribute appropriately. + 'u' + Equivalent to 'node.children.insert(i, child)'. This method also sets + the child's parent attribute appropriately. + 'b' + Equivalent to 'node.children.append(child)'. This method also sets the + child's parent attribute appropriately. + 'u' + Equivalent to 'node.children.append(child)'. This method also sets the + child's parent attribute appropriately. + 'b'Concrete implementation for leaf nodes.'u'Concrete implementation for leaf nodes.'b' + Initializer. + + Takes a type constant (a token number < 256), a string value, and an + optional context keyword argument. + 'u' + Initializer. + + Takes a type constant (a token number < 256), a string value, and an + optional context keyword argument. + 'b'%s(%r, %r)'u'%s(%r, %r)'b' + The whitespace and comments preceding this token in the input. + 'u' + The whitespace and comments preceding this token in the input. + 'b' + Convert raw node information to a Node or Leaf instance. + + This is passed to the parser driver which calls it whenever a reduction of a + grammar rule produces a new complete node, so that the tree is build + strictly bottom-up. + 'u' + Convert raw node information to a Node or Leaf instance. + + This is passed to the parser driver which calls it whenever a reduction of a + grammar rule produces a new complete node, so that the tree is build + strictly bottom-up. + 'b' + A pattern is a tree matching pattern. + + It looks for a specific node type (token or symbol), and + optionally for a specific content. + + This is an abstract base class. There are three concrete + subclasses: + + - LeafPattern matches a single leaf node; + - NodePattern matches a single node (usually non-leaf); + - WildcardPattern matches a sequence of nodes of variable length. + 'u' + A pattern is a tree matching pattern. + + It looks for a specific node type (token or symbol), and + optionally for a specific content. + + This is an abstract base class. There are three concrete + subclasses: + + - LeafPattern matches a single leaf node; + - NodePattern matches a single node (usually non-leaf); + - WildcardPattern matches a sequence of nodes of variable length. + 'b'Constructor that prevents BasePattern from being instantiated.'u'Constructor that prevents BasePattern from being instantiated.'b'Cannot instantiate BasePattern'u'Cannot instantiate BasePattern'b' + A subclass can define this as a hook for optimizations. + + Returns either self or another node with the same effect. + 'u' + A subclass can define this as a hook for optimizations. + + Returns either self or another node with the same effect. + 'b' + Does this pattern exactly match a node? + + Returns True if it matches, False if not. + + If results is not None, it must be a dict which will be + updated with the nodes matching named subpatterns. + + Default implementation for non-wildcard patterns. + 'u' + Does this pattern exactly match a node? + + Returns True if it matches, False if not. + + If results is not None, it must be a dict which will be + updated with the nodes matching named subpatterns. + + Default implementation for non-wildcard patterns. + 'b' + Does this pattern exactly match a sequence of nodes? + + Default implementation for non-wildcard patterns. + 'u' + Does this pattern exactly match a sequence of nodes? + + Default implementation for non-wildcard patterns. + 'b' + Generator yielding all matches for this pattern. + + Default implementation for non-wildcard patterns. + 'u' + Generator yielding all matches for this pattern. + + Default implementation for non-wildcard patterns. + 'b' + Initializer. Takes optional type, content, and name. + + The type, if given must be a token type (< 256). If not given, + this matches any *leaf* node; the content may still be required. + + The content, if given, must be a string. + + If a name is given, the matching node is stored in the results + dict under that key. + 'u' + Initializer. Takes optional type, content, and name. + + The type, if given must be a token type (< 256). If not given, + this matches any *leaf* node; the content may still be required. + + The content, if given, must be a string. + + If a name is given, the matching node is stored in the results + dict under that key. + 'b'Override match() to insist on a leaf node.'u'Override match() to insist on a leaf node.'b' + Match the pattern's content to the node's children. + + This assumes the node type matches and self.content is not None. + + Returns True if it matches, False if not. + + If results is not None, it must be a dict which will be + updated with the nodes matching named subpatterns. + + When returning False, the results dict may still be updated. + 'u' + Match the pattern's content to the node's children. + + This assumes the node type matches and self.content is not None. + + Returns True if it matches, False if not. + + If results is not None, it must be a dict which will be + updated with the nodes matching named subpatterns. + + When returning False, the results dict may still be updated. + 'b' + Initializer. Takes optional type, content, and name. + + The type, if given, must be a symbol type (>= 256). If the + type is None this matches *any* single node (leaf or not), + except if content is not None, in which it only matches + non-leaf nodes that also match the content pattern. + + The content, if not None, must be a sequence of Patterns that + must match the node's children exactly. If the content is + given, the type must not be None. + + If a name is given, the matching node is stored in the results + dict under that key. + 'u' + Initializer. Takes optional type, content, and name. + + The type, if given, must be a symbol type (>= 256). If the + type is None this matches *any* single node (leaf or not), + except if content is not None, in which it only matches + non-leaf nodes that also match the content pattern. + + The content, if not None, must be a sequence of Patterns that + must match the node's children exactly. If the content is + given, the type must not be None. + + If a name is given, the matching node is stored in the results + dict under that key. + 'b' + A wildcard pattern can match zero or more nodes. + + This has all the flexibility needed to implement patterns like: + + .* .+ .? .{m,n} + (a b c | d e | f) + (...)* (...)+ (...)? (...){m,n} + + except it always uses non-greedy matching. + 'u' + A wildcard pattern can match zero or more nodes. + + This has all the flexibility needed to implement patterns like: + + .* .+ .? .{m,n} + (a b c | d e | f) + (...)* (...)+ (...)? (...){m,n} + + except it always uses non-greedy matching. + 'b' + Initializer. + + Args: + content: optional sequence of subsequences of patterns; + if absent, matches one node; + if present, each subsequence is an alternative [*] + min: optional minimum number of times to match, default 0 + max: optional maximum number of times to match, default HUGE + name: optional name assigned to this match + + [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is + equivalent to (a b c | d e | f g h); if content is None, + this is equivalent to '.' in regular expression terms. + The min and max parameters work as follows: + min=0, max=maxint: .* + min=1, max=maxint: .+ + min=0, max=1: .? + min=1, max=1: . + If content is not None, replace the dot with the parenthesized + list of alternatives, e.g. (a b c | d e | f g h)* + 'u' + Initializer. + + Args: + content: optional sequence of subsequences of patterns; + if absent, matches one node; + if present, each subsequence is an alternative [*] + min: optional minimum number of times to match, default 0 + max: optional maximum number of times to match, default HUGE + name: optional name assigned to this match + + [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is + equivalent to (a b c | d e | f g h); if content is None, + this is equivalent to '.' in regular expression terms. + The min and max parameters work as follows: + min=0, max=maxint: .* + min=1, max=maxint: .+ + min=0, max=1: .? + min=1, max=1: . + If content is not None, replace the dot with the parenthesized + list of alternatives, e.g. (a b c | d e | f g h)* + 'b'Optimize certain stacked wildcard patterns.'u'Optimize certain stacked wildcard patterns.'b'Does this pattern exactly match a node?'u'Does this pattern exactly match a node?'b'Does this pattern exactly match a sequence of nodes?'u'Does this pattern exactly match a sequence of nodes?'b' + Generator yielding matches for a sequence of nodes. + + Args: + nodes: sequence of nodes + + Yields: + (count, results) tuples where: + count: the match comprises nodes[:count]; + results: dict containing named submatches. + 'u' + Generator yielding matches for a sequence of nodes. + + Args: + nodes: sequence of nodes + + Yields: + (count, results) tuples where: + count: the match comprises nodes[:count]; + results: dict containing named submatches. + 'b'bare_name'u'bare_name'b'getrefcount'u'getrefcount'b'Helper to iteratively yield the matches.'u'Helper to iteratively yield the matches.'b'Special optimized matcher for bare_name.'u'Special optimized matcher for bare_name.'b'Helper to recursively yield the matches.'u'Helper to recursively yield the matches.'b' + Initializer. + + The argument is either a pattern or None. If it is None, this + only matches an empty sequence (effectively '$' in regex + lingo). If it is not None, this matches whenever the argument + pattern doesn't have any matches. + 'u' + Initializer. + + The argument is either a pattern or None. If it is None, this + only matches an empty sequence (effectively '$' in regex + lingo). If it is not None, this matches whenever the argument + pattern doesn't have any matches. + 'b' + Generator yielding matches for a sequence of patterns and nodes. + + Args: + patterns: a sequence of patterns + nodes: a sequence of nodes + + Yields: + (count, results) tuples where: + count: the entire sequence of patterns matches nodes[:count]; + results: dict containing named submatches. + 'u' + Generator yielding matches for a sequence of patterns and nodes. + + Args: + patterns: a sequence of patterns + nodes: a sequence of nodes + + Yields: + (count, results) tuples where: + count: the entire sequence of patterns matches nodes[:count]; + results: dict containing named submatches. + 'u'lib2to3.pytree'u'pytree'A multi-producer, multi-consumer queue.PriorityQueueLifoQueueException raised by Queue.get(block=0)/get_nowait().Exception raised by Queue.put(block=0)/put_nowait().Create a queue object with a given maximum size. + + If maxsize is <= 0, the queue size is infinite. + _initmutexnot_emptynot_fullall_tasks_doneunfinished_tasksIndicate that a formerly enqueued task is complete. + + Used by Queue consumer threads. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items + have been processed (meaning that a task_done() call was received + for every item that had been put() into the queue). + + Raises a ValueError if called more times than there were items + placed in the queue. + unfinishedtask_done() called too many timesBlocks until all items in the Queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer thread calls task_done() + to indicate the item was retrieved and all work on it is complete. + + When the count of unfinished tasks drops to zero, join() unblocks. + Return the approximate size of the queue (not reliable!)._qsizeReturn True if the queue is empty, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() == 0 + as a direct substitute, but be aware that either approach risks a race + condition where a queue can grow before the result of empty() or + qsize() can be used. + + To create code that needs to wait for all queued tasks to be + completed, the preferred technique is to use the join() method. + Return True if the queue is full, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() >= n + as a direct substitute, but be aware that either approach risks a race + condition where a queue can shrink before the result of full() or + qsize() can be used. + Put an item into the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until a free slot is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Full exception if no free slot was available within that time. + Otherwise ('block' is false), put an item on the queue if a free slot + is immediately available, else raise the Full exception ('timeout' + is ignored in that case). + 'timeout' must be a non-negative number_putRemove and return an item from the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until an item is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Empty exception if no item was available within that time. + Otherwise ('block' is false), return an item if one is immediately + available, else raise the Empty exception ('timeout' is ignored + in that case). + _getPut an item into the queue without blocking. + + Only enqueue the item if a free slot is immediately available. + Otherwise raise the Full exception. + Remove and return an item from the queue without blocking. + + Only get an item if one is immediately available. Otherwise + raise the Empty exception. + Variant of Queue that retrieves open entries in priority order (lowest first). + + Entries are typically tuples of the form: (priority number, data). + Variant of Queue that retrieves most recently added entries first._PySimpleQueueSimple, unbounded FIFO queue. + + This pure Python implementation is not reentrant. + Put the item on the queue. + + The optional 'block' and 'timeout' arguments are ignored, as this method + never blocks. They are provided for compatibility with the Queue class. + Put an item into the queue without blocking. + + This is exactly equivalent to `put(item)` and is only provided + for compatibility with the Queue class. + Return True if the queue is empty, False otherwise (not reliable!).# mutex must be held whenever the queue is mutating. All methods# that acquire mutex must release it before returning. mutex# is shared between the three conditions, so acquiring and# releasing the conditions also acquires and releases mutex.# Notify not_empty whenever an item is added to the queue; a# thread waiting to get is notified then.# Notify not_full whenever an item is removed from the queue;# a thread waiting to put is notified then.# Notify all_tasks_done whenever the number of unfinished tasks# drops to zero; thread waiting to join() is notified to resume# Override these methods to implement other queue organizations# (e.g. stack or priority queue).# These will only be called with appropriate locks held# Initialize the queue representation# Put a new item in the queue# Get an item from the queue# Note: while this pure Python version provides fairness# (by using a threading.Semaphore which is itself fair, being based# on threading.Condition), fairness is not part of the API contract.# This allows the C version to use a different implementation.b'A multi-producer, multi-consumer queue.'u'A multi-producer, multi-consumer queue.'b'Empty'u'Empty'b'Full'u'Full'b'PriorityQueue'u'PriorityQueue'b'LifoQueue'u'LifoQueue'b'SimpleQueue'u'SimpleQueue'b'Exception raised by Queue.get(block=0)/get_nowait().'b'Exception raised by Queue.put(block=0)/put_nowait().'u'Exception raised by Queue.put(block=0)/put_nowait().'b'Create a queue object with a given maximum size. + + If maxsize is <= 0, the queue size is infinite. + 'u'Create a queue object with a given maximum size. + + If maxsize is <= 0, the queue size is infinite. + 'b'Indicate that a formerly enqueued task is complete. + + Used by Queue consumer threads. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items + have been processed (meaning that a task_done() call was received + for every item that had been put() into the queue). + + Raises a ValueError if called more times than there were items + placed in the queue. + 'u'Indicate that a formerly enqueued task is complete. + + Used by Queue consumer threads. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items + have been processed (meaning that a task_done() call was received + for every item that had been put() into the queue). + + Raises a ValueError if called more times than there were items + placed in the queue. + 'b'task_done() called too many times'u'task_done() called too many times'b'Blocks until all items in the Queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer thread calls task_done() + to indicate the item was retrieved and all work on it is complete. + + When the count of unfinished tasks drops to zero, join() unblocks. + 'u'Blocks until all items in the Queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer thread calls task_done() + to indicate the item was retrieved and all work on it is complete. + + When the count of unfinished tasks drops to zero, join() unblocks. + 'b'Return the approximate size of the queue (not reliable!).'u'Return the approximate size of the queue (not reliable!).'b'Return True if the queue is empty, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() == 0 + as a direct substitute, but be aware that either approach risks a race + condition where a queue can grow before the result of empty() or + qsize() can be used. + + To create code that needs to wait for all queued tasks to be + completed, the preferred technique is to use the join() method. + 'u'Return True if the queue is empty, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() == 0 + as a direct substitute, but be aware that either approach risks a race + condition where a queue can grow before the result of empty() or + qsize() can be used. + + To create code that needs to wait for all queued tasks to be + completed, the preferred technique is to use the join() method. + 'b'Return True if the queue is full, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() >= n + as a direct substitute, but be aware that either approach risks a race + condition where a queue can shrink before the result of full() or + qsize() can be used. + 'u'Return True if the queue is full, False otherwise (not reliable!). + + This method is likely to be removed at some point. Use qsize() >= n + as a direct substitute, but be aware that either approach risks a race + condition where a queue can shrink before the result of full() or + qsize() can be used. + 'b'Put an item into the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until a free slot is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Full exception if no free slot was available within that time. + Otherwise ('block' is false), put an item on the queue if a free slot + is immediately available, else raise the Full exception ('timeout' + is ignored in that case). + 'u'Put an item into the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until a free slot is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Full exception if no free slot was available within that time. + Otherwise ('block' is false), put an item on the queue if a free slot + is immediately available, else raise the Full exception ('timeout' + is ignored in that case). + 'b''timeout' must be a non-negative number'u''timeout' must be a non-negative number'b'Remove and return an item from the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until an item is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Empty exception if no item was available within that time. + Otherwise ('block' is false), return an item if one is immediately + available, else raise the Empty exception ('timeout' is ignored + in that case). + 'u'Remove and return an item from the queue. + + If optional args 'block' is true and 'timeout' is None (the default), + block if necessary until an item is available. If 'timeout' is + a non-negative number, it blocks at most 'timeout' seconds and raises + the Empty exception if no item was available within that time. + Otherwise ('block' is false), return an item if one is immediately + available, else raise the Empty exception ('timeout' is ignored + in that case). + 'b'Put an item into the queue without blocking. + + Only enqueue the item if a free slot is immediately available. + Otherwise raise the Full exception. + 'u'Put an item into the queue without blocking. + + Only enqueue the item if a free slot is immediately available. + Otherwise raise the Full exception. + 'b'Remove and return an item from the queue without blocking. + + Only get an item if one is immediately available. Otherwise + raise the Empty exception. + 'u'Remove and return an item from the queue without blocking. + + Only get an item if one is immediately available. Otherwise + raise the Empty exception. + 'b'Variant of Queue that retrieves open entries in priority order (lowest first). + + Entries are typically tuples of the form: (priority number, data). + 'u'Variant of Queue that retrieves open entries in priority order (lowest first). + + Entries are typically tuples of the form: (priority number, data). + 'b'Variant of Queue that retrieves most recently added entries first.'u'Variant of Queue that retrieves most recently added entries first.'b'Simple, unbounded FIFO queue. + + This pure Python implementation is not reentrant. + 'u'Simple, unbounded FIFO queue. + + This pure Python implementation is not reentrant. + 'b'Put the item on the queue. + + The optional 'block' and 'timeout' arguments are ignored, as this method + never blocks. They are provided for compatibility with the Queue class. + 'u'Put the item on the queue. + + The optional 'block' and 'timeout' arguments are ignored, as this method + never blocks. They are provided for compatibility with the Queue class. + 'b'Put an item into the queue without blocking. + + This is exactly equivalent to `put(item)` and is only provided + for compatibility with the Queue class. + 'u'Put an item into the queue without blocking. + + This is exactly equivalent to `put(item)` and is only provided + for compatibility with the Queue class. + 'b'Return True if the queue is empty, False otherwise (not reliable!).'u'Return True if the queue is empty, False otherwise (not reliable!).'register_after_forkis_exiting_maxsize_rlock_opid_wlock_semQueue._after_fork()_notempty_jointhread_joincancelledQueue _start_thread_semlockQueue.join_thread()Queue {0!r} not closedcancel_join_threadQueue.cancel_join_thread()Queue._start_thread()_feedQueueFeederThreaddoing self._thread.start()... done self._thread.start()_finalize_join_finalize_closetwrjoining queue thread... queue thread joined... queue thread already deadnotemptytelling queue thread to quitwritelockignore_epipequeue_semstarting thread to feed data to pipenacquirenreleasenwaitbpopleftwacquirewreleasefeeder thread got sentinel -- exitingerror in queue thread: %s + Private API hook called when feeding data in the background thread + raises an exception. For overriding by concurrent.futures. + _unfinished_tasks_cond# Module implementing queues# multiprocessing/queues.py# Queue type using a pipe, buffer and thread# Can raise ImportError (see issues #3770 and #23400)# For use by concurrent.futures# unserialize the data after having released the lock# Raises NotImplementedError on Mac OSX because of broken sem_getvalue()# Start thread which transfers data from buffer to pipe# Send sentinel to the thread queue object when garbage collected# serialize the data before acquiring the lock# Since this runs in a daemon thread the resources it uses# may be become unusable while the process is cleaning up.# We ignore errors which happen after the process has# started to cleanup.# Since the object has not been sent in the queue, we need# to decrease the size of the queue. The error acts as# if the object had been silently removed from the queue# and this step is necessary to have a properly working# queue.# A queue type which also supports join() and task_done() methods# Note that if you do not call task_done() for each finished task then# eventually the counter's semaphore may overflow causing Bad Things# to happen.# Simplified Queue type -- really just a locked pipe# writes to a message oriented win32 pipe are atomicb'JoinableQueue'u'JoinableQueue'b'Queue._after_fork()'u'Queue._after_fork()'b'Queue 'u'Queue 'b'Queue.join_thread()'u'Queue.join_thread()'b'Queue {0!r} not closed'u'Queue {0!r} not closed'b'Queue.cancel_join_thread()'u'Queue.cancel_join_thread()'b'Queue._start_thread()'u'Queue._start_thread()'b'QueueFeederThread'u'QueueFeederThread'b'doing self._thread.start()'u'doing self._thread.start()'b'... done self._thread.start()'u'... done self._thread.start()'b'joining queue thread'u'joining queue thread'b'... queue thread joined'u'... queue thread joined'b'... queue thread already dead'u'... queue thread already dead'b'telling queue thread to quit'u'telling queue thread to quit'b'starting thread to feed data to pipe'u'starting thread to feed data to pipe'b'feeder thread got sentinel -- exiting'u'feeder thread got sentinel -- exiting'b'error in queue thread: %s'u'error in queue thread: %s'b' + Private API hook called when feeding data in the background thread + raises an exception. For overriding by concurrent.futures. + 'u' + Private API hook called when feeding data in the background thread + raises an exception. For overriding by concurrent.futures. + 'u'multiprocessing.queues'u'queues'QueueFullQueueEmptyRaised when Queue.get_nowait() is called on an empty Queue.Raised when the Queue.put_nowait() method is called on a full Queue.A queue, useful for coordinating producer and consumer coroutines. + + If maxsize is less than or equal to zero, the queue size is infinite. If it + is an integer greater than 0, then "await put()" will block when the + queue reaches maxsize, until an item is removed by get(). + + Unlike the standard library Queue, you can reliably know this Queue's size + with qsize(), since your single-threaded asyncio application won't be + interrupted between calling qsize() and doing an operation on the Queue. + _getters_putters_wakeup_nextmaxsize= _queue= _getters[ _putters[ tasks=Number of items in the queue.Number of items allowed in the queue.Return True if the queue is empty, False otherwise.Return True if there are maxsize items in the queue. + + Note: if the Queue was initialized with maxsize=0 (the default), + then full() is never True. + Put an item into the queue. + + Put an item into the queue. If the queue is full, wait until a free + slot is available before adding item. + putterPut an item into the queue without blocking. + + If no free slot is immediately available, raise QueueFull. + Remove and return an item from the queue. + + If queue is empty, wait until an item is available. + Remove and return an item from the queue. + + Return an item if one is immediately available, else raise QueueEmpty. + Indicate that a formerly enqueued task is complete. + + Used by queue consumers. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items have + been processed (meaning that a task_done() call was received for every + item that had been put() into the queue). + + Raises ValueError if called more times than there were items placed in + the queue. + Block until all items in the queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer calls task_done() to + indicate that the item was retrieved and all work on it is complete. + When the count of unfinished tasks drops to zero, join() unblocks. + A subclass of Queue; retrieves entries in priority order (lowest first). + + Entries are typically tuples of the form: (priority number, data). + A subclass of Queue that retrieves most recently added entries first.# Futures.# These three are overridable in subclasses.# End of the overridable methods.# Wake up the next waiter (if any) that isn't cancelled.# Just in case putter is not done yet.# Clean self._putters from canceled putters.# The putter could be removed from self._putters by a# previous get_nowait call.# We were woken up by get_nowait(), but can't take# the call. Wake up the next in line.# Just in case getter is not done yet.# Clean self._getters from canceled getters.# The getter could be removed from self._getters by a# previous put_nowait call.# We were woken up by put_nowait(), but can't takeb'QueueFull'u'QueueFull'b'QueueEmpty'u'QueueEmpty'b'Raised when Queue.get_nowait() is called on an empty Queue.'u'Raised when Queue.get_nowait() is called on an empty Queue.'b'Raised when the Queue.put_nowait() method is called on a full Queue.'u'Raised when the Queue.put_nowait() method is called on a full Queue.'b'A queue, useful for coordinating producer and consumer coroutines. + + If maxsize is less than or equal to zero, the queue size is infinite. If it + is an integer greater than 0, then "await put()" will block when the + queue reaches maxsize, until an item is removed by get(). + + Unlike the standard library Queue, you can reliably know this Queue's size + with qsize(), since your single-threaded asyncio application won't be + interrupted between calling qsize() and doing an operation on the Queue. + 'u'A queue, useful for coordinating producer and consumer coroutines. + + If maxsize is less than or equal to zero, the queue size is infinite. If it + is an integer greater than 0, then "await put()" will block when the + queue reaches maxsize, until an item is removed by get(). + + Unlike the standard library Queue, you can reliably know this Queue's size + with qsize(), since your single-threaded asyncio application won't be + interrupted between calling qsize() and doing an operation on the Queue. + 'b'maxsize='u'maxsize='b'_queue'b' _queue='u' _queue='b' _getters['u' _getters['b' _putters['u' _putters['b' tasks='u' tasks='b'Number of items in the queue.'u'Number of items in the queue.'b'Number of items allowed in the queue.'u'Number of items allowed in the queue.'b'Return True if the queue is empty, False otherwise.'u'Return True if the queue is empty, False otherwise.'b'Return True if there are maxsize items in the queue. + + Note: if the Queue was initialized with maxsize=0 (the default), + then full() is never True. + 'u'Return True if there are maxsize items in the queue. + + Note: if the Queue was initialized with maxsize=0 (the default), + then full() is never True. + 'b'Put an item into the queue. + + Put an item into the queue. If the queue is full, wait until a free + slot is available before adding item. + 'u'Put an item into the queue. + + Put an item into the queue. If the queue is full, wait until a free + slot is available before adding item. + 'b'Put an item into the queue without blocking. + + If no free slot is immediately available, raise QueueFull. + 'u'Put an item into the queue without blocking. + + If no free slot is immediately available, raise QueueFull. + 'b'Remove and return an item from the queue. + + If queue is empty, wait until an item is available. + 'u'Remove and return an item from the queue. + + If queue is empty, wait until an item is available. + 'b'Remove and return an item from the queue. + + Return an item if one is immediately available, else raise QueueEmpty. + 'u'Remove and return an item from the queue. + + Return an item if one is immediately available, else raise QueueEmpty. + 'b'Indicate that a formerly enqueued task is complete. + + Used by queue consumers. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items have + been processed (meaning that a task_done() call was received for every + item that had been put() into the queue). + + Raises ValueError if called more times than there were items placed in + the queue. + 'u'Indicate that a formerly enqueued task is complete. + + Used by queue consumers. For each get() used to fetch a task, + a subsequent call to task_done() tells the queue that the processing + on the task is complete. + + If a join() is currently blocking, it will resume when all items have + been processed (meaning that a task_done() call was received for every + item that had been put() into the queue). + + Raises ValueError if called more times than there were items placed in + the queue. + 'b'Block until all items in the queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer calls task_done() to + indicate that the item was retrieved and all work on it is complete. + When the count of unfinished tasks drops to zero, join() unblocks. + 'u'Block until all items in the queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the + queue. The count goes down whenever a consumer calls task_done() to + indicate that the item was retrieved and all work on it is complete. + When the count of unfinished tasks drops to zero, join() unblocks. + 'b'A subclass of Queue; retrieves entries in priority order (lowest first). + + Entries are typically tuples of the form: (priority number, data). + 'u'A subclass of Queue; retrieves entries in priority order (lowest first). + + Entries are typically tuples of the form: (priority number, data). + 'b'A subclass of Queue that retrieves most recently added entries first.'u'A subclass of Queue that retrieves most recently added entries first.'u'asyncio.queues'Conversions to/from quoted-printable transport encoding as per RFC 1521.ESCAPE0123456789ABCDEFHEXneedsquotingDecide whether a particular byte ordinal needs to be quoted. + + The 'quotetabs' flag indicates whether embedded tabs and spaces should be + quoted. Note that line-ending tabs and spaces are always encoded, as per + RFC 1521. + Quote a single character.Read 'input', apply quoted-printable encoding, and write to 'output'. + + 'input' and 'output' are binary file objects. The 'quotetabs' flag + indicates whether embedded tabs and spaces should be quoted. Note that + line-ending tabs and spaces are always encoded, as per RFC 1521. + The 'header' flag indicates whether we are encoding spaces as _ as per RFC + 1522.odatalineEndprevlineoutlinethisline= +infpoutfpRead 'input', apply quoted-printable decoding, and write to 'output'. + 'input' and 'output' are binary file objects. + If 'header' is true, decode underscore as space (per RFC 1522). ishexunhexReturn true if the byte ordinal 'c' is a hexadecimal digit in ASCII.Get the integer value of a hexadecimal number.non-hex digit usage: quopri [-t | -d] [file] ...-t: quote tabs-d: decode; default encodedecotabs-t and -d are mutually exclusive%s: can't open (%s) +# (Dec 1991 version).# if header, we have to escape _ because _ is used to escape space# RFC 1521 requires that the line ending in a space or tab must have# that trailing character encoded.# Strip off any readline induced trailing newline# Calculate the un-length-limited encoded line# First, write out the previous line# Now see if we need any soft line breaks because of RFC-imposed# length limitations. Then do the thisline->prevline dance.# Don't forget to include the soft line break `=' sign in the# length calculation!# Write out the current line# Write out the last line, without a trailing newline# Strip trailing whitespace# Bad escape sequence -- leave it in# Other helper functionsb'Conversions to/from quoted-printable transport encoding as per RFC 1521.'u'Conversions to/from quoted-printable transport encoding as per RFC 1521.'b'encodestring'u'encodestring'b'0123456789ABCDEF'b'Decide whether a particular byte ordinal needs to be quoted. + + The 'quotetabs' flag indicates whether embedded tabs and spaces should be + quoted. Note that line-ending tabs and spaces are always encoded, as per + RFC 1521. + 'u'Decide whether a particular byte ordinal needs to be quoted. + + The 'quotetabs' flag indicates whether embedded tabs and spaces should be + quoted. Note that line-ending tabs and spaces are always encoded, as per + RFC 1521. + 'b'Quote a single character.'u'Quote a single character.'b'Read 'input', apply quoted-printable encoding, and write to 'output'. + + 'input' and 'output' are binary file objects. The 'quotetabs' flag + indicates whether embedded tabs and spaces should be quoted. Note that + line-ending tabs and spaces are always encoded, as per RFC 1521. + The 'header' flag indicates whether we are encoding spaces as _ as per RFC + 1522.'u'Read 'input', apply quoted-printable encoding, and write to 'output'. + + 'input' and 'output' are binary file objects. The 'quotetabs' flag + indicates whether embedded tabs and spaces should be quoted. Note that + line-ending tabs and spaces are always encoded, as per RFC 1521. + The 'header' flag indicates whether we are encoding spaces as _ as per RFC + 1522.'b'= +'b'Read 'input', apply quoted-printable decoding, and write to 'output'. + 'input' and 'output' are binary file objects. + If 'header' is true, decode underscore as space (per RFC 1522).'u'Read 'input', apply quoted-printable decoding, and write to 'output'. + 'input' and 'output' are binary file objects. + If 'header' is true, decode underscore as space (per RFC 1522).'b' 'b'Return true if the byte ordinal 'c' is a hexadecimal digit in ASCII.'u'Return true if the byte ordinal 'c' is a hexadecimal digit in ASCII.'b'Get the integer value of a hexadecimal number.'u'Get the integer value of a hexadecimal number.'b'non-hex digit 'u'non-hex digit 'b'td'u'td'b'usage: quopri [-t | -d] [file] ...'u'usage: quopri [-t | -d] [file] ...'b'-t: quote tabs'u'-t: quote tabs'b'-d: decode; default encode'u'-d: decode; default encode'b'-t and -d are mutually exclusive'u'-t and -d are mutually exclusive'b'%s: can't open (%s) +'u'%s: can't open (%s) +'Quoted-printable content transfer encoding per RFCs 2045-2047. + +This module handles the content transfer encoding method defined in RFC 2045 +to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to +safely encode text that is in a character set similar to the 7-bit US ASCII +character set, but that includes some 8-bit characters that are normally not +allowed in email bodies or headers. + +Quoted-printable is very space-inefficient for encoding binary files; use the +email.base64mime module for that instead. + +This module provides an interface to encode and decode both headers and bodies +with quoted-printable encoding. + +RFC 2045 defines a method for including character set information in an +`encoded-word' in a header. This method is commonly used for 8-bit real names +in To:/From:/Cc: etc. fields, as well as Subject: lines. + +This module does not do the line wrapping or end-of-line character +conversion necessary for proper internationalized headers; it only +does dumb encoding and decoding. To deal with the various line +wrapping issues, use the email.header module. +body_lengthhexdigits=%02X_QUOPRI_MAP_QUOPRI_HEADER_MAP_QUOPRI_BODY_MAP !"#$%&'()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ b' !"#$%&\'()*+,-./0123456789:;<>'b'?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`'b'abcdefghijklmnopqrstuvwxyz{|}~\t'header_checkoctetReturn True if the octet should be escaped with header quopri.body_checkReturn True if the octet should be escaped with body quopri.Return a header quoted-printable encoding length. + + Note that this does not include any RFC 2047 chrome added by + `header_encode()`. + + :param bytearray: An array of bytes (a.k.a. octets). + :return: The length in bytes of the byte array when it is encoded with + quoted-printable for headers. + Return a body quoted-printable encoding length. + + :param bytearray: An array of bytes (a.k.a. octets). + :return: The length in bytes of the byte array when it is encoded with + quoted-printable for bodies. + Turn a string in the form =AB to the ASCII character with value 0xabEncode a single header line with quoted-printable (like) encoding. + + Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but + used specifically for email header fields to allow charsets with mostly 7 + bit characters (and some 8 bit) to remain more or less readable in non-RFC + 2045 aware mail clients. + + charset names the character set to use in the RFC 2046 header. It + defaults to iso-8859-1. + =?%s?q?%s?=_QUOPRI_BODY_ENCODE_MAPEncode with quoted-printable, wrapping at maxlinelen characters. + + Each line of encoded text will end with eol, which defaults to "\n". Set + this to "\r\n" if you will be using the result of this function directly + in an email. + + Each line will be wrapped at, at most, maxlinelen characters before the + eol string (maxlinelen defaults to 76 characters, the maximum value + permitted by RFC 2045). Long lines will have the 'soft line break' + quoted-printable character "=" appended to them, so the decoded text will + be identical to the original text. + + The minimum maxlinelen is 4 to have room for a quoted character ("=XX") + followed by a soft line break. Smaller values will generate a + ValueError. + + maxlinelen must be at least 4soft_breakmaxlinelen1encoded_bodylaststartroomDecode a quoted-printable string. + + Lines are separated with eol, which defaults to \n. + _unquote_matchTurn a match in the form =AB to the ASCII character with value 0xabDecode a string encoded with RFC 2045 MIME header `Q' encoding. + + This function does not parse a full MIME header value encoded with + quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use + the high level email.header class for that functionality. + =[a-fA-F0-9]{2}# Build a mapping of octets to the expansion of that octet. Since we're only# going to have 256 of these things, this isn't terribly inefficient# space-wise. Remember that headers and bodies have different sets of safe# characters. Initialize both maps with the full expansion, and then override# the safe bytes with the more compact form.# Safe header bytes which need no encoding.# Headers have one other special encoding; spaces become underscores.# Safe body bytes which need no encoding.# Return empty headers as an empty string.# Iterate over every byte, encoding if necessary.# Now add the RFC chrome to each encoded chunk and glue the chunks# together.# quote special characters# leave space for the '=' at the end of a line# break up the line into pieces no longer than maxlinelen - 1# make sure we don't break up an escape sequence# handle rest of line, special case if line ends in whitespace# It's a whitespace character at end-of-line, and we have room# for the three-character quoted encoding.# There's room for the whitespace character and a soft break.# There's room only for a soft break. The quoted whitespace# will be the only content on the subsequent line.# add back final newline if present# BAW: I'm not sure if the intent was for the signature of this function to be# the same as base64MIME.decode() or not...# BAW: see comment in encode() above. Again, we're building up the# decoded string with string concatenation, which could be done much more# efficiently.# Otherwise, c == "=". Are we at the end of the line? If so, add# a soft line break.# Decode if in form =AB# Otherwise, not in form =AB, pass literally# Special case if original string did not end with eol# Header decoding is done a bit differentlyb'Quoted-printable content transfer encoding per RFCs 2045-2047. + +This module handles the content transfer encoding method defined in RFC 2045 +to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to +safely encode text that is in a character set similar to the 7-bit US ASCII +character set, but that includes some 8-bit characters that are normally not +allowed in email bodies or headers. + +Quoted-printable is very space-inefficient for encoding binary files; use the +email.base64mime module for that instead. + +This module provides an interface to encode and decode both headers and bodies +with quoted-printable encoding. + +RFC 2045 defines a method for including character set information in an +`encoded-word' in a header. This method is commonly used for 8-bit real names +in To:/From:/Cc: etc. fields, as well as Subject: lines. + +This module does not do the line wrapping or end-of-line character +conversion necessary for proper internationalized headers; it only +does dumb encoding and decoding. To deal with the various line +wrapping issues, use the email.header module. +'u'Quoted-printable content transfer encoding per RFCs 2045-2047. + +This module handles the content transfer encoding method defined in RFC 2045 +to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to +safely encode text that is in a character set similar to the 7-bit US ASCII +character set, but that includes some 8-bit characters that are normally not +allowed in email bodies or headers. + +Quoted-printable is very space-inefficient for encoding binary files; use the +email.base64mime module for that instead. + +This module provides an interface to encode and decode both headers and bodies +with quoted-printable encoding. + +RFC 2045 defines a method for including character set information in an +`encoded-word' in a header. This method is commonly used for 8-bit real names +in To:/From:/Cc: etc. fields, as well as Subject: lines. + +This module does not do the line wrapping or end-of-line character +conversion necessary for proper internationalized headers; it only +does dumb encoding and decoding. To deal with the various line +wrapping issues, use the email.header module. +'b'body_length'u'body_length'b'header_decode'u'header_decode'b'=%02X'u'=%02X'b' !"#$%&'()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 'b'Return True if the octet should be escaped with header quopri.'u'Return True if the octet should be escaped with header quopri.'b'Return True if the octet should be escaped with body quopri.'u'Return True if the octet should be escaped with body quopri.'b'Return a header quoted-printable encoding length. + + Note that this does not include any RFC 2047 chrome added by + `header_encode()`. + + :param bytearray: An array of bytes (a.k.a. octets). + :return: The length in bytes of the byte array when it is encoded with + quoted-printable for headers. + 'u'Return a header quoted-printable encoding length. + + Note that this does not include any RFC 2047 chrome added by + `header_encode()`. + + :param bytearray: An array of bytes (a.k.a. octets). + :return: The length in bytes of the byte array when it is encoded with + quoted-printable for headers. + 'b'Return a body quoted-printable encoding length. + + :param bytearray: An array of bytes (a.k.a. octets). + :return: The length in bytes of the byte array when it is encoded with + quoted-printable for bodies. + 'u'Return a body quoted-printable encoding length. + + :param bytearray: An array of bytes (a.k.a. octets). + :return: The length in bytes of the byte array when it is encoded with + quoted-printable for bodies. + 'b'Turn a string in the form =AB to the ASCII character with value 0xab'u'Turn a string in the form =AB to the ASCII character with value 0xab'b'Encode a single header line with quoted-printable (like) encoding. + + Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but + used specifically for email header fields to allow charsets with mostly 7 + bit characters (and some 8 bit) to remain more or less readable in non-RFC + 2045 aware mail clients. + + charset names the character set to use in the RFC 2046 header. It + defaults to iso-8859-1. + 'u'Encode a single header line with quoted-printable (like) encoding. + + Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but + used specifically for email header fields to allow charsets with mostly 7 + bit characters (and some 8 bit) to remain more or less readable in non-RFC + 2045 aware mail clients. + + charset names the character set to use in the RFC 2046 header. It + defaults to iso-8859-1. + 'b'=?%s?q?%s?='u'=?%s?q?%s?='b'Encode with quoted-printable, wrapping at maxlinelen characters. + + Each line of encoded text will end with eol, which defaults to "\n". Set + this to "\r\n" if you will be using the result of this function directly + in an email. + + Each line will be wrapped at, at most, maxlinelen characters before the + eol string (maxlinelen defaults to 76 characters, the maximum value + permitted by RFC 2045). Long lines will have the 'soft line break' + quoted-printable character "=" appended to them, so the decoded text will + be identical to the original text. + + The minimum maxlinelen is 4 to have room for a quoted character ("=XX") + followed by a soft line break. Smaller values will generate a + ValueError. + + 'u'Encode with quoted-printable, wrapping at maxlinelen characters. + + Each line of encoded text will end with eol, which defaults to "\n". Set + this to "\r\n" if you will be using the result of this function directly + in an email. + + Each line will be wrapped at, at most, maxlinelen characters before the + eol string (maxlinelen defaults to 76 characters, the maximum value + permitted by RFC 2045). Long lines will have the 'soft line break' + quoted-printable character "=" appended to them, so the decoded text will + be identical to the original text. + + The minimum maxlinelen is 4 to have room for a quoted character ("=XX") + followed by a soft line break. Smaller values will generate a + ValueError. + + 'b'maxlinelen must be at least 4'u'maxlinelen must be at least 4'b'Decode a quoted-printable string. + + Lines are separated with eol, which defaults to \n. + 'u'Decode a quoted-printable string. + + Lines are separated with eol, which defaults to \n. + 'b'Turn a match in the form =AB to the ASCII character with value 0xab'u'Turn a match in the form =AB to the ASCII character with value 0xab'b'Decode a string encoded with RFC 2045 MIME header `Q' encoding. + + This function does not parse a full MIME header value encoded with + quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use + the high level email.header class for that functionality. + 'u'Decode a string encoded with RFC 2045 MIME header `Q' encoding. + + This function does not parse a full MIME header value encoded with + quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use + the high level email.header class for that functionality. + 'b'=[a-fA-F0-9]{2}'u'=[a-fA-F0-9]{2}'u'email.quoprimime'Random variable generators. + + integers + -------- + uniform within range + + sequences + --------- + pick random element + pick random sample + pick weighted random sample + generate random permutation + + distributions on the real line: + ------------------------------ + uniform + triangular + normal (Gaussian) + lognormal + negative exponential + gamma + beta + pareto + Weibull + + distributions on the circle (angles 0 to 2pi) + --------------------------------------------- + circular uniform + von Mises + +General notes on the underlying Mersenne Twister core generator: + +* The period is 2**19937-1. +* It is one of the most extensively tested generators in existence. +* The random() method is implemented in C, executes in a single Python step, + and is, therefore, threadsafe. + +_pi_e_ceil_sqrt_acos_cos_sin_urandom_Set_Sequence_accumulateuniformrandintsamplerandrangeshufflenormalvariatelognormvariateexpovariatevonmisesvariategammavariatetriangulargaussbetavariateparetovariateweibullvariateSystemRandomNV_MAGICCONSTTWOPILOG44.5SG_MAGICCONSTBPFRECIP_BPFRandom number generator base class used by bound module functions. + + Used to instantiate instances of Random to get generators that don't + share state. + + Class Random can also be subclassed if you want to use a different basic + generator of your own devising: in that case, override the following + methods: random(), seed(), getstate(), and setstate(). + Optionally, implement a getrandbits() method so that randrange() + can cover arbitrarily large ranges. + + Initialize an instance. + + Optional argument x controls seeding, as for Random.seed(). + gauss_nextControl how subclasses generate random integers. + + The algorithm a subclass can use depends on the random() and/or + getrandbits() implementation available to it and determines + whether it can generate random integers from arbitrarily large + ranges. + _randbelow_randbelow_with_getrandbits_randbelow_without_getrandbitsInitialize internal state from hashable object. + + None or no argument seeds from current time or from an operating + system specific randomness source if available. + + If *a* is an int, all bits are used. + + For version 2 (the default), all of the bits are used if *a* is a str, + bytes, or bytearray. For version 1 (provided for reproducing random + sequences from older versions of Python), the algorithm for str and + bytes generates a narrower range of seeds. + + 0xFFFFFFFFFFFFFFFFReturn internal state; can be passed to setstate() later.Restore internal state from object returned by getstate().internalstatestate with version %s passed to Random.setstate() of version %s"state with version %s passed to ""Random.setstate() of version %s"Choose a random item from range(start, stop[, step]). + + This fixes the problem with randint() which includes the + endpoint; in Python this is usually not what you want. + + istartnon-integer arg 1 for randrange()empty range for randrange()istopnon-integer stop for randrange()empty range for randrange() (%d, %d, %d)istepnon-integer step for randrange()zero step for randrange()Return random integer in range [a, b], including both end points. + Return a random int in the range [0,n). Raises ValueError if n==0.Return a random int in the range [0,n). Raises ValueError if n==0. + + The implementation does not use getrandbits, but only random. + Underlying random() generator does not supply +enough bits to choose from a population range this large. +To remove the range limitation, add a getrandbits() method."Underlying random() generator does not supply \n""enough bits to choose from a population range this large.\n""To remove the range limitation, add a getrandbits() method."Boundary cannot be zeroChoose a random element from a non-empty sequence.Cannot choose from an empty sequenceShuffle list x in place, and return None. + + Optional argument random is a 0-argument function returning a + random float in [0.0, 1.0); if it is the default None, the + standard random.random will be used. + + randbelowpopulationChooses k unique random elements from a population sequence or set. + + Returns a new list containing elements from the population while + leaving the original population unchanged. The resulting list is + in selection order so that all sub-slices will also be valid random + samples. This allows raffle winners (the sample) to be partitioned + into grand prize and second place winners (the subslices). + + Members of the population need not be hashable or unique. If the + population contains repeats, then each occurrence is a possible + selection in the sample. + + To choose a sample in a range of integers, use range as an argument. + This is especially fast and space efficient for sampling from a + large population: sample(range(10000000), 60) + Population must be a sequence or set. For dicts, use list(d).Sample larger than population or is negativesetsizeselectedselected_addweightscum_weightsReturn a k sized list of population elements chosen with replacement. + + If the relative weights or cumulative weights are not specified, + the selections are made with equal probability. + + Cannot specify both weights and cumulative weightsThe number of weights does not match the populationtotalGet a random number in the range [a, b) or [a, b] depending on rounding.lowhighTriangular distribution. + + Continuous distribution bounded by given lower and upper limits, + and having a given mode value in-between. + + http://en.wikipedia.org/wiki/Triangular_distribution + + Normal distribution. + + mu is the mean, and sigma is the standard deviation. + + Log normal distribution. + + If you take the natural logarithm of this distribution, you'll get a + normal distribution with mean mu and standard deviation sigma. + mu can have any value, and sigma must be greater than zero. + + lambdExponential distribution. + + lambd is 1.0 divided by the desired mean. It should be + nonzero. (The parameter would be called "lambda", but that is + a reserved word in Python.) Returned values range from 0 to + positive infinity if lambd is positive, and from negative + infinity to 0 if lambd is negative. + + Circular data distribution. + + mu is the mean angle, expressed in radians between 0 and 2*pi, and + kappa is the concentration parameter, which must be greater than or + equal to zero. If kappa is equal to zero, this distribution reduces + to a uniform random angle over the range 0 to 2*pi. + + 1e-061e-6Gamma distribution. Not the gamma function! + + Conditions on the parameters are alpha > 0 and beta > 0. + + The probability distribution function is: + + x ** (alpha - 1) * math.exp(-x / beta) + pdf(x) = -------------------------------------- + math.gamma(alpha) * beta ** alpha + + gammavariate: alpha and beta must be > 0.0ainvbbb1e-071e-70.9999999.9999999Gaussian distribution. + + mu is the mean, and sigma is the standard deviation. This is + slightly faster than the normalvariate() function. + + Not thread-safe without a lock around calls. + + x2pig2radBeta distribution. + + Conditions on the parameters are alpha > 0 and beta > 0. + Returned values range between 0 and 1. + + Pareto distribution. alpha is the shape parameter.Weibull distribution. + + alpha is the scale parameter and beta is the shape parameter. + + Alternate random number generator using sources provided + by the operating system (such as /dev/urandom on Unix or + CryptGenRandom on Windows). + + Not available on all systems (see os.urandom() for details). + Get the next random number in the range [0.0, 1.0).getrandbits(k) -> x. Generates an int with k random bits.number of bits must be greater than zeronumbytesStub method. Not used for a system random number generator._notimplementedMethod should not be called for a system random number generator.System entropy source does not have state._test_generatorsqsum10000000000.01e10smallestlargestsec,avgstddevavg %g, stddev %g, min %g, max %g +0.9200.0_inst# hashlib is pretty heavy to load, try lean internal module first# fallback to official implementation# Number of bits in a float# Translated by Guido van Rossum from C source provided by# Adrian Baddeley. Adapted by Raymond Hettinger for use with# the Mersenne Twister and os.urandom() core generators.# used by getstate/setstate# just inherit it# In version 2, the state was saved as signed ints, which causes# inconsistencies between 32/64-bit systems. The state is# really unsigned 32-bit ints, so we convert negative ints from# version 2 to positive longs for version 3.## ---- Methods below this point do not need to be overridden when## ---- subclassing for the purpose of using a different core generator.## -------------------- pickle support -------------------# Issue 17489: Since __reduce__ was defined to fix #759889 this is no# longer called; we leave it here because it has been here since random was# rewritten back in 2001 and why risk breaking something.# for pickle## -------------------- integer methods -------------------# This code is a bit messy to make it fast for the# common case while still doing adequate error checking.# stop argument supplied.# Non-unit step argument supplied.# don't use (n-1) here because n can be 1# 0 <= r < 2**k# int(limit * maxsize) % n == 0## -------------------- sequence methods -------------------# pick an element in x[:i+1] with which to exchange x[i]# Sampling without replacement entails tracking either potential# selections (the pool) in a list or previous selections in a set.# When the number of selections is small compared to the# population, then tracking selections is efficient, requiring# only a small set and an occasional reselection. For# a larger number of selections, the pool tracking method is# preferred since the list takes less space than the# set and it doesn't suffer from frequent reselections.# The number of calls to _randbelow() is kept at or near k, the# theoretical minimum. This is important because running time# is dominated by _randbelow() and because it extracts the# least entropy from the underlying random number generators.# Memory requirements are kept to the smaller of a k-length# set or an n-length list.# There are other sampling algorithms that do not require# auxiliary memory, but they were rejected because they made# too many calls to _randbelow(), making them slower and# causing them to eat more entropy than necessary.# size of a small set minus size of an empty list# table size for big sets# An n-length list is smaller than a k-length set# invariant: non-selected at [0,n-i)# move non-selected item into vacancy# convert to float for a small speed improvement# convert to float## -------------------- real-valued distributions -------------------## -------------------- uniform distribution -------------------## -------------------- triangular --------------------## -------------------- normal distribution --------------------# mu = mean, sigma = standard deviation# Uses Kinderman and Monahan method. Reference: Kinderman,# A.J. and Monahan, J.F., "Computer generation of random# variables using the ratio of uniform deviates", ACM Trans# Math Software, 3, (1977), pp257-260.## -------------------- lognormal distribution --------------------## -------------------- exponential distribution --------------------# lambd: rate lambd = 1/mean# ('lambda' is a Python reserved word)# we use 1-random() instead of random() to preclude the# possibility of taking the log of zero.## -------------------- von Mises distribution --------------------# mu: mean angle (in radians between 0 and 2*pi)# kappa: concentration parameter kappa (>= 0)# if kappa = 0 generate uniform random angle# Based upon an algorithm published in: Fisher, N.I.,# "Statistical Analysis of Circular Data", Cambridge# University Press, 1993.# Thanks to Magnus Kessler for a correction to the# implementation of step 4.## -------------------- gamma distribution --------------------# alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2# Warning: a few older sources define the gamma distribution in terms# of alpha > -1.0# Uses R.C.H. Cheng, "The generation of Gamma# variables with non-integral shape parameters",# Applied Statistics, (1977), 26, No. 1, p71-74# expovariate(1/beta)# alpha is between 0 and 1 (exclusive)# Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle## -------------------- Gauss (faster alternative) --------------------# When x and y are two variables from [0, 1), uniformly# distributed, then# cos(2*pi*x)*sqrt(-2*log(1-y))# sin(2*pi*x)*sqrt(-2*log(1-y))# are two *independent* variables with normal distribution# (mu = 0, sigma = 1).# (Lambert Meertens)# (corrected version; bug discovered by Mike Miller, fixed by LM)# Multithreading note: When two threads call this function# simultaneously, it is possible that they will receive the# same return value. The window is very small though. To# avoid this, you have to use a lock around all calls. (I# didn't want to slow this down in the serial case by using a# lock here.)## -------------------- beta --------------------## See## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html## for Ivan Frohne's insightful analysis of why the original implementation:## def betavariate(self, alpha, beta):## # Discrete Event Simulation in C, pp 87-88.## y = self.expovariate(alpha)## z = self.expovariate(1.0/beta)## return z/(y+z)## was dead wrong, and how it probably got that way.# This version due to Janne Sinkkonen, and matches all the std# texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").## -------------------- Pareto --------------------# Jain, pg. 495## -------------------- Weibull --------------------# Jain, pg. 499; bug fix courtesy Bill Arms## --------------- Operating System Random Source ------------------# bits / 8 and rounded up# trim excess bits## -------------------- test program --------------------# Create one instance, seeded from current time, and export its methods# as module-level functions. The functions share state across all uses#(both in the user's code and in the Python libraries), but that's fine# for most programs and is easier for the casual user than making them# instantiate their own Random() instance.b'Random variable generators. + + integers + -------- + uniform within range + + sequences + --------- + pick random element + pick random sample + pick weighted random sample + generate random permutation + + distributions on the real line: + ------------------------------ + uniform + triangular + normal (Gaussian) + lognormal + negative exponential + gamma + beta + pareto + Weibull + + distributions on the circle (angles 0 to 2pi) + --------------------------------------------- + circular uniform + von Mises + +General notes on the underlying Mersenne Twister core generator: + +* The period is 2**19937-1. +* It is one of the most extensively tested generators in existence. +* The random() method is implemented in C, executes in a single Python step, + and is, therefore, threadsafe. + +'u'Random variable generators. + + integers + -------- + uniform within range + + sequences + --------- + pick random element + pick random sample + pick weighted random sample + generate random permutation + + distributions on the real line: + ------------------------------ + uniform + triangular + normal (Gaussian) + lognormal + negative exponential + gamma + beta + pareto + Weibull + + distributions on the circle (angles 0 to 2pi) + --------------------------------------------- + circular uniform + von Mises + +General notes on the underlying Mersenne Twister core generator: + +* The period is 2**19937-1. +* It is one of the most extensively tested generators in existence. +* The random() method is implemented in C, executes in a single Python step, + and is, therefore, threadsafe. + +'b'Random'u'Random'b'seed'u'seed'b'random'u'random'b'uniform'u'uniform'b'randint'u'randint'b'sample'u'sample'b'randrange'u'randrange'b'shuffle'u'shuffle'b'normalvariate'u'normalvariate'b'lognormvariate'u'lognormvariate'b'expovariate'u'expovariate'b'vonmisesvariate'u'vonmisesvariate'b'gammavariate'u'gammavariate'b'triangular'u'triangular'b'gauss'u'gauss'b'betavariate'u'betavariate'b'paretovariate'u'paretovariate'b'weibullvariate'u'weibullvariate'b'getstate'u'getstate'b'setstate'u'setstate'b'getrandbits'u'getrandbits'b'SystemRandom'u'SystemRandom'b'Random number generator base class used by bound module functions. + + Used to instantiate instances of Random to get generators that don't + share state. + + Class Random can also be subclassed if you want to use a different basic + generator of your own devising: in that case, override the following + methods: random(), seed(), getstate(), and setstate(). + Optionally, implement a getrandbits() method so that randrange() + can cover arbitrarily large ranges. + + 'u'Random number generator base class used by bound module functions. + + Used to instantiate instances of Random to get generators that don't + share state. + + Class Random can also be subclassed if you want to use a different basic + generator of your own devising: in that case, override the following + methods: random(), seed(), getstate(), and setstate(). + Optionally, implement a getrandbits() method so that randrange() + can cover arbitrarily large ranges. + + 'b'Initialize an instance. + + Optional argument x controls seeding, as for Random.seed(). + 'u'Initialize an instance. + + Optional argument x controls seeding, as for Random.seed(). + 'b'Control how subclasses generate random integers. + + The algorithm a subclass can use depends on the random() and/or + getrandbits() implementation available to it and determines + whether it can generate random integers from arbitrarily large + ranges. + 'u'Control how subclasses generate random integers. + + The algorithm a subclass can use depends on the random() and/or + getrandbits() implementation available to it and determines + whether it can generate random integers from arbitrarily large + ranges. + 'b'_randbelow'u'_randbelow'b'Initialize internal state from hashable object. + + None or no argument seeds from current time or from an operating + system specific randomness source if available. + + If *a* is an int, all bits are used. + + For version 2 (the default), all of the bits are used if *a* is a str, + bytes, or bytearray. For version 1 (provided for reproducing random + sequences from older versions of Python), the algorithm for str and + bytes generates a narrower range of seeds. + + 'u'Initialize internal state from hashable object. + + None or no argument seeds from current time or from an operating + system specific randomness source if available. + + If *a* is an int, all bits are used. + + For version 2 (the default), all of the bits are used if *a* is a str, + bytes, or bytearray. For version 1 (provided for reproducing random + sequences from older versions of Python), the algorithm for str and + bytes generates a narrower range of seeds. + + 'b'Return internal state; can be passed to setstate() later.'u'Return internal state; can be passed to setstate() later.'b'Restore internal state from object returned by getstate().'u'Restore internal state from object returned by getstate().'b'state with version %s passed to Random.setstate() of version %s'u'state with version %s passed to Random.setstate() of version %s'b'Choose a random item from range(start, stop[, step]). + + This fixes the problem with randint() which includes the + endpoint; in Python this is usually not what you want. + + 'u'Choose a random item from range(start, stop[, step]). + + This fixes the problem with randint() which includes the + endpoint; in Python this is usually not what you want. + + 'b'non-integer arg 1 for randrange()'u'non-integer arg 1 for randrange()'b'empty range for randrange()'u'empty range for randrange()'b'non-integer stop for randrange()'u'non-integer stop for randrange()'b'empty range for randrange() (%d, %d, %d)'u'empty range for randrange() (%d, %d, %d)'b'non-integer step for randrange()'u'non-integer step for randrange()'b'zero step for randrange()'u'zero step for randrange()'b'Return random integer in range [a, b], including both end points. + 'u'Return random integer in range [a, b], including both end points. + 'b'Return a random int in the range [0,n). Raises ValueError if n==0.'u'Return a random int in the range [0,n). Raises ValueError if n==0.'b'Return a random int in the range [0,n). Raises ValueError if n==0. + + The implementation does not use getrandbits, but only random. + 'u'Return a random int in the range [0,n). Raises ValueError if n==0. + + The implementation does not use getrandbits, but only random. + 'b'Underlying random() generator does not supply +enough bits to choose from a population range this large. +To remove the range limitation, add a getrandbits() method.'u'Underlying random() generator does not supply +enough bits to choose from a population range this large. +To remove the range limitation, add a getrandbits() method.'b'Boundary cannot be zero'u'Boundary cannot be zero'b'Choose a random element from a non-empty sequence.'u'Choose a random element from a non-empty sequence.'b'Cannot choose from an empty sequence'u'Cannot choose from an empty sequence'b'Shuffle list x in place, and return None. + + Optional argument random is a 0-argument function returning a + random float in [0.0, 1.0); if it is the default None, the + standard random.random will be used. + + 'u'Shuffle list x in place, and return None. + + Optional argument random is a 0-argument function returning a + random float in [0.0, 1.0); if it is the default None, the + standard random.random will be used. + + 'b'Chooses k unique random elements from a population sequence or set. + + Returns a new list containing elements from the population while + leaving the original population unchanged. The resulting list is + in selection order so that all sub-slices will also be valid random + samples. This allows raffle winners (the sample) to be partitioned + into grand prize and second place winners (the subslices). + + Members of the population need not be hashable or unique. If the + population contains repeats, then each occurrence is a possible + selection in the sample. + + To choose a sample in a range of integers, use range as an argument. + This is especially fast and space efficient for sampling from a + large population: sample(range(10000000), 60) + 'u'Chooses k unique random elements from a population sequence or set. + + Returns a new list containing elements from the population while + leaving the original population unchanged. The resulting list is + in selection order so that all sub-slices will also be valid random + samples. This allows raffle winners (the sample) to be partitioned + into grand prize and second place winners (the subslices). + + Members of the population need not be hashable or unique. If the + population contains repeats, then each occurrence is a possible + selection in the sample. + + To choose a sample in a range of integers, use range as an argument. + This is especially fast and space efficient for sampling from a + large population: sample(range(10000000), 60) + 'b'Population must be a sequence or set. For dicts, use list(d).'u'Population must be a sequence or set. For dicts, use list(d).'b'Sample larger than population or is negative'u'Sample larger than population or is negative'b'Return a k sized list of population elements chosen with replacement. + + If the relative weights or cumulative weights are not specified, + the selections are made with equal probability. + + 'u'Return a k sized list of population elements chosen with replacement. + + If the relative weights or cumulative weights are not specified, + the selections are made with equal probability. + + 'b'Cannot specify both weights and cumulative weights'u'Cannot specify both weights and cumulative weights'b'The number of weights does not match the population'u'The number of weights does not match the population'b'Get a random number in the range [a, b) or [a, b] depending on rounding.'u'Get a random number in the range [a, b) or [a, b] depending on rounding.'b'Triangular distribution. + + Continuous distribution bounded by given lower and upper limits, + and having a given mode value in-between. + + http://en.wikipedia.org/wiki/Triangular_distribution + + 'u'Triangular distribution. + + Continuous distribution bounded by given lower and upper limits, + and having a given mode value in-between. + + http://en.wikipedia.org/wiki/Triangular_distribution + + 'b'Normal distribution. + + mu is the mean, and sigma is the standard deviation. + + 'u'Normal distribution. + + mu is the mean, and sigma is the standard deviation. + + 'b'Log normal distribution. + + If you take the natural logarithm of this distribution, you'll get a + normal distribution with mean mu and standard deviation sigma. + mu can have any value, and sigma must be greater than zero. + + 'u'Log normal distribution. + + If you take the natural logarithm of this distribution, you'll get a + normal distribution with mean mu and standard deviation sigma. + mu can have any value, and sigma must be greater than zero. + + 'b'Exponential distribution. + + lambd is 1.0 divided by the desired mean. It should be + nonzero. (The parameter would be called "lambda", but that is + a reserved word in Python.) Returned values range from 0 to + positive infinity if lambd is positive, and from negative + infinity to 0 if lambd is negative. + + 'u'Exponential distribution. + + lambd is 1.0 divided by the desired mean. It should be + nonzero. (The parameter would be called "lambda", but that is + a reserved word in Python.) Returned values range from 0 to + positive infinity if lambd is positive, and from negative + infinity to 0 if lambd is negative. + + 'b'Circular data distribution. + + mu is the mean angle, expressed in radians between 0 and 2*pi, and + kappa is the concentration parameter, which must be greater than or + equal to zero. If kappa is equal to zero, this distribution reduces + to a uniform random angle over the range 0 to 2*pi. + + 'u'Circular data distribution. + + mu is the mean angle, expressed in radians between 0 and 2*pi, and + kappa is the concentration parameter, which must be greater than or + equal to zero. If kappa is equal to zero, this distribution reduces + to a uniform random angle over the range 0 to 2*pi. + + 'b'Gamma distribution. Not the gamma function! + + Conditions on the parameters are alpha > 0 and beta > 0. + + The probability distribution function is: + + x ** (alpha - 1) * math.exp(-x / beta) + pdf(x) = -------------------------------------- + math.gamma(alpha) * beta ** alpha + + 'u'Gamma distribution. Not the gamma function! + + Conditions on the parameters are alpha > 0 and beta > 0. + + The probability distribution function is: + + x ** (alpha - 1) * math.exp(-x / beta) + pdf(x) = -------------------------------------- + math.gamma(alpha) * beta ** alpha + + 'b'gammavariate: alpha and beta must be > 0.0'u'gammavariate: alpha and beta must be > 0.0'b'Gaussian distribution. + + mu is the mean, and sigma is the standard deviation. This is + slightly faster than the normalvariate() function. + + Not thread-safe without a lock around calls. + + 'u'Gaussian distribution. + + mu is the mean, and sigma is the standard deviation. This is + slightly faster than the normalvariate() function. + + Not thread-safe without a lock around calls. + + 'b'Beta distribution. + + Conditions on the parameters are alpha > 0 and beta > 0. + Returned values range between 0 and 1. + + 'u'Beta distribution. + + Conditions on the parameters are alpha > 0 and beta > 0. + Returned values range between 0 and 1. + + 'b'Pareto distribution. alpha is the shape parameter.'u'Pareto distribution. alpha is the shape parameter.'b'Weibull distribution. + + alpha is the scale parameter and beta is the shape parameter. + + 'u'Weibull distribution. + + alpha is the scale parameter and beta is the shape parameter. + + 'b'Alternate random number generator using sources provided + by the operating system (such as /dev/urandom on Unix or + CryptGenRandom on Windows). + + Not available on all systems (see os.urandom() for details). + 'u'Alternate random number generator using sources provided + by the operating system (such as /dev/urandom on Unix or + CryptGenRandom on Windows). + + Not available on all systems (see os.urandom() for details). + 'b'Get the next random number in the range [0.0, 1.0).'u'Get the next random number in the range [0.0, 1.0).'b'getrandbits(k) -> x. Generates an int with k random bits.'u'getrandbits(k) -> x. Generates an int with k random bits.'b'number of bits must be greater than zero'u'number of bits must be greater than zero'b'Stub method. Not used for a system random number generator.'u'Stub method. Not used for a system random number generator.'b'Method should not be called for a system random number generator.'u'Method should not be called for a system random number generator.'b'System entropy source does not have state.'u'System entropy source does not have state.'b'sec,'u'sec,'b'avg %g, stddev %g, min %g, max %g +'u'avg %g, stddev %g, min %g, max %g +'Support for regular expressions (RE). + +This module provides regular expression matching operations similar to +those found in Perl. It supports both 8-bit and Unicode strings; both +the pattern and the strings being processed can contain null bytes and +characters outside the US ASCII range. + +Regular expressions can contain both special and ordinary characters. +Most ordinary characters, like "A", "a", or "0", are the simplest +regular expressions; they simply match themselves. You can +concatenate ordinary characters, so last matches the string 'last'. + +The special characters are: + "." Matches any character except a newline. + "^" Matches the start of the string. + "$" Matches the end of the string or just before the newline at + the end of the string. + "*" Matches 0 or more (greedy) repetitions of the preceding RE. + Greedy means that it will match as many repetitions as possible. + "+" Matches 1 or more (greedy) repetitions of the preceding RE. + "?" Matches 0 or 1 (greedy) of the preceding RE. + *?,+?,?? Non-greedy versions of the previous three special characters. + {m,n} Matches from m to n repetitions of the preceding RE. + {m,n}? Non-greedy version of the above. + "\\" Either escapes special characters or signals a special sequence. + [] Indicates a set of characters. + A "^" as the first character indicates a complementing set. + "|" A|B, creates an RE that will match either A or B. + (...) Matches the RE inside the parentheses. + The contents can be retrieved or matched later in the string. + (?aiLmsux) The letters set the corresponding flags defined below. + (?:...) Non-grouping version of regular parentheses. + (?P...) The substring matched by the group is accessible by name. + (?P=name) Matches the text matched earlier by the group named name. + (?#...) A comment; ignored. + (?=...) Matches if ... matches next, but doesn't consume the string. + (?!...) Matches if ... doesn't match next. + (?<=...) Matches if preceded by ... (must be fixed length). + (?...) The substring matched by the group is accessible by name. + (?P=name) Matches the text matched earlier by the group named name. + (?#...) A comment; ignored. + (?=...) Matches if ... matches next, but doesn't consume the string. + (?!...) Matches if ... doesn't match next. + (?<=...) Matches if preceded by ... (must be fixed length). + (?...) The substring matched by the group is accessible by name. + (?P=name) Matches the text matched earlier by the group named name. + (?#...) A comment; ignored. + (?=...) Matches if ... matches next, but doesn't consume the string. + (?!...) Matches if ... doesn't match next. + (?<=...) Matches if preceded by ... (must be fixed length). + (? fixer list. head_nodeseveryheadsnode_type_accept_typeget_fixers_from_package + Return the fully qualified names for fixers in the package pkg_name. + fix_name_detect_future_featureshave_docstringadvancetokFixerErrorA fixer could not be loaded.write_unchanged_files_default_optionsFixCLASS_PREFIXFILE_PREFIXfixer_namesexplicitInitializer. + + Args: + fixer_names: a list of fixers to import + options: a dict with configuration. + explicit: a list of fixers to run even if they are explicit. + fixer_logget_fixersBMbmi_pre_orderbmi_post_orderBM_compatiblebmi_pre_order_headsbmi_post_order_headsInspects the options to load the requested patterns and handlers. + + Returns: + (pre_order, post_order), where pre_order is the list of fixers that + want a pre-order AST traversal, and post_order is the list that want + post-order traversal. + pre_order_fixerspost_order_fixersfix_mod_pathfix_classCan't find %s.%sSkipping optional fixer: %slog_debugAdding transformation: %sIllegal fixer order: %rrun_orderkey_funclog_errorCalled when an error occurs.Hook to log a message.print_outputold_textnew_textCalled with the old version, new version, and filename of a + refactored file.refactordoctests_onlyRefactor a list of files and directories.dir_or_filerefactor_dirrefactor_filedir_nameDescends down a directory and refactor every Python file found. + + Python files are assumed to have a .py extension. + + Files and subdirectories starting with '.' are skipped. + py_extdirnamesDescending into %s_read_python_source + Do our best to decode a Python source file correctly. + Can't open %s: %sRefactors a file.Refactoring doctests in %srefactor_docstringprocessed_fileNo doctest changes in %srefactor_stringNo changes in %sRefactor a given input string. + + Args: + data: a string holding the code to be refactored. + name: a human-readable name for use in error/log messages. + + Returns: + An AST corresponding to the refactored input stream; None if + there were errors during the parse. + Can't parse %s: %s: %sfuture_featuresRefactoring %srefactor_treerefactor_stdinRefactoring doctests in stdinNo doctest changes in stdinNo changes in stdinRefactors a parse tree (modifying the tree in place). + + For compatible patterns the bottom matcher module is + used. Otherwise the tree is traversed node-to-node for + matches. + + Args: + tree: a pytree.Node instance representing the root of the tree + to be refactored. + name: a human-readable name for this tree. + + Returns: + True if the tree was modified, False otherwise. + start_treetraverse_bymatch_setkeep_line_ordertransformnew_matchesfxrfinish_treetraversalTraverse an AST, applying a set of fixers to each node. + + This is a helper method for refactor_tree(). + + Args: + fixers: a list of fixer instances. + traversal: a generator that yields AST nodes. + + Returns: + None + + Called when a file has been refactored and there may be changes. + No changes to %sNot writing changes to %sWrites a string to a file. + + It first shows a unified diff between the old text and the new text, and + then rewrites the file; the latter is only done if the write option is + set. + Can't create %s: %sCan't write %s: %sWrote changes to %sPS1PS2Refactors a docstring, looking for doctests. + + This returns a modified version of the input string. It looks + for doctests, which start with a ">>>" prompt, and may be + continued with "..." prompts, as long as the "..." is indented + the same as the ">>>". + + (Unfortunately we can't use the doctest module's parser, + since, like most parsers, it is not geared towards preserving + the original source.) + block_linenorefactor_doctestRefactors one doctest. + + A doctest is given as a block of lines, the first of which starts + with ">>>" (possibly indented), while the remaining lines start + with "..." (identically indented). + + parse_blockSource: %sCan't parse docstring in %s line %s: %s: %sclippedneed to beNo files %s modified.Files that %s modified:Warnings/messages while refactoring:There was 1 error:There were %d errors:Parses a block into a tree. + + This is necessary to get correct line number / offset information + in the parser diagnostics and embedded into the parse tree. + wrap_toksWraps a tokenize stream to systematically modify start/end.gen_linesline0col0col1Generates lines as expected by tokenize from a list of lines. + + This strips the first len(indent + self.PS1) characters off each line. + prefix1prefix2line=%r, prefix=%rMultiprocessingUnsupportedMultiprocessRefactoringTooloutput_locknum_processesalready doing multiple processes_child# NodePatters must either have no type and no content# or a type and content -- so they don't get any farther# Always return leafs# Negated Patterns don't have a type# Recurse on each node in content# The prefix for fixer classes# The prefix for modules with a fixer within# When this is True, the refactor*() methods will call write_file() for# files processed even if they were not changed during refactoring. If# and only if the refactor method's write parameter was True.# List of files that were or should be modified# Bottom Matcher incompatible fixers# remove fixers that will be handled by the bottom-up# matcher# Modify dirnames in-place to remove subdirs with leading dots# Reading the file failed.# Silence certain parse errors# The [:-1] is to take off the \n we added earlier#use traditional matching for the incompatible fixers# obtain a set of candidate nodes#sort by depth; apply fixers from bottom(of the AST) to top#some fixers(eg fix_imports) must be applied#with the original file's line order# this node has been cut off from a# previous transformation ; skip# do not apply the same fixer again#new.fixers_applied.append(fixer)# do not apply the fixer again to# this or any subnode# update the original match set for# the added code# Undo the adjustment of the line numbers in wrap_toks() below.# Don't bother updating the columns; this is too complicated# since line_text would also have to be updated and it would# still break for tokens spanning lines. Let the user guess# that the column numbers for doctests are relative to the# end of the prompt string (PS1 or PS2).b'Refactoring framework. + +Used as a main program, this can refactor any number of files and/or +recursively descend down directories. Imported as a module, this +provides infrastructure to write your own refactoring tool. +'u'Refactoring framework. + +Used as a main program, this can refactor any number of files and/or +recursively descend down directories. Imported as a module, this +provides infrastructure to write your own refactoring tool. +'b'Return a sorted list of all available fix names in the given package.'u'Return a sorted list of all available fix names in the given package.'b'fix_'u'fix_'b' Accepts a pytree Pattern Node and returns a set + of the pattern types which will match first. 'u' Accepts a pytree Pattern Node and returns a set + of the pattern types which will match first. 'b'Oh no! I don't understand pattern %s'u'Oh no! I don't understand pattern %s'b' Accepts a list of fixers and returns a dictionary + of head node type --> fixer list. 'u' Accepts a list of fixers and returns a dictionary + of head node type --> fixer list. 'b' + Return the fully qualified names for fixers in the package pkg_name. + 'u' + Return the fully qualified names for fixers in the package pkg_name. + 'b'__future__'b'A fixer could not be loaded.'u'A fixer could not be loaded.'b'write_unchanged_files'u'write_unchanged_files'b'Fix'u'Fix'b'Initializer. + + Args: + fixer_names: a list of fixers to import + options: a dict with configuration. + explicit: a list of fixers to run even if they are explicit. + 'u'Initializer. + + Args: + fixer_names: a list of fixers to import + options: a dict with configuration. + explicit: a list of fixers to run even if they are explicit. + 'b'Inspects the options to load the requested patterns and handlers. + + Returns: + (pre_order, post_order), where pre_order is the list of fixers that + want a pre-order AST traversal, and post_order is the list that want + post-order traversal. + 'u'Inspects the options to load the requested patterns and handlers. + + Returns: + (pre_order, post_order), where pre_order is the list of fixers that + want a pre-order AST traversal, and post_order is the list that want + post-order traversal. + 'b'Can't find %s.%s'u'Can't find %s.%s'b'Skipping optional fixer: %s'u'Skipping optional fixer: %s'b'Adding transformation: %s'u'Adding transformation: %s'b'pre'u'pre'b'Illegal fixer order: %r'u'Illegal fixer order: %r'b'run_order'u'run_order'b'Called when an error occurs.'u'Called when an error occurs.'b'Hook to log a message.'u'Hook to log a message.'b'Called with the old version, new version, and filename of a + refactored file.'u'Called with the old version, new version, and filename of a + refactored file.'b'Refactor a list of files and directories.'u'Refactor a list of files and directories.'b'Descends down a directory and refactor every Python file found. + + Python files are assumed to have a .py extension. + + Files and subdirectories starting with '.' are skipped. + 'u'Descends down a directory and refactor every Python file found. + + Python files are assumed to have a .py extension. + + Files and subdirectories starting with '.' are skipped. + 'b'Descending into %s'u'Descending into %s'b' + Do our best to decode a Python source file correctly. + 'u' + Do our best to decode a Python source file correctly. + 'b'Can't open %s: %s'u'Can't open %s: %s'b'Refactors a file.'u'Refactors a file.'b'Refactoring doctests in %s'u'Refactoring doctests in %s'b'No doctest changes in %s'u'No doctest changes in %s'b'No changes in %s'u'No changes in %s'b'Refactor a given input string. + + Args: + data: a string holding the code to be refactored. + name: a human-readable name for use in error/log messages. + + Returns: + An AST corresponding to the refactored input stream; None if + there were errors during the parse. + 'u'Refactor a given input string. + + Args: + data: a string holding the code to be refactored. + name: a human-readable name for use in error/log messages. + + Returns: + An AST corresponding to the refactored input stream; None if + there were errors during the parse. + 'b'Can't parse %s: %s: %s'u'Can't parse %s: %s: %s'b'Refactoring %s'u'Refactoring %s'b'Refactoring doctests in stdin'u'Refactoring doctests in stdin'b'No doctest changes in stdin'u'No doctest changes in stdin'b'No changes in stdin'u'No changes in stdin'b'Refactors a parse tree (modifying the tree in place). + + For compatible patterns the bottom matcher module is + used. Otherwise the tree is traversed node-to-node for + matches. + + Args: + tree: a pytree.Node instance representing the root of the tree + to be refactored. + name: a human-readable name for this tree. + + Returns: + True if the tree was modified, False otherwise. + 'u'Refactors a parse tree (modifying the tree in place). + + For compatible patterns the bottom matcher module is + used. Otherwise the tree is traversed node-to-node for + matches. + + Args: + tree: a pytree.Node instance representing the root of the tree + to be refactored. + name: a human-readable name for this tree. + + Returns: + True if the tree was modified, False otherwise. + 'b'Traverse an AST, applying a set of fixers to each node. + + This is a helper method for refactor_tree(). + + Args: + fixers: a list of fixer instances. + traversal: a generator that yields AST nodes. + + Returns: + None + 'u'Traverse an AST, applying a set of fixers to each node. + + This is a helper method for refactor_tree(). + + Args: + fixers: a list of fixer instances. + traversal: a generator that yields AST nodes. + + Returns: + None + 'b' + Called when a file has been refactored and there may be changes. + 'u' + Called when a file has been refactored and there may be changes. + 'b'No changes to %s'u'No changes to %s'b'Not writing changes to %s'u'Not writing changes to %s'b'Writes a string to a file. + + It first shows a unified diff between the old text and the new text, and + then rewrites the file; the latter is only done if the write option is + set. + 'u'Writes a string to a file. + + It first shows a unified diff between the old text and the new text, and + then rewrites the file; the latter is only done if the write option is + set. + 'b'Can't create %s: %s'u'Can't create %s: %s'b'Can't write %s: %s'u'Can't write %s: %s'b'Wrote changes to %s'u'Wrote changes to %s'b'Refactors a docstring, looking for doctests. + + This returns a modified version of the input string. It looks + for doctests, which start with a ">>>" prompt, and may be + continued with "..." prompts, as long as the "..." is indented + the same as the ">>>". + + (Unfortunately we can't use the doctest module's parser, + since, like most parsers, it is not geared towards preserving + the original source.) + 'u'Refactors a docstring, looking for doctests. + + This returns a modified version of the input string. It looks + for doctests, which start with a ">>>" prompt, and may be + continued with "..." prompts, as long as the "..." is indented + the same as the ">>>". + + (Unfortunately we can't use the doctest module's parser, + since, like most parsers, it is not geared towards preserving + the original source.) + 'b'Refactors one doctest. + + A doctest is given as a block of lines, the first of which starts + with ">>>" (possibly indented), while the remaining lines start + with "..." (identically indented). + + 'u'Refactors one doctest. + + A doctest is given as a block of lines, the first of which starts + with ">>>" (possibly indented), while the remaining lines start + with "..." (identically indented). + + 'b'Source: %s'u'Source: %s'b'Can't parse docstring in %s line %s: %s: %s'u'Can't parse docstring in %s line %s: %s: %s'b'need to be'u'need to be'b'No files %s modified.'u'No files %s modified.'b'Files that %s modified:'u'Files that %s modified:'b'Warnings/messages while refactoring:'u'Warnings/messages while refactoring:'b'There was 1 error:'u'There was 1 error:'b'There were %d errors:'u'There were %d errors:'b'Parses a block into a tree. + + This is necessary to get correct line number / offset information + in the parser diagnostics and embedded into the parse tree. + 'u'Parses a block into a tree. + + This is necessary to get correct line number / offset information + in the parser diagnostics and embedded into the parse tree. + 'b'Wraps a tokenize stream to systematically modify start/end.'u'Wraps a tokenize stream to systematically modify start/end.'b'Generates lines as expected by tokenize from a list of lines. + + This strips the first len(indent + self.PS1) characters off each line. + 'u'Generates lines as expected by tokenize from a list of lines. + + This strips the first len(indent + self.PS1) characters off each line. + 'b'line=%r, prefix=%r'u'line=%r, prefix=%r'b'already doing multiple processes'u'already doing multiple processes'u'lib2to3.refactor'u'refactor'Redo the builtin repr() (representation) but with limits on most sizes.Decorator to make a repr function return fillvalue for a recursive callrepr_runningmaxlevelmaxarraymaxsetmaxfrozensetmaxdequemaxlong_repr_iterablemaxitertrailnewlevel%s%s%srepr_tuplerepr_listrepr_arrayarray('%s')array('%s', [repr_setset()_possibly_sortedrepr_frozensetfrozenset()frozenset({repr_dequedeque([repr_dictkeyreprvalreprrepr_int<%s instance at %#x>aRepr# Can't use functools.wraps() here because of bootstrap issues# XXX Hope this isn't too slow...# Bugs in x.__repr__() can cause arbitrary# exceptions -- then make up something# Since not all sequences of items can be sorted and comparison# functions may raise arbitrary exceptions, return an unsorted# sequence in that case.b'Redo the builtin repr() (representation) but with limits on most sizes.'u'Redo the builtin repr() (representation) but with limits on most sizes.'b'Repr'u'Repr'b'recursive_repr'u'recursive_repr'b'Decorator to make a repr function return fillvalue for a recursive call'u'Decorator to make a repr function return fillvalue for a recursive call'b'%s%s%s'u'%s%s%s'b'array('%s')'u'array('%s')'b'array('%s', ['u'array('%s', ['b'set()'u'set()'b'frozenset()'u'frozenset()'b'frozenset({'u'frozenset({'b'deque(['u'deque(['b'<%s instance at %#x>'u'<%s instance at %#x>'An extensible library for opening URLs using a variety of protocols + +The simplest way to use this module is to call the urlopen function, +which accepts a string containing a URL or a Request object (described +below). It opens the URL and returns the results as file-like +object; the returned object has some extra methods described below. + +The OpenerDirector manages a collection of Handler objects that do +all the actual work. Each Handler implements a particular protocol or +option. The OpenerDirector is a composite object that invokes the +Handlers needed to open the requested URL. For example, the +HTTPHandler performs HTTP GET and POST requests and deals with +non-error returns. The HTTPRedirectHandler automatically deals with +HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler +deals with digest authentication. + +urlopen(url, data=None) -- Basic usage is the same as original +urllib. pass the url and optionally data to post to an HTTP URL, and +get a file-like object back. One difference is that you can also pass +a Request instance instead of URL. Raises a URLError (subclass of +OSError); for HTTP errors, raises an HTTPError, which can also be +treated as a valid response. + +build_opener -- Function that creates a new OpenerDirector instance. +Will install the default handlers. Accepts one or more Handlers as +arguments, either instances or Handler classes that it will +instantiate. If one of the argument is a subclass of the default +handler, the argument will be installed instead of the default. + +install_opener -- Installs a new opener as the default opener. + +objects of interest: + +OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages +the Handler classes, while dealing with requests and responses. + +Request -- An object that encapsulates the state of a request. The +state can be as simple as the URL. It can also include extra HTTP +headers, e.g. a User-Agent. + +BaseHandler -- + +internals: +BaseHandler and parent +_call_chain conventions + +Example usage: + +import urllib.request + +# set up authentication info +authinfo = urllib.request.HTTPBasicAuthHandler() +authinfo.add_password(realm='PDQ Application', + uri='https://mahler:8092/site-updates.py', + user='klem', + passwd='geheim$parole') + +proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) + +# build a new opener that adds authentication and caching FTP handlers +opener = urllib.request.build_opener(proxy_support, authinfo, + urllib.request.CacheFTPHandler) + +# install it +urllib.request.install_opener(opener) + +f = urllib.request.urlopen('http://www.python.org/') +addclosehookRequestOpenerDirectorBaseHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerHTTPCookieProcessorProxyHandlerHTTPPasswordMgrHTTPPasswordMgrWithDefaultRealmHTTPPasswordMgrWithPriorAuthAbstractBasicAuthHandlerHTTPBasicAuthHandlerProxyBasicAuthHandlerAbstractDigestAuthHandlerHTTPDigestAuthHandlerProxyDigestAuthHandlerFTPHandlerCacheFTPHandlerDataHandlerUnknownHandlerHTTPErrorProcessorinstall_openerURLopenerFancyURLopener_openercafilecapathcadefaultOpen the URL url, which can be either a string or a Request object. + + *data* must be an object specifying additional data to be sent to + the server, or None if no such data is needed. See Request for + details. + + urllib.request module uses HTTP/1.1 and includes a "Connection:close" + header in its HTTP requests. + + The optional *timeout* parameter specifies a timeout in seconds for + blocking operations like the connection attempt (if not specified, the + global default timeout setting will be used). This only works for HTTP, + HTTPS and FTP connections. + + If *context* is specified, it must be a ssl.SSLContext instance describing + the various SSL options. See HTTPSConnection for more details. + + The optional *cafile* and *capath* parameters specify a set of trusted CA + certificates for HTTPS requests. cafile should point to a single file + containing a bundle of CA certificates, whereas capath should point to a + directory of hashed certificate files. More information can be found in + ssl.SSLContext.load_verify_locations(). + + The *cadefault* parameter is ignored. + + This function always returns an object which can work as a context + manager and has methods such as + + * geturl() - return the URL of the resource retrieved, commonly used to + determine if a redirect was followed + + * info() - return the meta-information of the page, such as headers, in the + form of an email.message_from_string() instance (see Quick Reference to + HTTP Headers) + + * getcode() - return the HTTP status code of the response. Raises URLError + on errors. + + For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse + object slightly modified. In addition to the three new methods above, the + msg attribute contains the same information as the reason attribute --- + the reason phrase returned by the server --- instead of the response + headers as it is specified in the documentation for HTTPResponse. + + For FTP, file, and data URLs and requests explicitly handled by legacy + URLopener and FancyURLopener classes, this function returns a + urllib.response.addinfourl object. + + Note that None may be returned if no handler handles the request (though + the default installed global OpenerDirector uses UnknownHandler to ensure + this never happens). + + In addition, if proxy settings are detected (for example, when a *_proxy + environment variable like http_proxy is set), ProxyHandler is default + installed and makes sure the requests are handled through the proxy. + + cafile, capath and cadefault are deprecated, use a custom context instead."cafile, capath and cadefault are deprecated, use a ""custom context instead."You can't pass both context and any of cafile, capath, and cadefault"You can't pass both context and any of cafile, capath, and ""cadefault"SSL support not availablecreate_default_contextPurposeSERVER_AUTHHTTPSHandlerhttps_handler_url_tempfilesreporthook + Retrieve a URL into a temporary location on disk. + + Requires a URL argument. If a filename is passed, it is used as + the temporary file location. The reporthook argument should be + a callable that accepts a block number, a read size, and the + total file size of the URL target. The data argument should be + valid URL encoded data. + + If a filename is passed and the URL points to a local resource, + the result is a copy from local file to new file. + + Returns a tuple containing the path to the newly created + data file as well as the resulting HTTPMessage object. + url_typetfpblocknumretrieval incomplete: got only %i out of %i bytesClean up temporary files from urlretrieve calls.temp_file:\d+$_cut_port_rerequest_hostReturn request-host, as defined by RFC 2965. + + Variation from RFC: returned value is lowercased, for convenient + comparison. + + full_urlget_headerorigin_req_hostunverifiableunredirected_hdrs{}#{}_full_urlhas_headerremove_headerunknown url type: %rget_methodReturn a string indicating the HTTP request method.default_methodget_full_urlset_proxyhas_proxyadd_unredirected_headerheader_itemsPython-urllib/%sclient_versionUser-agenthandle_openhandle_errorprocess_responseprocess_requestadd_handleradd_parentexpected BaseHandler instance, got %raddedredirect_requestdo_openproxy_open_call_chainmeth_namefullurl_requesturllib.Request_responsedefault_openunknown_openhttp_error_%shttp_errorig_argshttp_error_defaultCreate an opener object from a list of handlers. + + The opener will use several default handlers, including support + for HTTP, FTP and when applicable HTTPS. + + If any of the handlers passed as arguments are subclasses of the + default handlers, the default handlers will not be used. + default_classeshandler_orderProcess HTTP error responses.http_responsehttps_responsemax_repeatsmax_redirectionsnewurlReturn a Request or None in response to a redirect. + + This is called by the http_error_30x methods when a + redirection response is received. If a redirection should + take place, return a new Request to allow http_error_30x to + perform the redirect. Otherwise, raise HTTPError if no-one + else should try to handle this url. Return None if you can't + but another Handler might. + %20CONTENT_HEADERShttp_error_302urlparts%s - Redirection to url '%s' is not allowedpunctuationredirect_dictvisitedinf_msghttp_error_301http_error_303http_error_307The HTTP server returned a redirect error that would lead to an infinite loop. +The last 30x error message was: +"The HTTP server returned a redirect error that would ""lead to an infinite loop.\n""The last 30x error message was:\n"_parse_proxyReturn (scheme, user, password, host/port) given a URL or an authority. + + If a URL is supplied, it must have an authority (host:port) component. + According to RFC 3986, having an authority component means the URL must + have two slashes after the scheme. + r_schemeauthorityproxy URL with no authority: %rhost_separatorhostportproxiesproxies must be a mapping%s_openorig_typeproxy_typeproxy_bypassuser_passcredsProxy-authorizationadd_passwordrealmreduce_urireduced_urifind_user_passwordauthuridomainsreduced_authuriurisauthinfois_suburiAccept authority or URI and extract only the authority and path.dport%s:%dCheck if test is below base in a URI tree + + Both args must be URIs in reduced form. + is_authenticatedupdate_authenticated(?:^|,)[ ]*([^ ,]+)[ ]+realm=(["']?)([^"']*)\2'(?:^|,)''[ \t]*''([^ \t,]+)''[ \t]+''realm=(["\']?)([^"\']*)\\2'rxpassword_mgr_parse_realmfound_challengeBasic Auth Realm was unquotedhttp_error_auth_reqedauthrequnsupportedbasicretry_http_basic_authAbstractBasicAuthHandler does not support the following scheme: %r"AbstractBasicAuthHandler does not ""support the following scheme: %r"pwauth_headerhttp_request{0}:{1}auth_strBasic {}https_requesthttp_error_401www-authenticatehttp_error_407proxy-authenticate_randombytesretriednonce_countlast_noncereset_retry_countdigest auth failedretry_http_digest_authAbstractDigestAuthHandler does not support the following scheme: '%s'"AbstractDigestAuthHandler does not support"" the following scheme: '%s'"challengeparse_keqv_listparse_http_listchalget_authorizationDigest %sauth_valget_cnoncenonce%s:%s:%s:qopopaqueget_algorithm_implsKDget_entity_digestentdig%s:%s:%sA1A2respdig%08xncvaluecnonce%s:%s:%s:%s:%snoncebitqop '%s' is not supported.username="%s", realm="%s", nonce="%s", uri="%s", response="%s"'username="%s", realm="%s", nonce="%s", uri="%s", ''response="%s"', opaque="%s", digest="%s", algorithm="%s", qop=auth, nc=%s, cnonce="%s"SHAUnsupported digest authentication algorithm %r"Unsupported digest authentication ""algorithm %r"An authentication protocol defined by RFC 2069 + + Digest authentication improves on basic authentication because it + does not transmit passwords in the clear. + 490retryProxy-AuthorizationAbstractHTTPHandler_debuglevelset_http_debugleveldo_request_no host givenPOST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str."POST data should be bytes, an iterable of bytes, ""or a file object. It cannot be of type str."Transfer-encodingsel_hostsel_pathhttp_classhttp_conn_argsReturn an HTTPResponse object for the request, using http_class. + + http_class must implement the HTTPConnection API from http.client. + tunnel_headersproxy_auth_hdrhttp_open_check_hostnamehttps_opencookiejarCookieJaradd_cookie_headerextract_cookiesunknown url type: %sParse list of key=value strings where keys are not duplicated.parsedParse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Neither commas nor quotes count if they are escaped. + Only double-quotes count, not single-quotes. + curfile_openfile:// scheme is supported only on localhostopen_local_filemimetypeslocalfilestatsformatdateusegmtmtypeContent-type: %s +Content-length: %d +Last-modified: %s +_safe_gethostbynamefile://origurlfile not on local hostftp_openftplibftp error: no host givenconnect_ftpfwretrfileretrlenContent-type: %s +Content-length: %d +ftp error: %rftpwrapperpersistentsoonestmax_connssetTimeoutsetMaxConnscheck_cachedata_openmediatype;base64text/plain;charset=US-ASCIIContent-type: %s +Content-length: %d +MAXFTPCACHEnturl2pathOS-specific conversion from a relative URL of the 'file' scheme + to a file system path; not recommended for general use.OS-specific conversion from a file system path to a relative URL + of the 'file' scheme; not recommended for general use.ftpcacheClass to open URLs. + This is a class rather than just a subroutine because we may need + more than one set of global protocol-specific options. + Note -- this is a base class for those who don't want the + automatic handling of errors type 302 (relocated) and 401 + (authorization needed).__tempfiles%(class)s style of invoking requests is deprecated. Use newer urlopen functions/methods"%(class)s style of invoking requests is deprecated. ""Use newer urlopen functions/methods"Accept*/*__unlinktempcacheaddheaderAdd a header to be used by the HTTP interface only + e.g. u.addheader('Accept', 'sound/basic')Use URLopener().open(file) instead of open(file, 'r').%/:=&?~#+!$,;'@()*[]|urltypeproxyhostopen_open_unknown_proxyopen_unknownsocket errorOverridable interface to open unknown URL type.url errorunknown url typeinvalid proxy for %sretrieveretrieve(url) returns (filename, headers) for a local object + or (tempfilename, headers) for a remote object.url1_open_generic_httpconnection_factoryMake an HTTP connection using connection_class. + + This is an internal method that should be called from + open_http() or open_https(). + + Arguments: + - connection_factory should take a host name and return an + HTTPConnection instance. + - url is the url to retrieval or a host, relative-path pair. + - data is payload for a POST request or None. + user_passwdproxy_passwdrealhost%s://%s%shttp errorproxy_authBasic %shttp protocol error: bad status linehttp:http_erroropen_httpUse HTTP protocol.Handle http errors. + + Derived class can override this, or provide specific handlers + named http_error_DDD where DDD is the 3-digit error code.http_error_%dDefault error handler: close the connection and raise OSError._https_connectionopen_httpsUse HTTPS protocol.open_fileUse local file or FTP depending on form of URL.file error: proxy support for file protocol currently not implementedlocalhost/Use local file.localnameContent-Type: %s +Content-Length: %d +Last-modified: %s +urlfilethishostlocal file url may start with / or file:. Unknown url of type: %slocal file error: not on local hostopen_ftpUse FTP protocol.ftp error: proxy support for ftp protocol currently not implementedftp:Content-Type: %s +Content-Length: %d +ftperrorsftp error %ropen_dataUse "data" URL.data error: proxy support for data protocol currently not implementeddata errorbad data URLDate: %s%a, %d %b %Y %H:%M:%S GMTContent-type: %sContent-Length: %dDerived class with handlers for errors we can handle (perhaps).auth_cachemaxtriesDefault error handling -- don't raise an exception.Error 302 -- relocated (temporarily).http_error_500Internal Server Error: Redirect Recursionredirect_internal Redirection to url '%s' is not allowed.Error 301 -- also relocated (permanently).Error 303 -- also relocated (essentially identical to 302).Error 307 -- relocated, but turn POST into error.Error 401 -- authentication required. + This function supports Basic authentication only.[ ]*([^ ]+)[ ]+realm="([^"]*)"retry__basic_authError 407 -- proxy authentication required. + This function supports Basic authentication only.retry_proxy_retry_proxy_http_basic_authproxyselectorget_user_passwd%s:%s@%sretry_proxy_https_basic_authretry_https_basic_authprompt_user_passwdOverride this in a GUI environment!getpassEnter username for %s at %s: Enter password for %s in %s at %s: _localhostReturn the IP address of the magic hostname 'localhost'._thishostReturn the IP addresses of the current host._ftperrorsReturn the set of errors raised by the FTP class._noheadersnoheadersReturn an empty email Message object.Class used by open_ftp() for cache of open FTP connections.refcountkeepalivebusyendtransfer550LIST file_closeftpobjreal_closegetproxies_environmentReturn a dictionary of scheme -> proxy server URL mappings. + + Scan the environment for variables named _proxy; + this seems to be the standard convention. If you need a + different way, you can pass a proxies dictionary to the + [Fancy]URLopener constructor. + + REQUEST_METHODproxy_bypass_environmentTest if proxies should not be used for a particular host. + + Checks the proxy dict for the value of no_proxy, which should + be a list of comma separated DNS suffixes, or '*' for all hosts. + + no_proxyhostonly_proxy_bypass_macosx_sysconfproxy_settings + Return True iff this host shouldn't be accessed using a proxy + + This function uses the MacOSX framework SystemConfiguration + to fetch the proxy information. + + proxy_settings come from _scproxy._get_proxy_settings or get mocked ie: + { 'exclude_simple': bool, + 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16'] + } + ip2numipAddrexclude_simplehostIP(\d+(?:\.\d+)*)(/\d+)?proxy_bypass_macosx_sysconfgetproxies_macosx_sysconfReturn a dictionary of scheme -> proxy server URL mappings. + + This function uses the MacOSX framework SystemConfiguration + to fetch the proxy information. + Return True, if host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or from the MacOSX framework SystemConfiguration. + + getproxies_registryReturn a dictionary of scheme -> proxy server URL mappings. + + Win32 uses the registry to store proxies. + + Software\Microsoft\Windows\CurrentVersion\Internet SettingsinternetSettingsProxyEnableproxyEnableProxyServerproxyServer(?:[^/:]+)://%s://%shttp://%shttps://%sftp://%sCloseReturn a dictionary of scheme -> proxy server URL mappings. + + Returns settings gathered from the environment, if specified, + or the registry. + + proxy_bypass_registryProxyOverrideproxyOverriderawHostgetfqdnfqdn\.Return True, if host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + + # XXX issues:# If an authentication error handler that tries to perform# authentication for some reason but fails, how should the error be# signalled? The client needs to know the HTTP error code. But if# the handler knows that the problem was, e.g., that it didn't know# that hash algo that requested in the challenge, it would be good to# pass that information along to the client, too.# ftp errors aren't handled cleanly# check digest against correct (i.e. non-apache) implementation# Possible extensions:# complex proxies XXX not sure what exactly was meant by this# abstract factory for opener# check for SSL# Classes# Functions# Legacy interface# Just return the local path and the "headers" for file://# URLs. No sense in performing a copy unless requested.# Handle temporary file setup.# copied from cookielib.py# remove port, if present# unwrap('') --> 'type://host/path'# issue 16464# if we change data we need to remove content-length header# (cause it's most probably calculated for previous value)# useful for something like authentication# will not be added to a redirected request# self.handlers is retained only for backward compatibility# manage the individual handlers# oops, coincidental match# Only exists for backwards compatibility.# Handlers raise an exception if no one else should try to handle# the request, or return None if they can't but another handler# could. Otherwise, they return the response.# accept a URL or a Request object# pre-process request# post-process response# XXX http[s] protocols are special-cased# https is not different than http# YUCK!# XXX probably also want an abstract factory that knows when it makes# sense to skip a superclass in favor of a subclass and when it might# make sense to include both# Only exists for backwards compatibility# Try to preserve the old behavior of having custom classes# inserted after default ones (works only for custom user# classes which are not aware of handler_order).# after all other processing# According to RFC 2616, "2xx" code indicates that the client's# request was successfully received, understood, and accepted.# maximum number of redirections to any single URL# this is needed because of the state that cookies introduce# maximum total number of redirections (regardless of URL) before# assuming we're in a loop# Strictly (according to RFC 2616), 301 or 302 in response to# a POST MUST NOT cause a redirection without confirmation# from the user (of urllib.request, in this case). In practice,# essentially all clients do redirect in this case, so we do# the same.# Be conciliant with URIs containing a space. This is mainly# redundant with the more complete encoding done in http_error_302(),# but it is kept for compatibility with other callers.# Implementation note: To avoid the server sending us into an# infinite loop, the request object needs to track what URLs we# have already seen. Do this by adding a handler-specific# attribute to the Request object.# Some servers (incorrectly) return multiple Location headers# (so probably same goes for URI). Use first header.# fix a possible malformed URL# For security reasons we don't allow redirection to anything other# than http, https or ftp.# http.client.parse_headers() decodes as ISO-8859-1. Recover the# original bytes and percent-encode non-ASCII bytes, and any special# characters such as the space.# XXX Probably want to forget about the state of the current# request, although that might interact poorly with other# handlers that also use handler-specific request attributes# loop detection# .redirect_dict has a key url if url was previously visited.# Don't close the fp until we are sure that we won't use it# with HTTPError.# authority# URL# We have an authority, so for RFC 3986-compliant URLs (by ss 3.# and 3.3.), path is empty or starts with '/'# Proxies must be in front# let other handlers take care of it# need to start over, because the other handlers don't# grok the proxy's URL type# e.g. if we have a constructor arg proxies like so:# {'http': 'ftp://proxy.example.com'}, we may end up turning# a request for http://acme.example.com/a into one for# ftp://proxy.example.com/a# uri could be a single URI or a sequence# note HTTP URLs do not have a userinfo component# URI# host or host:port# Add a default for prior auth requests# XXX this allows for multiple auth-schemes, but will stupidly pick# the last one with a realm specified.# allow for double- and single-quoted realm values# (single quotes are a violation of the RFC, but appear in the wild)# start of the string or ','# optional whitespaces# scheme like "Basic"# mandatory whitespaces# realm=xxx# realm='xxx'# realm="xxx"# XXX could pre-emptively send auth info already accepted (RFC 2617,# end of section 2, and section 1.2 immediately after "credentials"# production).# parse WWW-Authenticate header: accept multiple challenges per header# host may be an authority (without userinfo) or a URL with an# no header found# Use the first matching Basic challenge.# Ignore following challenges even if they use the Basic# scheme.# http_error_auth_reqed requires that there is no userinfo component in# authority. Assume there isn't one, since urllib.request does not (and# should not, RFC 3986 s. 3.2.1) support requests for URLs containing# userinfo.# Return n random bytes.# Digest authentication is specified in RFC 2617.# XXX The client does not inspect the Authentication-Info header# in a successful response.# XXX It should be possible to test this implementation against# a mock server that just generates a static set of challenges.# XXX qop="auth-int" supports is shaky# Don't fail endlessly - if we failed once, we'll probably# fail a second time. Hm. Unless the Password Manager is# prompting for the information. Crap. This isn't great# but it's better than the current 'repeat until recursion# depth exceeded' approach # The cnonce-value is an opaque# quoted string value provided by the client and used by both client# and server to avoid chosen plaintext attacks, to provide mutual# authentication, and to provide some message integrity protection.# This isn't a fabulous effort, but it's probably Good Enough.# mod_digest doesn't send an opaque, even though it isn't# supposed to be optional# XXX not implemented yet# XXX selector: what about proxies and full urls# NOTE: As per RFC 2617, when server sends "auth,auth-int", the client could use either `auth`# or `auth-int` to the response back. we use `auth` to send the response back.# XXX handle auth-int.# XXX should the partial digests be encoded too?# lambdas assume digest modules are imported at the top level# XXX MD5-sess# before Basic auth# POST# will parse host:port# TODO(jhylton): Should this be redesigned to handle# persistent connections?# We want to make an HTTP/1.1 request, but the addinfourl# class isn't prepared to deal with a persistent connection.# It will try to read all remaining data from the socket,# which will block while the server waits for the next request.# So make sure the connection gets closed after the (only)# request.# Proxy-Authorization should not be sent to origin# server.# timeout error# If the server does not send us a 'Connection: close' header,# HTTPConnection assumes the socket should be left open. Manually# mark the socket to be closed when this response object goes away.# This line replaces the .msg attribute of the HTTPResponse# with .headers, because urllib clients expect the response to# have the reason in .msg. It would be good to mark this# attribute is deprecated and get then to use info() or# .headers.# append last part# Use local file or FTP depending on form of URL# names for the localhost# not entirely sure what the rules are here# username/password handling# XXX would be nice to have pluggable cache strategies# XXX this stuff is definitely not thread safe# first check for old ones# then check the size# data URLs as specified in RFC 2397.# ignores POSTed data# syntax:# even base64 encoded data URLs might be quoted so unquote in any case:# Code move from the old urllib module# Trim the ftp cache beyond this size# Helper for non-unix systems# Constructor# See cleanup()# Undocumented feature: if you assign {} to tempcache,# it is used to cache files retrieved with# self.retrieve(). This is not enabled by default# since it does not work for changing documents (and I# haven't got the logic to check expiration headers# yet).# Undocumented feature: you can use a different# ftp cache by assigning to the .ftpcache member;# in case you want logically independent URL openers# XXX This is not threadsafe. Bah.# This code sometimes runs when the rest of this module# has already been deleted, so it can't use any globals# or import anything.# External interface# Signal special case to open_*()# raise exception if actual size does not match content-length header# Each method named open_ knows how to open that type of URL# check whether the proxy contains authorization information# now we proceed with the url we want to obtain# Add Connection:close as we don't support persistent connections yet.# This helps in closing the socket and avoiding ResourceWarning# something went wrong with the HTTP status line# First check if there's a specific handler for this error# XXX thread unsafe!# Prune the cache, rather arbitrarily# ignore POSTed data# XXX is this encoding/decoding ok?#f.fileno = None # needed for addinfourl# In case the server sent a relative URL, join with original:# For security reasons, we don't allow redirection to anything other# than http, https and ftp.# We are using newer HTTPError with older redirect_internal method# This older method will get deprecated in 3.3# Utility classes# Try to retrieve as a file# Set transfer mode to ASCII!# Try a directory listing. Verify that directory exists.# Pass back both a suitably decorated object and a retrieval length# Proxy handling# in order to prefer lowercase variables, process environment in# two passes: first matches any, second pass matches lowercase only# CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY# (non-all-lowercase) as it may be set from the web server by a "Proxy:"# header from the client# If "proxy" is lowercase, it will still be used thanks to the next block# don't bypass, if no_proxy isn't specified# '*' is special case for always bypass# strip port off host# check if the host ends with any of the DNS suffixes# ignore leading dots# otherwise, don't bypass# This code tests an OSX specific data structure but is testable on all# Check for simple host names:# Items in the list are strings like these: *.local, 169.254/16# System libraries ignore invalid prefix lengths# Std module, so should be around - but you never know!# Returned as Unicode but problems if not converted to ASCII# Per-protocol settings# See if address has a type:// prefix# Use one setting for all protocols# Either registry key not found etc, or the value in an# unexpected format.# proxies already set up to be empty so nothing to do# Std modules, so should be around - but you never know!# ^^^^ Returned as Unicode but problems if not converted to ASCII# try to make a host list from name and IP address.# make a check value list from the registry entry: replace the# '' string by the localhost entry and the corresponding# canonical entry.# now check if we match one of the registry values.# mask dots# change glob sequence# change glob char# By default use environment variablesb'An extensible library for opening URLs using a variety of protocols + +The simplest way to use this module is to call the urlopen function, +which accepts a string containing a URL or a Request object (described +below). It opens the URL and returns the results as file-like +object; the returned object has some extra methods described below. + +The OpenerDirector manages a collection of Handler objects that do +all the actual work. Each Handler implements a particular protocol or +option. The OpenerDirector is a composite object that invokes the +Handlers needed to open the requested URL. For example, the +HTTPHandler performs HTTP GET and POST requests and deals with +non-error returns. The HTTPRedirectHandler automatically deals with +HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler +deals with digest authentication. + +urlopen(url, data=None) -- Basic usage is the same as original +urllib. pass the url and optionally data to post to an HTTP URL, and +get a file-like object back. One difference is that you can also pass +a Request instance instead of URL. Raises a URLError (subclass of +OSError); for HTTP errors, raises an HTTPError, which can also be +treated as a valid response. + +build_opener -- Function that creates a new OpenerDirector instance. +Will install the default handlers. Accepts one or more Handlers as +arguments, either instances or Handler classes that it will +instantiate. If one of the argument is a subclass of the default +handler, the argument will be installed instead of the default. + +install_opener -- Installs a new opener as the default opener. + +objects of interest: + +OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages +the Handler classes, while dealing with requests and responses. + +Request -- An object that encapsulates the state of a request. The +state can be as simple as the URL. It can also include extra HTTP +headers, e.g. a User-Agent. + +BaseHandler -- + +internals: +BaseHandler and parent +_call_chain conventions + +Example usage: + +import urllib.request + +# set up authentication info +authinfo = urllib.request.HTTPBasicAuthHandler() +authinfo.add_password(realm='PDQ Application', + uri='https://mahler:8092/site-updates.py', + user='klem', + passwd='geheim$parole') + +proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) + +# build a new opener that adds authentication and caching FTP handlers +opener = urllib.request.build_opener(proxy_support, authinfo, + urllib.request.CacheFTPHandler) + +# install it +urllib.request.install_opener(opener) + +f = urllib.request.urlopen('http://www.python.org/') +'u'An extensible library for opening URLs using a variety of protocols + +The simplest way to use this module is to call the urlopen function, +which accepts a string containing a URL or a Request object (described +below). It opens the URL and returns the results as file-like +object; the returned object has some extra methods described below. + +The OpenerDirector manages a collection of Handler objects that do +all the actual work. Each Handler implements a particular protocol or +option. The OpenerDirector is a composite object that invokes the +Handlers needed to open the requested URL. For example, the +HTTPHandler performs HTTP GET and POST requests and deals with +non-error returns. The HTTPRedirectHandler automatically deals with +HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler +deals with digest authentication. + +urlopen(url, data=None) -- Basic usage is the same as original +urllib. pass the url and optionally data to post to an HTTP URL, and +get a file-like object back. One difference is that you can also pass +a Request instance instead of URL. Raises a URLError (subclass of +OSError); for HTTP errors, raises an HTTPError, which can also be +treated as a valid response. + +build_opener -- Function that creates a new OpenerDirector instance. +Will install the default handlers. Accepts one or more Handlers as +arguments, either instances or Handler classes that it will +instantiate. If one of the argument is a subclass of the default +handler, the argument will be installed instead of the default. + +install_opener -- Installs a new opener as the default opener. + +objects of interest: + +OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages +the Handler classes, while dealing with requests and responses. + +Request -- An object that encapsulates the state of a request. The +state can be as simple as the URL. It can also include extra HTTP +headers, e.g. a User-Agent. + +BaseHandler -- + +internals: +BaseHandler and parent +_call_chain conventions + +Example usage: + +import urllib.request + +# set up authentication info +authinfo = urllib.request.HTTPBasicAuthHandler() +authinfo.add_password(realm='PDQ Application', + uri='https://mahler:8092/site-updates.py', + user='klem', + passwd='geheim$parole') + +proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) + +# build a new opener that adds authentication and caching FTP handlers +opener = urllib.request.build_opener(proxy_support, authinfo, + urllib.request.CacheFTPHandler) + +# install it +urllib.request.install_opener(opener) + +f = urllib.request.urlopen('http://www.python.org/') +'b'Request'u'Request'b'OpenerDirector'u'OpenerDirector'b'BaseHandler'u'BaseHandler'b'HTTPDefaultErrorHandler'u'HTTPDefaultErrorHandler'b'HTTPRedirectHandler'u'HTTPRedirectHandler'b'HTTPCookieProcessor'u'HTTPCookieProcessor'b'ProxyHandler'u'ProxyHandler'b'HTTPPasswordMgr'u'HTTPPasswordMgr'b'HTTPPasswordMgrWithDefaultRealm'u'HTTPPasswordMgrWithDefaultRealm'b'HTTPPasswordMgrWithPriorAuth'u'HTTPPasswordMgrWithPriorAuth'b'AbstractBasicAuthHandler'u'AbstractBasicAuthHandler'b'HTTPBasicAuthHandler'u'HTTPBasicAuthHandler'b'ProxyBasicAuthHandler'u'ProxyBasicAuthHandler'b'AbstractDigestAuthHandler'u'AbstractDigestAuthHandler'b'HTTPDigestAuthHandler'u'HTTPDigestAuthHandler'b'ProxyDigestAuthHandler'u'ProxyDigestAuthHandler'b'HTTPHandler'u'HTTPHandler'b'FTPHandler'u'FTPHandler'b'CacheFTPHandler'u'CacheFTPHandler'b'DataHandler'u'DataHandler'b'UnknownHandler'u'UnknownHandler'b'HTTPErrorProcessor'u'HTTPErrorProcessor'b'install_opener'u'install_opener'b'build_opener'u'build_opener'b'URLopener'u'URLopener'b'FancyURLopener'u'FancyURLopener'b'Open the URL url, which can be either a string or a Request object. + + *data* must be an object specifying additional data to be sent to + the server, or None if no such data is needed. See Request for + details. + + urllib.request module uses HTTP/1.1 and includes a "Connection:close" + header in its HTTP requests. + + The optional *timeout* parameter specifies a timeout in seconds for + blocking operations like the connection attempt (if not specified, the + global default timeout setting will be used). This only works for HTTP, + HTTPS and FTP connections. + + If *context* is specified, it must be a ssl.SSLContext instance describing + the various SSL options. See HTTPSConnection for more details. + + The optional *cafile* and *capath* parameters specify a set of trusted CA + certificates for HTTPS requests. cafile should point to a single file + containing a bundle of CA certificates, whereas capath should point to a + directory of hashed certificate files. More information can be found in + ssl.SSLContext.load_verify_locations(). + + The *cadefault* parameter is ignored. + + This function always returns an object which can work as a context + manager and has methods such as + + * geturl() - return the URL of the resource retrieved, commonly used to + determine if a redirect was followed + + * info() - return the meta-information of the page, such as headers, in the + form of an email.message_from_string() instance (see Quick Reference to + HTTP Headers) + + * getcode() - return the HTTP status code of the response. Raises URLError + on errors. + + For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse + object slightly modified. In addition to the three new methods above, the + msg attribute contains the same information as the reason attribute --- + the reason phrase returned by the server --- instead of the response + headers as it is specified in the documentation for HTTPResponse. + + For FTP, file, and data URLs and requests explicitly handled by legacy + URLopener and FancyURLopener classes, this function returns a + urllib.response.addinfourl object. + + Note that None may be returned if no handler handles the request (though + the default installed global OpenerDirector uses UnknownHandler to ensure + this never happens). + + In addition, if proxy settings are detected (for example, when a *_proxy + environment variable like http_proxy is set), ProxyHandler is default + installed and makes sure the requests are handled through the proxy. + + 'u'Open the URL url, which can be either a string or a Request object. + + *data* must be an object specifying additional data to be sent to + the server, or None if no such data is needed. See Request for + details. + + urllib.request module uses HTTP/1.1 and includes a "Connection:close" + header in its HTTP requests. + + The optional *timeout* parameter specifies a timeout in seconds for + blocking operations like the connection attempt (if not specified, the + global default timeout setting will be used). This only works for HTTP, + HTTPS and FTP connections. + + If *context* is specified, it must be a ssl.SSLContext instance describing + the various SSL options. See HTTPSConnection for more details. + + The optional *cafile* and *capath* parameters specify a set of trusted CA + certificates for HTTPS requests. cafile should point to a single file + containing a bundle of CA certificates, whereas capath should point to a + directory of hashed certificate files. More information can be found in + ssl.SSLContext.load_verify_locations(). + + The *cadefault* parameter is ignored. + + This function always returns an object which can work as a context + manager and has methods such as + + * geturl() - return the URL of the resource retrieved, commonly used to + determine if a redirect was followed + + * info() - return the meta-information of the page, such as headers, in the + form of an email.message_from_string() instance (see Quick Reference to + HTTP Headers) + + * getcode() - return the HTTP status code of the response. Raises URLError + on errors. + + For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse + object slightly modified. In addition to the three new methods above, the + msg attribute contains the same information as the reason attribute --- + the reason phrase returned by the server --- instead of the response + headers as it is specified in the documentation for HTTPResponse. + + For FTP, file, and data URLs and requests explicitly handled by legacy + URLopener and FancyURLopener classes, this function returns a + urllib.response.addinfourl object. + + Note that None may be returned if no handler handles the request (though + the default installed global OpenerDirector uses UnknownHandler to ensure + this never happens). + + In addition, if proxy settings are detected (for example, when a *_proxy + environment variable like http_proxy is set), ProxyHandler is default + installed and makes sure the requests are handled through the proxy. + + 'b'cafile, capath and cadefault are deprecated, use a custom context instead.'u'cafile, capath and cadefault are deprecated, use a custom context instead.'b'You can't pass both context and any of cafile, capath, and cadefault'u'You can't pass both context and any of cafile, capath, and cadefault'b'SSL support not available'u'SSL support not available'b' + Retrieve a URL into a temporary location on disk. + + Requires a URL argument. If a filename is passed, it is used as + the temporary file location. The reporthook argument should be + a callable that accepts a block number, a read size, and the + total file size of the URL target. The data argument should be + valid URL encoded data. + + If a filename is passed and the URL points to a local resource, + the result is a copy from local file to new file. + + Returns a tuple containing the path to the newly created + data file as well as the resulting HTTPMessage object. + 'u' + Retrieve a URL into a temporary location on disk. + + Requires a URL argument. If a filename is passed, it is used as + the temporary file location. The reporthook argument should be + a callable that accepts a block number, a read size, and the + total file size of the URL target. The data argument should be + valid URL encoded data. + + If a filename is passed and the URL points to a local resource, + the result is a copy from local file to new file. + + Returns a tuple containing the path to the newly created + data file as well as the resulting HTTPMessage object. + 'b'retrieval incomplete: got only %i out of %i bytes'u'retrieval incomplete: got only %i out of %i bytes'b'Clean up temporary files from urlretrieve calls.'u'Clean up temporary files from urlretrieve calls.'b':\d+$'u':\d+$'b'Return request-host, as defined by RFC 2965. + + Variation from RFC: returned value is lowercased, for convenient + comparison. + + 'u'Return request-host, as defined by RFC 2965. + + Variation from RFC: returned value is lowercased, for convenient + comparison. + + 'b'{}#{}'u'{}#{}'b'unknown url type: %r'u'unknown url type: %r'b'Return a string indicating the HTTP request method.'u'Return a string indicating the HTTP request method.'b'Python-urllib/%s'u'Python-urllib/%s'b'User-agent'u'User-agent'b'add_parent'u'add_parent'b'expected BaseHandler instance, got %r'u'expected BaseHandler instance, got %r'b'redirect_request'u'redirect_request'b'do_open'u'do_open'b'proxy_open'u'proxy_open'b'response'u'response'b'request'u'request'b'_request'u'_request'b'urllib.Request'u'urllib.Request'b'_response'u'_response'b'default_open'u'default_open'b'_open'u'_open'b'unknown_open'u'unknown_open'b'http_error_%s'u'http_error_%s'b'_error'u'_error'b'http_error_default'u'http_error_default'b'Create an opener object from a list of handlers. + + The opener will use several default handlers, including support + for HTTP, FTP and when applicable HTTPS. + + If any of the handlers passed as arguments are subclasses of the + default handlers, the default handlers will not be used. + 'u'Create an opener object from a list of handlers. + + The opener will use several default handlers, including support + for HTTP, FTP and when applicable HTTPS. + + If any of the handlers passed as arguments are subclasses of the + default handlers, the default handlers will not be used. + 'b'handler_order'u'handler_order'b'Process HTTP error responses.'u'Process HTTP error responses.'b'Return a Request or None in response to a redirect. + + This is called by the http_error_30x methods when a + redirection response is received. If a redirection should + take place, return a new Request to allow http_error_30x to + perform the redirect. Otherwise, raise HTTPError if no-one + else should try to handle this url. Return None if you can't + but another Handler might. + 'u'Return a Request or None in response to a redirect. + + This is called by the http_error_30x methods when a + redirection response is received. If a redirection should + take place, return a new Request to allow http_error_30x to + perform the redirect. Otherwise, raise HTTPError if no-one + else should try to handle this url. Return None if you can't + but another Handler might. + 'b'%20'u'%20'b'uri'u'uri'b'%s - Redirection to url '%s' is not allowed'u'%s - Redirection to url '%s' is not allowed'b'redirect_dict'u'redirect_dict'b'The HTTP server returned a redirect error that would lead to an infinite loop. +The last 30x error message was: +'u'The HTTP server returned a redirect error that would lead to an infinite loop. +The last 30x error message was: +'b'Return (scheme, user, password, host/port) given a URL or an authority. + + If a URL is supplied, it must have an authority (host:port) component. + According to RFC 3986, having an authority component means the URL must + have two slashes after the scheme. + 'u'Return (scheme, user, password, host/port) given a URL or an authority. + + If a URL is supplied, it must have an authority (host:port) component. + According to RFC 3986, having an authority component means the URL must + have two slashes after the scheme. + 'b'proxy URL with no authority: %r'u'proxy URL with no authority: %r'b'proxies must be a mapping'u'proxies must be a mapping'b'%s_open'u'%s_open'b'Proxy-authorization'u'Proxy-authorization'b'Accept authority or URI and extract only the authority and path.'u'Accept authority or URI and extract only the authority and path.'b'%s:%d'u'%s:%d'b'Check if test is below base in a URI tree + + Both args must be URIs in reduced form. + 'u'Check if test is below base in a URI tree + + Both args must be URIs in reduced form. + 'b'(?:^|,)[ ]*([^ ,]+)[ ]+realm=(["']?)([^"']*)\2'u'(?:^|,)[ ]*([^ ,]+)[ ]+realm=(["']?)([^"']*)\2'b'Basic Auth Realm was unquoted'u'Basic Auth Realm was unquoted'b'basic'u'basic'b'AbstractBasicAuthHandler does not support the following scheme: %r'u'AbstractBasicAuthHandler does not support the following scheme: %r'b'is_authenticated'u'is_authenticated'b'{0}:{1}'u'{0}:{1}'b'Basic {}'u'Basic {}'b'www-authenticate'u'www-authenticate'b'proxy-authenticate'u'proxy-authenticate'b'digest auth failed'u'digest auth failed'b'digest'u'digest'b'AbstractDigestAuthHandler does not support the following scheme: '%s''u'AbstractDigestAuthHandler does not support the following scheme: '%s''b'Digest %s'u'Digest %s'b'%s:%s:%s:'u'%s:%s:%s:'b'realm'u'realm'b'nonce'u'nonce'b'qop'u'qop'b'algorithm'u'algorithm'b'opaque'u'opaque'b'%s:%s:%s'u'%s:%s:%s'b'%08x'u'%08x'b'%s:%s:%s:%s:%s'u'%s:%s:%s:%s:%s'b'qop '%s' is not supported.'u'qop '%s' is not supported.'b'username="%s", realm="%s", nonce="%s", uri="%s", response="%s"'u'username="%s", realm="%s", nonce="%s", uri="%s", response="%s"'b', opaque="%s"'u', opaque="%s"'b', digest="%s"'u', digest="%s"'b', algorithm="%s"'u', algorithm="%s"'b', qop=auth, nc=%s, cnonce="%s"'u', qop=auth, nc=%s, cnonce="%s"'b'SHA'u'SHA'b'Unsupported digest authentication algorithm %r'u'Unsupported digest authentication algorithm %r'b'An authentication protocol defined by RFC 2069 + + Digest authentication improves on basic authentication because it + does not transmit passwords in the clear. + 'u'An authentication protocol defined by RFC 2069 + + Digest authentication improves on basic authentication because it + does not transmit passwords in the clear. + 'b'Proxy-Authorization'u'Proxy-Authorization'b'no host given'u'no host given'b'POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.'u'POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.'b'Transfer-encoding'u'Transfer-encoding'b'Return an HTTPResponse object for the request, using http_class. + + http_class must implement the HTTPConnection API from http.client. + 'u'Return an HTTPResponse object for the request, using http_class. + + http_class must implement the HTTPConnection API from http.client. + 'b'HTTPSHandler'u'HTTPSHandler'b'unknown url type: %s'u'unknown url type: %s'b'Parse list of key=value strings where keys are not duplicated.'u'Parse list of key=value strings where keys are not duplicated.'b'Parse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Neither commas nor quotes count if they are escaped. + Only double-quotes count, not single-quotes. + 'u'Parse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Neither commas nor quotes count if they are escaped. + Only double-quotes count, not single-quotes. + 'b'file:// scheme is supported only on localhost'u'file:// scheme is supported only on localhost'b'Content-type: %s +Content-length: %d +Last-modified: %s +'u'Content-type: %s +Content-length: %d +Last-modified: %s +'b'file://'u'file://'b'file not on local host'u'file not on local host'b'ftp error: no host given'u'ftp error: no host given'b'Content-type: %s +'u'Content-type: %s +'b'Content-length: %d +'u'Content-length: %d +'b'ftp error: %r'u'ftp error: %r'b';base64'u';base64'b'text/plain;charset=US-ASCII'u'text/plain;charset=US-ASCII'b'Content-type: %s +Content-length: %d +'u'Content-type: %s +Content-length: %d +'b'OS-specific conversion from a relative URL of the 'file' scheme + to a file system path; not recommended for general use.'u'OS-specific conversion from a relative URL of the 'file' scheme + to a file system path; not recommended for general use.'b'OS-specific conversion from a file system path to a relative URL + of the 'file' scheme; not recommended for general use.'u'OS-specific conversion from a file system path to a relative URL + of the 'file' scheme; not recommended for general use.'b'Class to open URLs. + This is a class rather than just a subroutine because we may need + more than one set of global protocol-specific options. + Note -- this is a base class for those who don't want the + automatic handling of errors type 302 (relocated) and 401 + (authorization needed).'u'Class to open URLs. + This is a class rather than just a subroutine because we may need + more than one set of global protocol-specific options. + Note -- this is a base class for those who don't want the + automatic handling of errors type 302 (relocated) and 401 + (authorization needed).'b'%(class)s style of invoking requests is deprecated. Use newer urlopen functions/methods'u'%(class)s style of invoking requests is deprecated. Use newer urlopen functions/methods'b'key_file'u'key_file'b'cert_file'u'cert_file'b'Accept'u'Accept'b'*/*'u'*/*'b'Add a header to be used by the HTTP interface only + e.g. u.addheader('Accept', 'sound/basic')'u'Add a header to be used by the HTTP interface only + e.g. u.addheader('Accept', 'sound/basic')'b'Use URLopener().open(file) instead of open(file, 'r').'u'Use URLopener().open(file) instead of open(file, 'r').'b'%/:=&?~#+!$,;'@()*[]|'u'%/:=&?~#+!$,;'@()*[]|'b'open_'u'open_'b'open_local_file'u'open_local_file'b'socket error'u'socket error'b'Overridable interface to open unknown URL type.'u'Overridable interface to open unknown URL type.'b'url error'u'url error'b'unknown url type'u'unknown url type'b'invalid proxy for %s'u'invalid proxy for %s'b'retrieve(url) returns (filename, headers) for a local object + or (tempfilename, headers) for a remote object.'u'retrieve(url) returns (filename, headers) for a local object + or (tempfilename, headers) for a remote object.'b'Make an HTTP connection using connection_class. + + This is an internal method that should be called from + open_http() or open_https(). + + Arguments: + - connection_factory should take a host name and return an + HTTPConnection instance. + - url is the url to retrieval or a host, relative-path pair. + - data is payload for a POST request or None. + 'u'Make an HTTP connection using connection_class. + + This is an internal method that should be called from + open_http() or open_https(). + + Arguments: + - connection_factory should take a host name and return an + HTTPConnection instance. + - url is the url to retrieval or a host, relative-path pair. + - data is payload for a POST request or None. + 'b'%s://%s%s'u'%s://%s%s'b'http error'u'http error'b'Basic %s'u'Basic %s'b'http protocol error: bad status line'u'http protocol error: bad status line'b'http:'u'http:'b'Use HTTP protocol.'u'Use HTTP protocol.'b'Handle http errors. + + Derived class can override this, or provide specific handlers + named http_error_DDD where DDD is the 3-digit error code.'u'Handle http errors. + + Derived class can override this, or provide specific handlers + named http_error_DDD where DDD is the 3-digit error code.'b'http_error_%d'u'http_error_%d'b'Default error handler: close the connection and raise OSError.'u'Default error handler: close the connection and raise OSError.'b'Use HTTPS protocol.'u'Use HTTPS protocol.'b'Use local file or FTP depending on form of URL.'u'Use local file or FTP depending on form of URL.'b'file error: proxy support for file protocol currently not implemented'u'file error: proxy support for file protocol currently not implemented'b'localhost/'u'localhost/'b'Use local file.'u'Use local file.'b'Content-Type: %s +Content-Length: %d +Last-modified: %s +'u'Content-Type: %s +Content-Length: %d +Last-modified: %s +'b'local file url may start with / or file:. Unknown url of type: %s'u'local file url may start with / or file:. Unknown url of type: %s'b'local file error: not on local host'u'local file error: not on local host'b'Use FTP protocol.'u'Use FTP protocol.'b'ftp error: proxy support for ftp protocol currently not implemented'u'ftp error: proxy support for ftp protocol currently not implemented'b'ftp:'u'ftp:'b'Content-Type: %s +'u'Content-Type: %s +'b'Content-Length: %d +'u'Content-Length: %d +'b'ftp error %r'u'ftp error %r'b'Use "data" URL.'u'Use "data" URL.'b'data error: proxy support for data protocol currently not implemented'u'data error: proxy support for data protocol currently not implemented'b'data error'u'data error'b'bad data URL'u'bad data URL'b'Date: %s'u'Date: %s'b'%a, %d %b %Y %H:%M:%S GMT'u'%a, %d %b %Y %H:%M:%S GMT'b'Content-type: %s'u'Content-type: %s'b'Content-Length: %d'u'Content-Length: %d'b'Derived class with handlers for errors we can handle (perhaps).'u'Derived class with handlers for errors we can handle (perhaps).'b'Default error handling -- don't raise an exception.'u'Default error handling -- don't raise an exception.'b'Error 302 -- relocated (temporarily).'u'Error 302 -- relocated (temporarily).'b'http_error_500'u'http_error_500'b'Internal Server Error: Redirect Recursion'u'Internal Server Error: Redirect Recursion'b' Redirection to url '%s' is not allowed.'u' Redirection to url '%s' is not allowed.'b'Error 301 -- also relocated (permanently).'u'Error 301 -- also relocated (permanently).'b'Error 303 -- also relocated (essentially identical to 302).'u'Error 303 -- also relocated (essentially identical to 302).'b'Error 307 -- relocated, but turn POST into error.'u'Error 307 -- relocated, but turn POST into error.'b'Error 401 -- authentication required. + This function supports Basic authentication only.'u'Error 401 -- authentication required. + This function supports Basic authentication only.'b'[ ]*([^ ]+)[ ]+realm="([^"]*)"'u'[ ]*([^ ]+)[ ]+realm="([^"]*)"'b'retry_'u'retry_'b'_basic_auth'u'_basic_auth'b'Error 407 -- proxy authentication required. + This function supports Basic authentication only.'u'Error 407 -- proxy authentication required. + This function supports Basic authentication only.'b'retry_proxy_'u'retry_proxy_'b'%s:%s@%s'u'%s:%s@%s'b'Override this in a GUI environment!'u'Override this in a GUI environment!'b'Enter username for %s at %s: 'u'Enter username for %s at %s: 'b'Enter password for %s in %s at %s: 'u'Enter password for %s in %s at %s: 'b'Return the IP address of the magic hostname 'localhost'.'u'Return the IP address of the magic hostname 'localhost'.'b'Return the IP addresses of the current host.'u'Return the IP addresses of the current host.'b'Return the set of errors raised by the FTP class.'u'Return the set of errors raised by the FTP class.'b'Return an empty email Message object.'u'Return an empty email Message object.'b'Class used by open_ftp() for cache of open FTP connections.'u'Class used by open_ftp() for cache of open FTP connections.'b'550'u'550'b'LIST 'u'LIST 'b'Return a dictionary of scheme -> proxy server URL mappings. + + Scan the environment for variables named _proxy; + this seems to be the standard convention. If you need a + different way, you can pass a proxies dictionary to the + [Fancy]URLopener constructor. + + 'u'Return a dictionary of scheme -> proxy server URL mappings. + + Scan the environment for variables named _proxy; + this seems to be the standard convention. If you need a + different way, you can pass a proxies dictionary to the + [Fancy]URLopener constructor. + + 'b'_proxy'u'_proxy'b'REQUEST_METHOD'u'REQUEST_METHOD'b'Test if proxies should not be used for a particular host. + + Checks the proxy dict for the value of no_proxy, which should + be a list of comma separated DNS suffixes, or '*' for all hosts. + + 'u'Test if proxies should not be used for a particular host. + + Checks the proxy dict for the value of no_proxy, which should + be a list of comma separated DNS suffixes, or '*' for all hosts. + + 'b' + Return True iff this host shouldn't be accessed using a proxy + + This function uses the MacOSX framework SystemConfiguration + to fetch the proxy information. + + proxy_settings come from _scproxy._get_proxy_settings or get mocked ie: + { 'exclude_simple': bool, + 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16'] + } + 'u' + Return True iff this host shouldn't be accessed using a proxy + + This function uses the MacOSX framework SystemConfiguration + to fetch the proxy information. + + proxy_settings come from _scproxy._get_proxy_settings or get mocked ie: + { 'exclude_simple': bool, + 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16'] + } + 'b'exclude_simple'u'exclude_simple'b'(\d+(?:\.\d+)*)(/\d+)?'u'(\d+(?:\.\d+)*)(/\d+)?'b'Return a dictionary of scheme -> proxy server URL mappings. + + This function uses the MacOSX framework SystemConfiguration + to fetch the proxy information. + 'u'Return a dictionary of scheme -> proxy server URL mappings. + + This function uses the MacOSX framework SystemConfiguration + to fetch the proxy information. + 'b'Return True, if host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or from the MacOSX framework SystemConfiguration. + + 'u'Return True, if host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or from the MacOSX framework SystemConfiguration. + + 'b'Return a dictionary of scheme -> proxy server URL mappings. + + Win32 uses the registry to store proxies. + + 'u'Return a dictionary of scheme -> proxy server URL mappings. + + Win32 uses the registry to store proxies. + + 'b'Software\Microsoft\Windows\CurrentVersion\Internet Settings'u'Software\Microsoft\Windows\CurrentVersion\Internet Settings'b'ProxyEnable'u'ProxyEnable'b'ProxyServer'u'ProxyServer'b'(?:[^/:]+)://'u'(?:[^/:]+)://'b'%s://%s'u'%s://%s'b'http://%s'u'http://%s'b'https://%s'u'https://%s'b'ftp://%s'u'ftp://%s'b'Return a dictionary of scheme -> proxy server URL mappings. + + Returns settings gathered from the environment, if specified, + or the registry. + + 'u'Return a dictionary of scheme -> proxy server URL mappings. + + Returns settings gathered from the environment, if specified, + or the registry. + + 'b'ProxyOverride'u'ProxyOverride'b''u''b'\.'u'\.'b'Return True, if host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + + 'u'Return True, if host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + + 'RLIMIT_ASRLIMIT_CPURLIMIT_DATARLIMIT_FSIZERLIMIT_MEMLOCKRLIMIT_NOFILERLIMIT_NPROCRLIMIT_RSSRLIMIT_STACKRLIM_INFINITYRUSAGE_CHILDRENRUSAGE_SELFu'/Users/pwntester/.pyenv/versions/3.8.13/lib/python3.8/lib-dynload/resource.cpython-38-darwin.so'u'resource'getpagesizegetrusageu'struct_rusage: Result from getrusage. + +This object may be accessed either as a tuple of + (utime,stime,maxrss,ixrss,idrss,isrss,minflt,majflt, + nswap,inblock,oublock,msgsnd,msgrcv,nsignals,nvcsw,nivcsw) +or via the attributes ru_utime, ru_stime, ru_maxrss, and so on.'ru_idrssru_inblockru_isrssru_ixrssru_majfltru_maxrssru_minfltru_msgrcvru_msgsndru_nivcswru_nsignalsru_nswapru_nvcswru_oublockru_stimeru_utimeresource.struct_rusagestruct_rusagePicklable wrapper for a socket.new_sock_resource_sharerGet the socket. This should only be called once.get_connectionfromshareWrapper for fd which can be used at any time.new_fdGet the fd. This should only be called once._ResourceSharerManager for resources using background thread._old_locks_afterforkRegister resource, returning an identifier.Return connection from which to receive identified resource.Stop the background thread and clear registered resources.sub_warning_ResourceSharer thread did not stop when asked'_ResourceSharer thread did ''not stop when asked'Already have Listenerstarting listener and thread for sending handles_serve# We use a background thread for sharing fds on Unix, and for sharing sockets on# Windows.# A client which wants to pickle a resource registers it with the resource# sharer and gets an identifier in return. The unpickling process will connect# to the resource sharer, sends the identifier and its pid, and then receives# the resource.# If self._lock was locked at the time of the fork, it may be broken# -- see issue 6721. Replace it without letting it be gc'ed.b'stop'u'stop'b'DupSocket'u'DupSocket'b'Picklable wrapper for a socket.'u'Picklable wrapper for a socket.'b'Get the socket. This should only be called once.'u'Get the socket. This should only be called once.'b'Wrapper for fd which can be used at any time.'u'Wrapper for fd which can be used at any time.'b'Get the fd. This should only be called once.'u'Get the fd. This should only be called once.'b'Manager for resources using background thread.'u'Manager for resources using background thread.'b'Register resource, returning an identifier.'u'Register resource, returning an identifier.'b'Return connection from which to receive identified resource.'u'Return connection from which to receive identified resource.'b'Stop the background thread and clear registered resources.'u'Stop the background thread and clear registered resources.'b'_ResourceSharer thread did not stop when asked'u'_ResourceSharer thread did not stop when asked'b'Already have Listener'u'Already have Listener'b'starting listener and thread for sending handles'u'starting listener and thread for sending handles'b'pthread_sigmask'u'pthread_sigmask'u'multiprocessing.resource_sharer'u'resource_sharer'_HAVE_SIGMASK_IGNORED_SIGNALSnoop_CLEANUP_FUNCSsemaphoreshared_memoryResourceTrackerMake sure that resource tracker process is running. + + This can be run from any process. Usually a child process will use + the resource created by its parent._check_aliveresource_tracker: process died unexpectedly, relaunching. Some resources might leak.'resource_tracker: process died unexpectedly, ''relaunching. Some resources might leak.'from multiprocessing.resource_tracker import main;main(%d)Check that the pipe has not been closed by sending a probe.PROBE:0:noop +rtypeRegister name of resource with resource tracker.REGISTERUnregister name of resource with resource tracker.UNREGISTER{0}:{1}:{2} +name too longnbytes {0:n} but len(msg) {1:n}Run resource tracker.cleanup_funcCannot register for automatic cleanup: unknown resource type ' for automatic cleanup: ''unknown resource type 'PROBEunrecognized command %rrtype_cacheresource_tracker: There appear to be %d leaked %s objects to clean up at shutdown'resource_tracker: There appear to be %d ''leaked %s objects to clean up at shutdown'resource_tracker: %r: %s# Server process to keep track of unlinked resources (like shared memory# segments, semaphores etc.) and clean them.# On Unix we run a server process which keeps track of unlinked# resources. The server ignores SIGINT and SIGTERM and reads from a# pipe. Every other process of the program has a copy of the writable# end of the pipe, so we get EOF when all other processes have exited.# Then the server process unlinks any remaining resource names.# This is important because there may be system limits for such resources: for# instance, the system only supports a limited number of named semaphores, and# shared-memory segments live in the RAM. If a python process leaks such a# resource, this resource will not be removed till the next reboot. Without# this resource tracker process, "killall python" would probably leave unlinked# resources.# not running# closing the "alive" file descriptor stops main()# resource tracker was launched before, is it still running?# => still alive# => dead, launch it again# Clean-up to avoid dangling processes.# _pid can be None if this process is a child from another# python process, which has started the resource_tracker.# The resource_tracker has already been terminated.# process will out live us, so no need to wait on pid# bpo-33613: Register a signal mask that will block the signals.# This signal mask will be inherited by the child that is going# to be spawned and will protect the child from a race condition# that can make the child die before it registers signal handlers# for SIGINT and SIGTERM. The mask is unregistered after spawning# the child.# We cannot use send here as it calls ensure_running, creating# a cycle.# posix guarantees that writes to a pipe of less than PIPE_BUF# bytes are atomic, and that PIPE_BUF >= 512# protect the process from ^C and "killall python" etc# keep track of registered/unregistered resources# all processes have terminated; cleanup any remaining resources# For some reason the process which created and registered this# resource has failed to unregister it. Presumably it has# died. We therefore unlink it.b'unregister'u'unregister'b'noop'u'noop'b'semaphore'u'semaphore'b'shared_memory'u'shared_memory'b'Make sure that resource tracker process is running. + + This can be run from any process. Usually a child process will use + the resource created by its parent.'u'Make sure that resource tracker process is running. + + This can be run from any process. Usually a child process will use + the resource created by its parent.'b'resource_tracker: process died unexpectedly, relaunching. Some resources might leak.'u'resource_tracker: process died unexpectedly, relaunching. Some resources might leak.'b'from multiprocessing.resource_tracker import main;main(%d)'u'from multiprocessing.resource_tracker import main;main(%d)'b'Check that the pipe has not been closed by sending a probe.'u'Check that the pipe has not been closed by sending a probe.'b'PROBE:0:noop +'b'Register name of resource with resource tracker.'u'Register name of resource with resource tracker.'b'REGISTER'u'REGISTER'b'Unregister name of resource with resource tracker.'u'Unregister name of resource with resource tracker.'b'UNREGISTER'u'UNREGISTER'b'{0}:{1}:{2} +'u'{0}:{1}:{2} +'b'name too long'u'name too long'b'nbytes {0:n} but len(msg) {1:n}'u'nbytes {0:n} but len(msg) {1:n}'b'Run resource tracker.'u'Run resource tracker.'b'Cannot register 'u'Cannot register 'b' for automatic cleanup: unknown resource type 'u' for automatic cleanup: unknown resource type 'b'PROBE'u'PROBE'b'unrecognized command %r'u'unrecognized command %r'b'resource_tracker: There appear to be %d leaked %s objects to clean up at shutdown'u'resource_tracker: There appear to be %d leaked %s objects to clean up at shutdown'b'resource_tracker: %r: %s'u'resource_tracker: %r: %s'u'multiprocessing.resource_tracker'u'resource_tracker'Response classes used by urllib. + +The base class, addbase, defines a minimal file-like interface, +including read() and readline(). The typical response object is an +addinfourl instance, which defines an info() method that returns +headers and a geturl() method that returns the url. +addbaseaddinfo_TemporaryFileWrapperBase class for addinfo and addclosehook. Is a good idea for garbage collection.<%s at %r whose fp = %r>Class to add a close hook to an open file.closehookhookargsclass to add an info() method to an open file.class to add info() and geturl() methods to an open file.# XXX Add a method to expose the timeout on the underlying socket?# Keep reference around as this was part of the original API.b'Response classes used by urllib. + +The base class, addbase, defines a minimal file-like interface, +including read() and readline(). The typical response object is an +addinfourl instance, which defines an info() method that returns +headers and a geturl() method that returns the url. +'u'Response classes used by urllib. + +The base class, addbase, defines a minimal file-like interface, +including read() and readline(). The typical response object is an +addinfourl instance, which defines an info() method that returns +headers and a geturl() method that returns the url. +'b'addbase'u'addbase'b'addclosehook'u'addclosehook'b'addinfo'u'addinfo'b'addinfourl'u'addinfourl'b'Base class for addinfo and addclosehook. Is a good idea for garbage collection.'u'Base class for addinfo and addclosehook. Is a good idea for garbage collection.'b''u''b'<%s at %r whose fp = %r>'u'<%s at %r whose fp = %r>'b'Class to add a close hook to an open file.'u'Class to add a close hook to an open file.'b'class to add an info() method to an open file.'u'class to add an info() method to an open file.'b'class to add info() and geturl() methods to an open file.'u'class to add info() and geturl() methods to an open file.'u'urllib.response'Test result object +Stdout: +%sSTDOUT_LINE +Stderr: +%sSTDERR_LINEHolder for test result information. + + Test results are automatically managed by the TestCase and TestSuite + classes, and do not need to be explicitly manipulated by writers of tests. + + Each instance holds the total number of tests run, and collections of + failures and errors that occurred among those test runs. The collections + contain tuples of (testcase, exceptioninfo), where exceptioninfo is the + formatted traceback of the error that occurred. + _previousTestClass_testRunEntered_moduleSetUpFailedexpectedFailuresunexpectedSuccessesshouldStop_stdout_buffer_stderr_buffer_original_stderr_mirrorOutputprintErrorsCalled by TestRunner after test runCalled when the given test is about to be run_setupStdoutCalled once before any tests are executed. + + See startTest for a method called before each test. + Called when the given test has been run_restoreStdoutCalled once after all tests are executed. + + See stopTest for a method called after each test. + Called when an error has occurred. 'err' is a tuple of values as + returned by sys.exc_info(). + _exc_info_to_stringCalled when an error has occurred. 'err' is a tuple of values as + returned by sys.exc_info().subtestCalled at the end of a subtest. + 'err' is None if the subtest ended successfully, otherwise it's a + tuple of values as returned by sys.exc_info(). + Called when a test has completed successfullyCalled when a test is skipped.Called when an expected failure/error occurred.Called when a test was expected to fail, but succeed.Tells whether or not this result was a success.Indicates that the tests should be aborted.Converts a sys.exc_info()-style tuple of values into a string._is_relevant_tb_level_count_relevant_tb_levelsTracebackExceptioncapture_localstb_emsgLines<%s run=%i errors=%i failures=%i># By default, we don't do anything with successful subtests, but# more sophisticated test results might want to record them.# The hasattr check is for test_result's OldResult test. That# way this method works on objects that lack the attribute.# (where would such result intances come from? old stored pickles?)# Skip test runner traceback levels# Skip assert*() traceback levelsb'Test result object'u'Test result object'b' +Stdout: +%s'u' +Stdout: +%s'b' +Stderr: +%s'u' +Stderr: +%s'b'Holder for test result information. + + Test results are automatically managed by the TestCase and TestSuite + classes, and do not need to be explicitly manipulated by writers of tests. + + Each instance holds the total number of tests run, and collections of + failures and errors that occurred among those test runs. The collections + contain tuples of (testcase, exceptioninfo), where exceptioninfo is the + formatted traceback of the error that occurred. + 'u'Holder for test result information. + + Test results are automatically managed by the TestCase and TestSuite + classes, and do not need to be explicitly manipulated by writers of tests. + + Each instance holds the total number of tests run, and collections of + failures and errors that occurred among those test runs. The collections + contain tuples of (testcase, exceptioninfo), where exceptioninfo is the + formatted traceback of the error that occurred. + 'b'Called by TestRunner after test run'u'Called by TestRunner after test run'b'Called when the given test is about to be run'u'Called when the given test is about to be run'b'Called once before any tests are executed. + + See startTest for a method called before each test. + 'u'Called once before any tests are executed. + + See startTest for a method called before each test. + 'b'Called when the given test has been run'u'Called when the given test has been run'b'Called once after all tests are executed. + + See stopTest for a method called after each test. + 'u'Called once after all tests are executed. + + See stopTest for a method called after each test. + 'b'Called when an error has occurred. 'err' is a tuple of values as + returned by sys.exc_info(). + 'u'Called when an error has occurred. 'err' is a tuple of values as + returned by sys.exc_info(). + 'b'Called when an error has occurred. 'err' is a tuple of values as + returned by sys.exc_info().'u'Called when an error has occurred. 'err' is a tuple of values as + returned by sys.exc_info().'b'Called at the end of a subtest. + 'err' is None if the subtest ended successfully, otherwise it's a + tuple of values as returned by sys.exc_info(). + 'u'Called at the end of a subtest. + 'err' is None if the subtest ended successfully, otherwise it's a + tuple of values as returned by sys.exc_info(). + 'b'Called when a test has completed successfully'u'Called when a test has completed successfully'b'Called when a test is skipped.'u'Called when a test is skipped.'b'Called when an expected failure/error occurred.'u'Called when an expected failure/error occurred.'b'Called when a test was expected to fail, but succeed.'u'Called when a test was expected to fail, but succeed.'b'Tells whether or not this result was a success.'u'Tells whether or not this result was a success.'b'unexpectedSuccesses'u'unexpectedSuccesses'b'Indicates that the tests should be aborted.'u'Indicates that the tests should be aborted.'b'Converts a sys.exc_info()-style tuple of values into a string.'u'Converts a sys.exc_info()-style tuple of values into a string.'b'__unittest'u'__unittest'b'<%s run=%i errors=%i failures=%i>'u'<%s run=%i errors=%i failures=%i>'u'unittest.result'Running tests_WritelnDecoratorUsed to decorate file-like objects with a handy 'writeln' methodA test result class that can print formatted text results to a stream. + + Used by TextTestRunner. + separator1separator2showAlldotsgetDescriptiondoc_first_line ... FAILskipped {0!r}expected failureunexpected successprintErrorListflavourA test runner class that displays results in textual form. + + It prints out the names of tests as they are run, errors as they + occur, and a summary of the results at the end of the test run. + resultclassConstruct a TextTestRunner. + + Subclasses should accept **kwargs to ensure compatibility as the + interface changes. + _makeResultRun the given test case or test suite.Please use assert\w+ instead.startTimestopTimetimeTakenRan %d test%s in %.3fsexpectedFailsFAILEDerroredfailures=%derrors=%dskipped=%dexpected failures=%dunexpected successes=%d# text-mode streams translate to \r\n if needed# if self.warnings is set, use it to filter all the warnings# if the filter is 'default' or 'always', special-case the# warnings from the deprecated unittest methods to show them# no more than once per module, because they can be fairly# noisy. The -Wd and -Wa flags can be used to bypass this# only when self.warnings is None.b'Running tests'u'Running tests'b'Used to decorate file-like objects with a handy 'writeln' method'u'Used to decorate file-like objects with a handy 'writeln' method'b'A test result class that can print formatted text results to a stream. + + Used by TextTestRunner. + 'u'A test result class that can print formatted text results to a stream. + + Used by TextTestRunner. + 'b' ... 'u' ... 'b'ok'u'ok'b'FAIL'u'FAIL'b'skipped {0!r}'u'skipped {0!r}'b'expected failure'u'expected failure'b'unexpected success'u'unexpected success'b'A test runner class that displays results in textual form. + + It prints out the names of tests as they are run, errors as they + occur, and a summary of the results at the end of the test run. + 'u'A test runner class that displays results in textual form. + + It prints out the names of tests as they are run, errors as they + occur, and a summary of the results at the end of the test run. + 'b'Construct a TextTestRunner. + + Subclasses should accept **kwargs to ensure compatibility as the + interface changes. + 'u'Construct a TextTestRunner. + + Subclasses should accept **kwargs to ensure compatibility as the + interface changes. + 'b'Run the given test case or test suite.'u'Run the given test case or test suite.'b'module'b'Please use assert\w+ instead.'u'Please use assert\w+ instead.'b'separator2'u'separator2'b'Ran %d test%s in %.3fs'u'Ran %d test%s in %.3fs'b'FAILED'u'FAILED'b'failures=%d'u'failures=%d'b'errors=%d'u'errors=%d'b'skipped=%d'u'skipped=%d'b'expected failures=%d'u'expected failures=%d'b'unexpected successes=%d'u'unexpected successes=%d'u'unittest.runner'u'runner'Execute the coroutine and return the result. + + This function runs the passed coroutine, taking care of + managing the asyncio event loop and finalizing asynchronous + generators. + + This function cannot be called when another asyncio event loop is + running in the same thread. + + If debug is True, the event loop will be run in debug mode. + + This function always creates a new event loop and closes it at the end. + It should be used as a main entry point for asyncio programs, and should + ideally only be called once. + + Example: + + async def main(): + await asyncio.sleep(1) + print('hello') + + asyncio.run(main()) + asyncio.run() cannot be called from a running event loopa coroutine was expected, got {!r}_cancel_all_tasksunhandled exception during asyncio.run() shutdownb'Execute the coroutine and return the result. + + This function runs the passed coroutine, taking care of + managing the asyncio event loop and finalizing asynchronous + generators. + + This function cannot be called when another asyncio event loop is + running in the same thread. + + If debug is True, the event loop will be run in debug mode. + + This function always creates a new event loop and closes it at the end. + It should be used as a main entry point for asyncio programs, and should + ideally only be called once. + + Example: + + async def main(): + await asyncio.sleep(1) + print('hello') + + asyncio.run(main()) + 'u'Execute the coroutine and return the result. + + This function runs the passed coroutine, taking care of + managing the asyncio event loop and finalizing asynchronous + generators. + + This function cannot be called when another asyncio event loop is + running in the same thread. + + If debug is True, the event loop will be run in debug mode. + + This function always creates a new event loop and closes it at the end. + It should be used as a main entry point for asyncio programs, and should + ideally only be called once. + + Example: + + async def main(): + await asyncio.sleep(1) + print('hello') + + asyncio.run(main()) + 'b'asyncio.run() cannot be called from a running event loop'u'asyncio.run() cannot be called from a running event loop'b'a coroutine was expected, got {!r}'u'a coroutine was expected, got {!r}'b'unhandled exception during asyncio.run() shutdown'u'unhandled exception during asyncio.run() shutdown'u'asyncio.runners'u'runners'runpy.py - locating and running Python code using the module namespace + +Provides support for locating and running Python scripts using the Python +module namespace instead of the native filesystem. + +This allows Python code to play nicely with non-filesystem based PEP 302 +importers when locating support scripts as well as when importing modules. +run_modulerun_path_TempModuleTemporarily replace a module in sys.modules with an empty namespace_saved_module_ModifiedArgv0_saved_valueAlready preserving saved value_run_coderun_globalsinit_globalsscript_nameHelper to run code in nominated namespace_run_module_codeHelper to run code in new namespace with sys modifiedtemp_modulemod_globalsRelative module names not supportedexisting{mod_name!r} found in sys.modules after import of package {pkg_name!r}, but prior to execution of {mod_name!r}; this may result in unpredictable behaviour"{mod_name!r} found in sys.modules after import of ""package {pkg_name!r}, but prior to execution of ""{mod_name!r}; this may result in unpredictable ""behaviour"Error while finding module specification for {!r} ({}: {})No module named %s.__main__Cannot use package as __main__ modulepkg_main_name%s; %r is a package and cannot be directly executed%r is a namespace package and cannot be executedNo code object available for %s_ErrorError that _run_module_as_main() should report without a traceback_run_module_as_mainalter_argvRuns the designated module in the __main__ namespace + + Note that the executed module will have full access to the + __main__ namespace. If this is not desirable, the run_module() + function should be used to run the module code in a fresh namespace. + + At the very least, these variables in __main__ will be overwritten: + __name__ + __file__ + __cached__ + __loader__ + __package__ + _get_main_module_detailsmain_globalsrun_namealter_sysExecute a module's code without importing it + + Returns the resulting top level namespace dictionary + main_namesaved_maincan't find %r module in %r_get_code_from_filedecoded_pathpath_nameExecute code located at the specified filesystem location + + Returns the resulting top level namespace dictionary + + The file path may refer directly to a Python script (i.e. + one that could be directly executed with execfile) or else + it may refer to a zipfile or directory containing a top + level __main__.py script. + is_NullImporterNullImporterNo module specified for execution# Written by Nick Coghlan # to implement PEP 338 (Executing Modules as Scripts)# importlib first so we can test #15386 via -m# TODO: Replace these helpers with importlib._bootstrap_external functions.# Copy the globals of the temporary module, as they# may be cleared when the temporary module goes away# Helper to get the full name, spec and code for a module# Try importing the parent to avoid catching initialization errors# If the parent or higher ancestor package is missing, let the# error be raised by find_spec() below and then be caught. But do# not allow other errors to be caught.# Warn if the module has already been imported under its normal name# No module loaded; being a package is irrelevant# XXX ncoghlan: Should this be documented and made public?# (Current thoughts: don't repeat the mistake that lead to its# creation when run_module() no longer met the needs of# mainmodule.c, but couldn't be changed because it was public)# i.e. -m switch# i.e. directory or zipfile execution# Leave the sys module alone# Helper that gives a nicer error message when attempting to# execute a zipfile or directory by invoking __main__.py# Also moves the standard __main__ out of the way so that the# preexisting __loader__ entry doesn't cause issues# Check for a compiled file first# That didn't work, so try it as normal source code# Trying to avoid importing imp so as to not consume the deprecation warning.# Not a valid sys.path entry, so run the code directly# execfile() doesn't help as we want to allow compiled files# Finder is defined for path, so add it to# the start of sys.path# Here's where things are a little different from the run_module# case. There, we only had to replace the module in sys while the# code was running and doing so was somewhat optional. Here, we# have no choice and we have to remove it even while we read the# code. If we don't do this, a __loader__ attribute in the# existing __main__ module may prevent location of the new module.# Run the module specified as the next command line argument# Make the requested module sys.argv[0]b'runpy.py - locating and running Python code using the module namespace + +Provides support for locating and running Python scripts using the Python +module namespace instead of the native filesystem. + +This allows Python code to play nicely with non-filesystem based PEP 302 +importers when locating support scripts as well as when importing modules. +'u'runpy.py - locating and running Python code using the module namespace + +Provides support for locating and running Python scripts using the Python +module namespace instead of the native filesystem. + +This allows Python code to play nicely with non-filesystem based PEP 302 +importers when locating support scripts as well as when importing modules. +'b'run_module'u'run_module'b'run_path'u'run_path'b'Temporarily replace a module in sys.modules with an empty namespace'u'Temporarily replace a module in sys.modules with an empty namespace'b'Already preserving saved value'u'Already preserving saved value'b'Helper to run code in nominated namespace'u'Helper to run code in nominated namespace'b'Helper to run code in new namespace with sys modified'u'Helper to run code in new namespace with sys modified'b'Relative module names not supported'u'Relative module names not supported'b'{mod_name!r} found in sys.modules after import of package {pkg_name!r}, but prior to execution of {mod_name!r}; this may result in unpredictable behaviour'u'{mod_name!r} found in sys.modules after import of package {pkg_name!r}, but prior to execution of {mod_name!r}; this may result in unpredictable behaviour'b'Error while finding module specification for {!r} ({}: {})'u'Error while finding module specification for {!r} ({}: {})'b'No module named %s'u'No module named %s'b'.__main__'u'.__main__'b'Cannot use package as __main__ module'u'Cannot use package as __main__ module'b'%s; %r is a package and cannot 'u'%s; %r is a package and cannot 'b'be directly executed'u'be directly executed'b'%r is a namespace package and cannot be executed'u'%r is a namespace package and cannot be executed'b'No code object available for %s'u'No code object available for %s'b'Error that _run_module_as_main() should report without a traceback'u'Error that _run_module_as_main() should report without a traceback'b'Runs the designated module in the __main__ namespace + + Note that the executed module will have full access to the + __main__ namespace. If this is not desirable, the run_module() + function should be used to run the module code in a fresh namespace. + + At the very least, these variables in __main__ will be overwritten: + __name__ + __file__ + __cached__ + __loader__ + __package__ + 'u'Runs the designated module in the __main__ namespace + + Note that the executed module will have full access to the + __main__ namespace. If this is not desirable, the run_module() + function should be used to run the module code in a fresh namespace. + + At the very least, these variables in __main__ will be overwritten: + __name__ + __file__ + __cached__ + __loader__ + __package__ + 'b'Execute a module's code without importing it + + Returns the resulting top level namespace dictionary + 'u'Execute a module's code without importing it + + Returns the resulting top level namespace dictionary + 'b'can't find %r module in %r'u'can't find %r module in %r'b'Execute code located at the specified filesystem location + + Returns the resulting top level namespace dictionary + + The file path may refer directly to a Python script (i.e. + one that could be directly executed with execfile) or else + it may refer to a zipfile or directory containing a top + level __main__.py script. + 'u'Execute code located at the specified filesystem location + + Returns the resulting top level namespace dictionary + + The file path may refer directly to a Python script (i.e. + one that could be directly executed with execfile) or else + it may refer to a zipfile or directory containing a top + level __main__.py script. + 'b''u''b'NullImporter'u'NullImporter'b'No module specified for execution'u'No module specified for execution'u'runpy'KQ_EV_ADDKQ_EV_CLEARKQ_EV_DELETEKQ_EV_DISABLEKQ_EV_ENABLEKQ_EV_EOFKQ_EV_ERRORKQ_EV_FLAG1KQ_EV_ONESHOTKQ_EV_SYSFLAGS-3KQ_FILTER_AIO-5KQ_FILTER_PROCKQ_FILTER_READ-6KQ_FILTER_SIGNAL-7KQ_FILTER_TIMER-4KQ_FILTER_VNODEKQ_FILTER_WRITEKQ_NOTE_ATTRIBKQ_NOTE_CHILDKQ_NOTE_DELETEKQ_NOTE_EXECKQ_NOTE_EXITKQ_NOTE_EXTENDKQ_NOTE_FORKKQ_NOTE_LINKKQ_NOTE_LOWAT-1048576KQ_NOTE_PCTRLMASKKQ_NOTE_PDATAMASKKQ_NOTE_RENAMEKQ_NOTE_REVOKEKQ_NOTE_TRACKKQ_NOTE_TRACKERRKQ_NOTE_WRITEPIPE_BUFPOLLERRPOLLHUPPOLLINPOLLNVALPOLLOUTPOLLPRIPOLLRDBANDPOLLRDNORMPOLLWRBANDPOLLWRNORMu'This module supports asynchronous I/O on multiple file descriptors. + +*** IMPORTANT NOTICE *** +On Windows, only sockets are supported; on Unix, all file descriptors.'u'/Users/pwntester/.pyenv/versions/3.8.13/lib/python3.8/lib-dynload/select.cpython-38-darwin.so'u'kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0) + +This object is the equivalent of the struct kevent for the C API. + +See the kqueue manpage for more detailed information about the meaning +of the arguments. + +One minor note: while you might hope that udata could store a +reference to a python object, it cannot, because it is impossible to +keep a proper reference count of the object once it's passed into the +kernel. Therefore, I have restricted it to only storing an integer. I +recommend ignoring it and simply using the 'ident' field to key off +of. You could also set up a dictionary on the python side to store a +udata->object mapping.'fflagsudataselect.keventkeventu'Kqueue syscall wrapper. + +For example, to start watching a socket for input: +>>> kq = kqueue() +>>> sock = socket() +>>> sock.connect((host, port)) +>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0) + +To wait one second for it to become writeable: +>>> kq.control(None, 1, 1000) + +To stop listening: +>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)'u'True if the kqueue handler is closed'u'kqueue.closed'controlselect.kqueuekqueueEvent loop using a selector and related classes. + +A selector is a "notify-when-ready" multiplexer. For a subclass which +also includes support for signal handling, see the unix_events sub-module. +BaseSelectorEventLoop_test_selector_eventget_key_check_ssl_socketSocket cannot be of type SSLSocketSelector event loop. + + See events.EventLoop for API specification. + Using selector: %s_transports_SelectorSocketTransport_SelectorDatagramTransport_remove_reader_add_reader_read_from_self_process_self_data_accept_connection_accept_connection2socket.accept() out of system resourceError on transport creation for incoming connection_ensure_fd_no_transportInvalid file object: File descriptor is used by transport ' is used by transport 'modify_add_writerEVENT_WRITE_remove_writerRemove a writer callback.Add a reader callback.Remove a reader callback.Add a writer callback..Receive data from the socket. + + The return value is a bytes object representing the data received. + The maximum amount of data to be received at once is specified by + nbytes. + _sock_recv_sock_read_doneReceive data from the socket. + + The received data is written into *buf* (a writable buffer). + The return value is the number of bytes written. + _sock_recv_intoSend data to the socket. + + The socket must be connected to a remote socket. This method continues + to send data from data until either all data has been sent or an + error occurs. None is returned on success. On error, an exception is + raised, and there is no way to determine how much data, if any, was + successfully processed by the receiving end of the connection. + _sock_write_done_sock_sendallConnect to a remote socket at address. + + This method is a coroutine. + resolved_sock_connect_sock_connect_cbConnect call failed Accept a connection. + + The socket must be bound to an address and listening for connections. + The return value is a pair (conn, address) where conn is a new socket + object usable to send and receive data on the connection, and address + is the address bound to the socket on the other end of the connection. + _sock_acceptregistered_sock_fd_SelectorTransport_buffer_factory_protocol_connectedpollingread=pollingread=idlewrite=<, bufsize=Fatal error on transport_read_ready_cb_read_ready_read_ready__get_buffer_read_ready__data_receivedFatal error: protocol.get_buffer() call failed.Fatal read error on socket transport_read_ready__on_eofFatal error: protocol.data_received() call failed.'data argument must be a bytes-like object, ''not 'Cannot call write() after write_eof()Fatal write error on socket transport_write_readyData should not be emptyFatal read error on datagram transport_sendto_ready# Test if the selector is monitoring 'event' events# for the file descriptor 'fd'.# This method is only called once for each event loop tick where the# listening socket has triggered an EVENT_READ. There may be multiple# connections waiting for an .accept() so it is called in a loop.# See https://bugs.python.org/issue27906 for more details.# Early exit because the socket accept buffer is empty.# There's nowhere to send the error, so just log it.# Some platforms (e.g. Linux keep reporting the FD as# ready, so we remove the read handler temporarily.# We'll try again in a while.# The event loop will catch, log and ignore it.# It's now up to the protocol to handle the connection.# This code matches selectors._fileobj_to_fd function.# Remove both writer and connector.# _sock_recv() can add itself as an I/O callback if the operation can't# be done immediately. Don't use it directly, call sock_recv().# try again next time# _sock_recv_into() can add itself as an I/O callback if the operation# can't be done immediately. Don't use it directly, call# sock_recv_into().# all data sent# use a trick with a list in closure to store a mutable state# Future cancellation can be scheduled on previous loop iteration# Issue #23618: When the C function connect() fails with EINTR, the# connection runs in background. We have to wait until the socket# becomes writable to be notified when the connection succeed or# fails.# Jump to any except clause below.# socket is still registered, the callback will be retried later# Buffer size passed to recv().# Constructs initial value for self._buffer.# Attribute used in the destructor: it must be set even if the constructor# is not called (see _SelectorSslTransport which may start by raising an# exception)# Set when call to connection_lost scheduled.# test if the transport was closed# Should be called from exception handler only.# Disable the Nagle algorithm -- small writes will be# sent without waiting for the TCP ACK. This generally# decreases the latency (in some cases significantly.)# only start reading when connection_made() has been called# We're keeping the connection open so the# protocol can write more, but we still can't# receive more, so remove the reader callback.# Optimization: try to send now.# Not all was written; register write handler.# Add it to the buffer.# May append to buffer.# Attempt to send it right away first.# Try again later.b'Event loop using a selector and related classes. + +A selector is a "notify-when-ready" multiplexer. For a subclass which +also includes support for signal handling, see the unix_events sub-module. +'u'Event loop using a selector and related classes. + +A selector is a "notify-when-ready" multiplexer. For a subclass which +also includes support for signal handling, see the unix_events sub-module. +'b'BaseSelectorEventLoop'u'BaseSelectorEventLoop'b'Socket cannot be of type SSLSocket'u'Socket cannot be of type SSLSocket'b'Selector event loop. + + See events.EventLoop for API specification. + 'u'Selector event loop. + + See events.EventLoop for API specification. + 'b'Using selector: %s'u'Using selector: %s'b'socket.accept() out of system resource'u'socket.accept() out of system resource'b'Error on transport creation for incoming connection'u'Error on transport creation for incoming connection'b'Invalid file object: 'u'Invalid file object: 'b'File descriptor 'u'File descriptor 'b' is used by transport 'u' is used by transport 'b'Remove a writer callback.'u'Remove a writer callback.'b'Add a reader callback.'u'Add a reader callback.'b'Remove a reader callback.'u'Remove a reader callback.'b'Add a writer callback..'u'Add a writer callback..'b'Receive data from the socket. + + The return value is a bytes object representing the data received. + The maximum amount of data to be received at once is specified by + nbytes. + 'u'Receive data from the socket. + + The return value is a bytes object representing the data received. + The maximum amount of data to be received at once is specified by + nbytes. + 'b'Receive data from the socket. + + The received data is written into *buf* (a writable buffer). + The return value is the number of bytes written. + 'u'Receive data from the socket. + + The received data is written into *buf* (a writable buffer). + The return value is the number of bytes written. + 'b'Send data to the socket. + + The socket must be connected to a remote socket. This method continues + to send data from data until either all data has been sent or an + error occurs. None is returned on success. On error, an exception is + raised, and there is no way to determine how much data, if any, was + successfully processed by the receiving end of the connection. + 'u'Send data to the socket. + + The socket must be connected to a remote socket. This method continues + to send data from data until either all data has been sent or an + error occurs. None is returned on success. On error, an exception is + raised, and there is no way to determine how much data, if any, was + successfully processed by the receiving end of the connection. + 'b'Connect to a remote socket at address. + + This method is a coroutine. + 'u'Connect to a remote socket at address. + + This method is a coroutine. + 'b'Connect call failed 'u'Connect call failed 'b'Accept a connection. + + The socket must be bound to an address and listening for connections. + The return value is a pair (conn, address) where conn is a new socket + object usable to send and receive data on the connection, and address + is the address bound to the socket on the other end of the connection. + 'u'Accept a connection. + + The socket must be bound to an address and listening for connections. + The return value is a pair (conn, address) where conn is a new socket + object usable to send and receive data on the connection, and address + is the address bound to the socket on the other end of the connection. + 'b'read=polling'u'read=polling'b'read=idle'u'read=idle'b'polling'u'polling'b'write=<'u'write=<'b', bufsize='u', bufsize='b'Fatal error on transport'u'Fatal error on transport'b'Fatal error: protocol.get_buffer() call failed.'u'Fatal error: protocol.get_buffer() call failed.'b'Fatal read error on socket transport'u'Fatal read error on socket transport'b'Fatal error: protocol.data_received() call failed.'u'Fatal error: protocol.data_received() call failed.'b'Cannot call write() after write_eof()'u'Cannot call write() after write_eof()'b'Fatal write error on socket transport'u'Fatal write error on socket transport'b'Data should not be empty'u'Data should not be empty'b'Fatal read error on datagram transport'u'Fatal read error on datagram transport'u'asyncio.selector_events'u'selector_events'Selectors module. + +This module allows high-level and efficient I/O multiplexing, built upon the +`select` module primitives. +_fileobj_to_fdReturn a file descriptor from a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + corresponding file descriptor + + Raises: + ValueError if the object is invalid + Invalid file object: {!r}"Invalid file object: ""{!r}"Invalid file descriptor: {}SelectorKeySelectorKey(fileobj, fd, events, data) + + Object used to associate a file object to its backing + file descriptor, selected event mask, and attached data. +File object registered.Underlying file descriptor.Events that must be waited for on this file object.Optional opaque data associated to this file object. + For example, this could be used to store a per-client session ID._SelectorMappingMapping of file objects to selector keys._fd_to_key_fileobj_lookup{!r} is not registeredBaseSelectorSelector abstract base class. + + A selector supports registering file objects to be monitored for specific + I/O events. + + A file object is a file descriptor or any object with a `fileno()` method. + An arbitrary object can be attached to the file object, which can be used + for example to store context information, a callback, etc. + + A selector can use various implementations (select(), poll(), epoll()...) + depending on the platform. The default `Selector` class uses the most + efficient implementation on the current platform. + Register a file object. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + ValueError if events is invalid + KeyError if fileobj is already registered + OSError if fileobj is closed or otherwise is unacceptable to + the underlying system call (if a system call is made) + + Note: + OSError may or may not be raised + Unregister a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + SelectorKey instance + + Raises: + KeyError if fileobj is not registered + + Note: + If fileobj is registered but has since been closed this does + *not* raise OSError (even if the wrapped syscall does) + Change a registered file object monitored events or attached data. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + Anything that unregister() or register() raises + Perform the actual selection, until some monitored file objects are + ready or a timeout expires. + + Parameters: + timeout -- if timeout > 0, this specifies the maximum wait time, in + seconds + if timeout <= 0, the select() call won't block, and will + report the currently ready file objects + if timeout is None, select() will block until a monitored + file object becomes ready + + Returns: + list of (key, events) for ready file objects + `events` is a bitwise mask of EVENT_READ|EVENT_WRITE + Close the selector. + + This must be called to make sure that any underlying resource is freed. + Return the key associated to a registered file object. + + Returns: + SelectorKey for this file object + get_mapSelector is closedReturn a mapping of file objects to selector keys._BaseSelectorImplBase selector implementation.Return a file descriptor from a file object. + + This wraps _fileobj_to_fd() to do an exhaustive search in case + the object is invalid but we still have it in our map. This + is used by unregister() so we can unregister an object that + was previously registered even if it is closed. It is also + used by _SelectorMapping. + Invalid events: {!r}{!r} (FD {}) is already registered_key_from_fdReturn the key associated to a given file descriptor. + + Parameters: + fd -- file descriptor + + Returns: + corresponding key, or None if not found + Select-based selector._readers_writers_select_PollLikeSelectorBase class shared between poll, epoll and devpoll selectors._selector_cls_EVENT_READ_EVENT_WRITEpoller_events is not registeredselector_eventsfd_event_listPoll-based selector.epollEpollSelectorEpoll-based selector.EPOLLINEPOLLOUT1e-3max_evdevpollDevpollSelectorSolaris /dev/poll selector.KqueueSelectorKqueue-based selector.kevkev_list# generic events, that must be mapped to implementation-specific ones# this maps file descriptors to keys# read-only mapping returned by get_map()# Do an exhaustive search.# Raise ValueError after all.# Use a shortcut to update the data.# This can happen if the FD was closed since it# was registered.# This is shared between poll() and epoll().# epoll() has a different signature and handling of timeout parameter.# poll() has a resolution of 1 millisecond, round away from# zero to wait *at least* timeout seconds.# epoll_wait() has a resolution of 1 millisecond, round away# from zero to wait *at least* timeout seconds.# epoll_wait() expects `maxevents` to be greater than zero;# we want to make sure that `select()` can be called when no# FD is registered.# See comment above.# Choose the best implementation, roughly:# epoll|kqueue|devpoll > poll > select.# select() also can't accept a FD > FD_SETSIZE (usually around 1024)b'Selectors module. + +This module allows high-level and efficient I/O multiplexing, built upon the +`select` module primitives. +'u'Selectors module. + +This module allows high-level and efficient I/O multiplexing, built upon the +`select` module primitives. +'b'Return a file descriptor from a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + corresponding file descriptor + + Raises: + ValueError if the object is invalid + 'u'Return a file descriptor from a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + corresponding file descriptor + + Raises: + ValueError if the object is invalid + 'b'Invalid file object: {!r}'u'Invalid file object: {!r}'b'Invalid file descriptor: {}'u'Invalid file descriptor: {}'b'SelectorKey'u'SelectorKey'b'fileobj'u'fileobj'b'fd'u'fd'b'events'b'SelectorKey(fileobj, fd, events, data) + + Object used to associate a file object to its backing + file descriptor, selected event mask, and attached data. +'u'SelectorKey(fileobj, fd, events, data) + + Object used to associate a file object to its backing + file descriptor, selected event mask, and attached data. +'b'File object registered.'u'File object registered.'b'Underlying file descriptor.'u'Underlying file descriptor.'b'Events that must be waited for on this file object.'u'Events that must be waited for on this file object.'b'Optional opaque data associated to this file object. + For example, this could be used to store a per-client session ID.'u'Optional opaque data associated to this file object. + For example, this could be used to store a per-client session ID.'b'Mapping of file objects to selector keys.'u'Mapping of file objects to selector keys.'b'{!r} is not registered'u'{!r} is not registered'b'Selector abstract base class. + + A selector supports registering file objects to be monitored for specific + I/O events. + + A file object is a file descriptor or any object with a `fileno()` method. + An arbitrary object can be attached to the file object, which can be used + for example to store context information, a callback, etc. + + A selector can use various implementations (select(), poll(), epoll()...) + depending on the platform. The default `Selector` class uses the most + efficient implementation on the current platform. + 'u'Selector abstract base class. + + A selector supports registering file objects to be monitored for specific + I/O events. + + A file object is a file descriptor or any object with a `fileno()` method. + An arbitrary object can be attached to the file object, which can be used + for example to store context information, a callback, etc. + + A selector can use various implementations (select(), poll(), epoll()...) + depending on the platform. The default `Selector` class uses the most + efficient implementation on the current platform. + 'b'Register a file object. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + ValueError if events is invalid + KeyError if fileobj is already registered + OSError if fileobj is closed or otherwise is unacceptable to + the underlying system call (if a system call is made) + + Note: + OSError may or may not be raised + 'u'Register a file object. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + ValueError if events is invalid + KeyError if fileobj is already registered + OSError if fileobj is closed or otherwise is unacceptable to + the underlying system call (if a system call is made) + + Note: + OSError may or may not be raised + 'b'Unregister a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + SelectorKey instance + + Raises: + KeyError if fileobj is not registered + + Note: + If fileobj is registered but has since been closed this does + *not* raise OSError (even if the wrapped syscall does) + 'u'Unregister a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + SelectorKey instance + + Raises: + KeyError if fileobj is not registered + + Note: + If fileobj is registered but has since been closed this does + *not* raise OSError (even if the wrapped syscall does) + 'b'Change a registered file object monitored events or attached data. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + Anything that unregister() or register() raises + 'u'Change a registered file object monitored events or attached data. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + Anything that unregister() or register() raises + 'b'Perform the actual selection, until some monitored file objects are + ready or a timeout expires. + + Parameters: + timeout -- if timeout > 0, this specifies the maximum wait time, in + seconds + if timeout <= 0, the select() call won't block, and will + report the currently ready file objects + if timeout is None, select() will block until a monitored + file object becomes ready + + Returns: + list of (key, events) for ready file objects + `events` is a bitwise mask of EVENT_READ|EVENT_WRITE + 'u'Perform the actual selection, until some monitored file objects are + ready or a timeout expires. + + Parameters: + timeout -- if timeout > 0, this specifies the maximum wait time, in + seconds + if timeout <= 0, the select() call won't block, and will + report the currently ready file objects + if timeout is None, select() will block until a monitored + file object becomes ready + + Returns: + list of (key, events) for ready file objects + `events` is a bitwise mask of EVENT_READ|EVENT_WRITE + 'b'Close the selector. + + This must be called to make sure that any underlying resource is freed. + 'u'Close the selector. + + This must be called to make sure that any underlying resource is freed. + 'b'Return the key associated to a registered file object. + + Returns: + SelectorKey for this file object + 'u'Return the key associated to a registered file object. + + Returns: + SelectorKey for this file object + 'b'Selector is closed'u'Selector is closed'b'Return a mapping of file objects to selector keys.'u'Return a mapping of file objects to selector keys.'b'Base selector implementation.'u'Base selector implementation.'b'Return a file descriptor from a file object. + + This wraps _fileobj_to_fd() to do an exhaustive search in case + the object is invalid but we still have it in our map. This + is used by unregister() so we can unregister an object that + was previously registered even if it is closed. It is also + used by _SelectorMapping. + 'u'Return a file descriptor from a file object. + + This wraps _fileobj_to_fd() to do an exhaustive search in case + the object is invalid but we still have it in our map. This + is used by unregister() so we can unregister an object that + was previously registered even if it is closed. It is also + used by _SelectorMapping. + 'b'Invalid events: {!r}'u'Invalid events: {!r}'b'{!r} (FD {}) is already registered'u'{!r} (FD {}) is already registered'b'Return the key associated to a given file descriptor. + + Parameters: + fd -- file descriptor + + Returns: + corresponding key, or None if not found + 'u'Return the key associated to a given file descriptor. + + Parameters: + fd -- file descriptor + + Returns: + corresponding key, or None if not found + 'b'Select-based selector.'u'Select-based selector.'b'Base class shared between poll, epoll and devpoll selectors.'u'Base class shared between poll, epoll and devpoll selectors.'b' is not registered'u' is not registered'b'Poll-based selector.'u'Poll-based selector.'b'epoll'u'epoll'b'Epoll-based selector.'u'Epoll-based selector.'b'devpoll'u'devpoll'b'Solaris /dev/poll selector.'u'Solaris /dev/poll selector.'b'kqueue'u'kqueue'b'Kqueue-based selector.'u'Kqueue-based selector.'b'KqueueSelector'u'KqueueSelector'b'EpollSelector'u'EpollSelector'b'DevpollSelector'u'DevpollSelector'u'selectors'HTTP server classes. + +Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see +SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, +and CGIHTTPRequestHandler for CGI scripts. + +It does, however, optionally implement HTTP/1.1 persistent connections, +as of version 0.3. + +Notes on CGIHTTPRequestHandler +------------------------------ + +This class implements GET and POST requests to cgi-bin scripts. + +If the os.fork() function is not present (e.g. on Windows), +subprocess.Popen() is used as a fallback, with slightly altered semantics. + +In all cases, the implementation is intentionally naive -- all +requests are executed synchronously. + +SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL +-- it may execute arbitrary Python code or external programs. + +Note that status code 200 is sent prior to execution of a CGI script, so +scripts cannot send other status codes such as 302 (redirect). + +XXX To do: + +- log requests even later (to capture byte count) +- log user-agent header and other interesting goodies +- send error log to separate file +ThreadingHTTPServer + + + + Error response + + +

Error response

+

Error code: %(code)d

+

Message: %(message)s.

+

Error code explanation: %(code)s - %(explain)s.

+ + +DEFAULT_ERROR_MESSAGEtext/html;charset=utf-8DEFAULT_ERROR_CONTENT_TYPETCPServerallow_reuse_addressserver_bindOverride server_bind to store the server name.server_addressserver_nameThreadingMixIndaemon_threadsStreamRequestHandlerHTTP request handler base class. + + The following explanation of HTTP serves to guide you through the + code as well as to expose any misunderstandings I may have about + HTTP (so you don't need to read the code to figure out I'm wrong + :-). + + HTTP (HyperText Transfer Protocol) is an extensible protocol on + top of a reliable stream transport (e.g. TCP/IP). The protocol + recognizes three parts to a request: + + 1. One line identifying the request type and path + 2. An optional set of RFC-822-style headers + 3. An optional data part + + The headers and data are separated by a blank line. + + The first line of the request has the form + + + + where is a (case-sensitive) keyword such as GET or POST, + is a string containing path information for the request, + and should be the string "HTTP/1.0" or "HTTP/1.1". + is encoded using the URL encoding scheme (using %xx to signify + the ASCII character with hex code xx). + + The specification specifies that lines are separated by CRLF but + for compatibility with the widest range of clients recommends + servers also handle LF. Similarly, whitespace in the request line + is treated sensibly (allowing multiple spaces between components + and allowing trailing whitespace). + + Similarly, for output, lines ought to be separated by CRLF pairs + but most clients grok LF characters just fine. + + If the first line of the request has the form + + + + (i.e. is left out) then this is assumed to be an HTTP + 0.9 request; this form has no optional headers and data part and + the reply consists of just the data. + + The reply form of the HTTP 1.x protocol again has three parts: + + 1. One line giving the response code + 2. An optional set of RFC-822-style headers + 3. The data + + Again, the headers and data are separated by a blank line. + + The response code line has the form + + + + where is the protocol version ("HTTP/1.0" or "HTTP/1.1"), + is a 3-digit response code indicating success or + failure of the request, and is an optional + human-readable string explaining what the response code means. + + This server parses the request and the headers, and then calls a + function specific to the request type (). Specifically, + a request SPAM will be handled by a method do_SPAM(). If no + such method exists the server sends an error response to the + client. If it exists, it is called with no arguments: + + do_SPAM() + + Note that the request name is case sensitive (i.e. SPAM and spam + are different requests). + + The various request details are stored in instance variables: + + - client_address is the client IP address in the form (host, + port); + + - command, path and version are the broken-down request line; + + - headers is an instance of email.message.Message (or a derived + class) containing the header information; + + - rfile is a file object open for reading positioned at the + start of the optional input data part; + + - wfile is a file object open for writing. + + IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! + + The first thing to be written must be the response line. Then + follow 0 or more header lines, then a blank line, and then the + actual data (if any). The meaning of the header lines depends on + the command executed by the server; in most cases, when data is + returned, there should be at least one header line of the form + + Content-type: / + + where and should be registered MIME types, + e.g. "text/html" or "text/plain". + + Python/BaseHTTP/server_versionerror_message_formaterror_content_typedefault_request_versionparse_requestParse a request (internal). + + The request should be stored in self.raw_requestline; the results + are in self.command, self.path, self.request_version and + self.headers. + + Return True for success, False for failure; on failure, any relevant + error response has already been sent back. + + request_versionclose_connectionraw_requestlinerequestlinebase_version_numberversion_numbersend_errorBad request version (%r)protocol_versionInvalid HTTP version (%s)Bad request syntax (%r)Bad HTTP/0.9 request type (%r)rfileLine too longToo many headersconntypeExpect100-continuehandle_expect_100Decide what to do with an "Expect: 100-continue" header. + + If the client is expecting a 100 Continue response, we must + respond with either a 100 Continue or a final response before + waiting for the request body. The default is to always respond + with a 100 Continue. You can behave differently (for example, + reject unauthorized requests) by overriding this method. + + This method should either return True (possibly after sending + a 100 Continue response) or send an error response and return + False. + + send_response_onlyhandle_one_requestHandle a single HTTP request. + + You normally don't need to override this method; see the class + __doc__ string for information on how to handle specific HTTP + commands such as GET and POST. + + 65537mnameUnsupported method (%r)Request timed out: %rHandle multiple requests if necessary.explainSend and log an error reply. + + Arguments are + * code: an HTTP error code + 3 digits + * message: a simple optional 1 line reason phrase. + *( HTAB / SP / VCHAR / %x80-FF ) + defaults to short entry matching the response code + * explain: a detailed message defaults to the long entry + matching the response code. + + This sends an error response (so it must be called before any + output has been generated), logs the error, and finally sends + a piece of HTML explaining the error to the user. + + shortmsglongmsgcode %d, message %sAdd the response header to the headers buffer and log the + response code. + + Also send two standard headers with the server software + version and the current date. + + log_requestversion_stringdate_time_stringSend the response header only._headers_buffer%s %d %s +Send a MIME header to the headers buffer.Send the blank line ending the MIME headers.flush_headersLog an accepted request. + + This is called by send_response(). + + "%s" %s %sLog an error. + + This is called when a request cannot be fulfilled. By + default it passes the message on to log_message(). + + Arguments are the same as for log_message(). + + XXX This should go to the separate error log. + + Log an arbitrary message. + + This is used by all other logging functions. Override + it if you have specific logging wishes. + + The first argument, FORMAT, is a format string for the + message to be logged. If the format string contains + any % escapes requiring parameters, they should be + specified as subsequent arguments (it's just like + printf!). + + The client ip and current date/time are prefixed to + every message. + + %s - - [%s] %s +address_stringlog_date_time_stringReturn the server software version string.Return the current date and time formatted for a message header.Return the current time formatted for logging.%02d/%3s/%04d %02d:%02d:%02dmonthnameweekdaynameReturn the client address.client_addressSimple HTTP request handler with GET and HEAD commands. + + This serves files from the current directory and any of its + subdirectories. The MIME type for files is determined by + calling the .guess_type() method. + + The GET and HEAD requests are identical except that the HEAD + request omits the actual contents of the file. + + SimpleHTTP/Serve a GET request.send_headcopyfiledo_HEADServe a HEAD request.Common code for GET and HEAD commands. + + This sends the response code and MIME headers. + + Return value is either a file object (which has to be copied + to the outputfile by the caller unless the command was HEAD, + and must be closed by the caller under all circumstances), or + None, in which case the caller has nothing further to do. + + translate_pathnew_partsnew_urlLocationindex.htmlindex.htmlist_directoryFile not foundIf-Modified-SinceIf-None-Matchparsedate_to_datetimeimslast_modifLast-ModifiedHelper to produce a directory listing (absent index.html). + + Return value is either a file object, or None (indicating an + error). In either case, the headers are sent, making the + interface the same as for send_head(). + + No permission to list directorydisplaypathDirectory listing for %s'' +''%s + +

%s


+
    displaynamelinkname
  • %s
+
+ + +text/html; charset=%sTranslate a /-separated PATH to the local filename syntax. + + Components that mean special things to the local file system + (e.g. drive or directory names) are ignored. (XXX They should + probably be diagnosed.) + + trailing_slashoutputfileCopy all data between two file objects. + + The SOURCE argument is a file object open for reading + (or anything with a read() method) and the DESTINATION + argument is a file object open for writing (or + anything with a write() method). + + The only reason for overriding this would be to change + the block size or perhaps to replace newlines by CRLF + -- note however that this the default server uses this + to copy binary data as well. + + copyfileobjGuess the type of a file. + + Argument is a PATH (a filename). + + Return value is a string of the form type/subtype, + usable for a MIME Content-type header. + + The default implementation looks the file's extension + up in the table self.extensions_map, using application/octet-stream + as a default; however it would be permissible (if + slow) to look inside the data to make a better guess. + + extensions_map_url_collapse_path + Given a URL path, remove extra '/'s and '.' path elements and collapse + any '..' references and returns a collapsed path. + + Implements something akin to RFC-2396 5.2 step 6 to parse relative paths. + The utility of this function is limited to is_cgi method and helps + preventing some security attacks. + + Returns: The reconstituted URL, which will always start with a '/'. + + Raises: IndexError if too many '..' occur within the path. + + head_partstail_partsplitpathcollapsed_pathnobodynobody_uidInternal routine to get nobody's uidTest for executable file.Complete HTTP server with GET, HEAD and POST commands. + + GET and HEAD also support running CGI scripts. + + The POST command is *only* implemented for CGI scripts. + + have_forkrbufsizedo_POSTServe a POST request. + + This is only implemented for CGI scripts. + + is_cgirun_cgiCan only POST to CGI scriptsVersion of send_head that support CGI scriptsTest whether self.path corresponds to a CGI script. + + Returns True and updates the cgi_info attribute to the tuple + (dir, rest) if self.path requires running a CGI script. + Returns False otherwise. + + If any exception is raised, the caller should assume that + self.path was rejected as invalid and act accordingly. + + The default implementation tests whether the normalized url + path begins with one of the strings in self.cgi_directories + (and the next character is a '/' or the end of the string). + + dir_sepcgi_directoriescgi_info/cgi-bin/htbinis_executableTest whether argument path is an executable file.is_pythonTest whether argument path is a Python script.Execute a CGI script.nextdirnextrestscriptdirscriptnamescriptfileNo such CGI script (%r)CGI script is not a plain file (%r)ispyCGI script is not executable (%r)SERVER_SOFTWARESERVER_NAMECGI/1.1GATEWAY_INTERFACESERVER_PROTOCOLSERVER_PORTuqrestPATH_INFOPATH_TRANSLATEDSCRIPT_NAMEQUERY_STRINGREMOTE_ADDRauthorizationAUTH_TYPEREMOTE_USERCONTENT_TYPECONTENT_LENGTHrefererHTTP_REFERER + HTTP_ACCEPTuser-agentuaHTTP_USER_AGENTcookie_strHTTP_COOKIEREMOTE_HOSTScript output followsdecoded_queryCGI script exit status %#xcmdlinew.execommand: %slist2cmdlineCGI script exited OK_get_best_familyHandlerClassServerClassTest the HTTP request handler class. + + This runs an HTTP server on port 8000 (or the port argument). + + address_familyhttpdurl_hostServing HTTP on port (http://"(http://"/) ... +Keyboard interrupt received, exiting.--cgiRun as CGI Server--bindADDRESSSpecify alternate bind address [default: all interfaces]'Specify alternate bind address ''[default: all interfaces]'--directorySpecify alternative directory [default:current directory]'Specify alternative directory ''[default:current directory]'Specify alternate port [default: 8000]cgihandler_classDualStackServer# See also:# HTTP Working Group T. Berners-Lee# INTERNET-DRAFT R. T. Fielding# H. Frystyk Nielsen# Expires September 8, 1995 March 8, 1995# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt# Network Working Group R. Fielding# Request for Comments: 2616 et al# Obsoletes: 2068 June 1999# Category: Standards Track# URL: http://www.faqs.org/rfcs/rfc2616.html# Log files# ---------# Here's a quote from the NCSA httpd docs about log file format.# | The logfile format is as follows. Each line consists of:# |# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb# | host: Either the DNS name or the IP number of the remote client# | rfc931: Any information returned by identd for this person,# | - otherwise.# | authuser: If user sent a userid for authentication, the user name,# | - otherwise.# | DD: Day# | Mon: Month (calendar name)# | YYYY: Year# | hh: hour (24-hour format, the machine's timezone)# | mm: minutes# | ss: seconds# | request: The first line of the HTTP request as sent by the client.# | ddd: the status code returned by the server, - if not available.# | bbbb: the total number of bytes sent,# | *not including the HTTP/1.0 header*, - if not available# | You can determine the name of the file accessed through request.# (Actually, the latter is only true if you know the server configuration# at the time the request was made!)# For gethostbyaddr()# Default error message template# Seems to make sense in testing environment# The Python system version, truncated to its first component.# The server software version. You may want to override this.# The format is multiple whitespace-separated strings,# where each string is of the form name[/version].# The default request version. This only affects responses up until# the point where the request line is parsed, so it mainly decides what# the client gets back when sending a malformed request line.# Most web servers default to HTTP 0.9, i.e. don't send a status line.# set in case of error on the first line# Enough to determine protocol version# RFC 2145 section 3.1 says there can be only one "." and# - major and minor numbers MUST be treated as# separate integers;# - HTTP/2.4 is a lower version than HTTP/2.13, which in# turn is lower than HTTP/12.3;# - Leading zeros MUST be ignored by recipients.# Examine the headers and look for a Connection directive.# Examine the headers and look for an Expect directive# An error code has been sent, just exit#actually send the response if not already done.#a read or a write timed out. Discard this connection# Message body is omitted for cases described in:# - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)# - RFC7231: 6.3.6. 205(Reset Content)# HTML encode to prevent Cross Site Scripting attacks# (see bug #1100201)# Essentially static class variables# The version of the HTTP protocol we support.# Set this to HTTP/1.1 to enable automatic keepalive# MessageClass used to parse headers# redirect browser - doing basically what apache does# check for trailing "/" which should return 404. See Issue17324# The test for this was added in test_httpserver.py# However, some OS platforms accept a trailingSlash as a filename# See discussion on python-dev and Issue34711 regarding# parseing and rejection of filenames with a trailing slash# Use browser cache if possible# compare If-Modified-Since and time of last file modification# ignore ill-formed values# obsolete format with no timezone, cf.# https://tools.ietf.org/html/rfc7231#section-7.1.1.1# compare to UTC datetime of last modification# remove microseconds, like in If-Modified-Since# Append / for directories or @ for symbolic links# Note: a link to a directory displays with @ and links with /# abandon query parameters# Don't forget explicit trailing slash when normalizing. Issue17324# Ignore components that are not a simple file/directory name# try to read system mime.types# Default# Utilities for CGIHTTPRequestHandler# Query component should not be involved.# Similar to os.path.split(os.path.normpath(path)) but specific to URL# path semantics rather than local operating system semantics.# IndexError if more '..' than prior parts# Determine platform specifics# Make rfile unbuffered -- we need to read one line and then pass# the rest to a subprocess, so we can't use buffered input.# find an explicit query string, if present.# dissect the part after the directory name into a script name &# a possible additional path, to be stored in PATH_INFO.# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html# XXX Much of the following could be prepared ahead of time!# XXX REMOTE_IDENT# XXX Other HTTP_* headers# Since we're setting the env in the parent, provide empty# values to override previously set values# Unix -- fork as we should# Always flush before forking# throw away additional data [see bug #427345]# Non-Unix -- use subprocess# On Windows, use python.exe, not pythonw.exe# ensure dual-stack is not disabled; ref #38907# suppress exception when protocol is IPv4b'HTTP server classes. + +Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see +SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, +and CGIHTTPRequestHandler for CGI scripts. + +It does, however, optionally implement HTTP/1.1 persistent connections, +as of version 0.3. + +Notes on CGIHTTPRequestHandler +------------------------------ + +This class implements GET and POST requests to cgi-bin scripts. + +If the os.fork() function is not present (e.g. on Windows), +subprocess.Popen() is used as a fallback, with slightly altered semantics. + +In all cases, the implementation is intentionally naive -- all +requests are executed synchronously. + +SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL +-- it may execute arbitrary Python code or external programs. + +Note that status code 200 is sent prior to execution of a CGI script, so +scripts cannot send other status codes such as 302 (redirect). + +XXX To do: + +- log requests even later (to capture byte count) +- log user-agent header and other interesting goodies +- send error log to separate file +'u'HTTP server classes. + +Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see +SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, +and CGIHTTPRequestHandler for CGI scripts. + +It does, however, optionally implement HTTP/1.1 persistent connections, +as of version 0.3. + +Notes on CGIHTTPRequestHandler +------------------------------ + +This class implements GET and POST requests to cgi-bin scripts. + +If the os.fork() function is not present (e.g. on Windows), +subprocess.Popen() is used as a fallback, with slightly altered semantics. + +In all cases, the implementation is intentionally naive -- all +requests are executed synchronously. + +SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL +-- it may execute arbitrary Python code or external programs. + +Note that status code 200 is sent prior to execution of a CGI script, so +scripts cannot send other status codes such as 302 (redirect). + +XXX To do: + +- log requests even later (to capture byte count) +- log user-agent header and other interesting goodies +- send error log to separate file +'b'0.6'u'0.6'b'HTTPServer'u'HTTPServer'b'ThreadingHTTPServer'u'ThreadingHTTPServer'b'BaseHTTPRequestHandler'u'BaseHTTPRequestHandler'b' + + + + Error response + + +

Error response

+

Error code: %(code)d

+

Message: %(message)s.

+

Error code explanation: %(code)s - %(explain)s.

+ + +'u' + + + + Error response + + +

Error response

+

Error code: %(code)d

+

Message: %(message)s.

+

Error code explanation: %(code)s - %(explain)s.

+ + +'b'text/html;charset=utf-8'u'text/html;charset=utf-8'b'Override server_bind to store the server name.'u'Override server_bind to store the server name.'b'HTTP request handler base class. + + The following explanation of HTTP serves to guide you through the + code as well as to expose any misunderstandings I may have about + HTTP (so you don't need to read the code to figure out I'm wrong + :-). + + HTTP (HyperText Transfer Protocol) is an extensible protocol on + top of a reliable stream transport (e.g. TCP/IP). The protocol + recognizes three parts to a request: + + 1. One line identifying the request type and path + 2. An optional set of RFC-822-style headers + 3. An optional data part + + The headers and data are separated by a blank line. + + The first line of the request has the form + + + + where is a (case-sensitive) keyword such as GET or POST, + is a string containing path information for the request, + and should be the string "HTTP/1.0" or "HTTP/1.1". + is encoded using the URL encoding scheme (using %xx to signify + the ASCII character with hex code xx). + + The specification specifies that lines are separated by CRLF but + for compatibility with the widest range of clients recommends + servers also handle LF. Similarly, whitespace in the request line + is treated sensibly (allowing multiple spaces between components + and allowing trailing whitespace). + + Similarly, for output, lines ought to be separated by CRLF pairs + but most clients grok LF characters just fine. + + If the first line of the request has the form + + + + (i.e. is left out) then this is assumed to be an HTTP + 0.9 request; this form has no optional headers and data part and + the reply consists of just the data. + + The reply form of the HTTP 1.x protocol again has three parts: + + 1. One line giving the response code + 2. An optional set of RFC-822-style headers + 3. The data + + Again, the headers and data are separated by a blank line. + + The response code line has the form + + + + where is the protocol version ("HTTP/1.0" or "HTTP/1.1"), + is a 3-digit response code indicating success or + failure of the request, and is an optional + human-readable string explaining what the response code means. + + This server parses the request and the headers, and then calls a + function specific to the request type (). Specifically, + a request SPAM will be handled by a method do_SPAM(). If no + such method exists the server sends an error response to the + client. If it exists, it is called with no arguments: + + do_SPAM() + + Note that the request name is case sensitive (i.e. SPAM and spam + are different requests). + + The various request details are stored in instance variables: + + - client_address is the client IP address in the form (host, + port); + + - command, path and version are the broken-down request line; + + - headers is an instance of email.message.Message (or a derived + class) containing the header information; + + - rfile is a file object open for reading positioned at the + start of the optional input data part; + + - wfile is a file object open for writing. + + IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! + + The first thing to be written must be the response line. Then + follow 0 or more header lines, then a blank line, and then the + actual data (if any). The meaning of the header lines depends on + the command executed by the server; in most cases, when data is + returned, there should be at least one header line of the form + + Content-type: / + + where and should be registered MIME types, + e.g. "text/html" or "text/plain". + + 'u'HTTP request handler base class. + + The following explanation of HTTP serves to guide you through the + code as well as to expose any misunderstandings I may have about + HTTP (so you don't need to read the code to figure out I'm wrong + :-). + + HTTP (HyperText Transfer Protocol) is an extensible protocol on + top of a reliable stream transport (e.g. TCP/IP). The protocol + recognizes three parts to a request: + + 1. One line identifying the request type and path + 2. An optional set of RFC-822-style headers + 3. An optional data part + + The headers and data are separated by a blank line. + + The first line of the request has the form + + + + where is a (case-sensitive) keyword such as GET or POST, + is a string containing path information for the request, + and should be the string "HTTP/1.0" or "HTTP/1.1". + is encoded using the URL encoding scheme (using %xx to signify + the ASCII character with hex code xx). + + The specification specifies that lines are separated by CRLF but + for compatibility with the widest range of clients recommends + servers also handle LF. Similarly, whitespace in the request line + is treated sensibly (allowing multiple spaces between components + and allowing trailing whitespace). + + Similarly, for output, lines ought to be separated by CRLF pairs + but most clients grok LF characters just fine. + + If the first line of the request has the form + + + + (i.e. is left out) then this is assumed to be an HTTP + 0.9 request; this form has no optional headers and data part and + the reply consists of just the data. + + The reply form of the HTTP 1.x protocol again has three parts: + + 1. One line giving the response code + 2. An optional set of RFC-822-style headers + 3. The data + + Again, the headers and data are separated by a blank line. + + The response code line has the form + + + + where is the protocol version ("HTTP/1.0" or "HTTP/1.1"), + is a 3-digit response code indicating success or + failure of the request, and is an optional + human-readable string explaining what the response code means. + + This server parses the request and the headers, and then calls a + function specific to the request type (). Specifically, + a request SPAM will be handled by a method do_SPAM(). If no + such method exists the server sends an error response to the + client. If it exists, it is called with no arguments: + + do_SPAM() + + Note that the request name is case sensitive (i.e. SPAM and spam + are different requests). + + The various request details are stored in instance variables: + + - client_address is the client IP address in the form (host, + port); + + - command, path and version are the broken-down request line; + + - headers is an instance of email.message.Message (or a derived + class) containing the header information; + + - rfile is a file object open for reading positioned at the + start of the optional input data part; + + - wfile is a file object open for writing. + + IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! + + The first thing to be written must be the response line. Then + follow 0 or more header lines, then a blank line, and then the + actual data (if any). The meaning of the header lines depends on + the command executed by the server; in most cases, when data is + returned, there should be at least one header line of the form + + Content-type: / + + where and should be registered MIME types, + e.g. "text/html" or "text/plain". + + 'b'Python/'u'Python/'b'BaseHTTP/'u'BaseHTTP/'b'Parse a request (internal). + + The request should be stored in self.raw_requestline; the results + are in self.command, self.path, self.request_version and + self.headers. + + Return True for success, False for failure; on failure, any relevant + error response has already been sent back. + + 'u'Parse a request (internal). + + The request should be stored in self.raw_requestline; the results + are in self.command, self.path, self.request_version and + self.headers. + + Return True for success, False for failure; on failure, any relevant + error response has already been sent back. + + 'b'Bad request version (%r)'u'Bad request version (%r)'b'Invalid HTTP version (%s)'u'Invalid HTTP version (%s)'b'Bad request syntax (%r)'u'Bad request syntax (%r)'b'Bad HTTP/0.9 request type (%r)'u'Bad HTTP/0.9 request type (%r)'b'Line too long'u'Line too long'b'Too many headers'u'Too many headers'b'Expect'u'Expect'b'100-continue'u'100-continue'b'Decide what to do with an "Expect: 100-continue" header. + + If the client is expecting a 100 Continue response, we must + respond with either a 100 Continue or a final response before + waiting for the request body. The default is to always respond + with a 100 Continue. You can behave differently (for example, + reject unauthorized requests) by overriding this method. + + This method should either return True (possibly after sending + a 100 Continue response) or send an error response and return + False. + + 'u'Decide what to do with an "Expect: 100-continue" header. + + If the client is expecting a 100 Continue response, we must + respond with either a 100 Continue or a final response before + waiting for the request body. The default is to always respond + with a 100 Continue. You can behave differently (for example, + reject unauthorized requests) by overriding this method. + + This method should either return True (possibly after sending + a 100 Continue response) or send an error response and return + False. + + 'b'Handle a single HTTP request. + + You normally don't need to override this method; see the class + __doc__ string for information on how to handle specific HTTP + commands such as GET and POST. + + 'u'Handle a single HTTP request. + + You normally don't need to override this method; see the class + __doc__ string for information on how to handle specific HTTP + commands such as GET and POST. + + 'b'Unsupported method (%r)'u'Unsupported method (%r)'b'Request timed out: %r'u'Request timed out: %r'b'Handle multiple requests if necessary.'u'Handle multiple requests if necessary.'b'Send and log an error reply. + + Arguments are + * code: an HTTP error code + 3 digits + * message: a simple optional 1 line reason phrase. + *( HTAB / SP / VCHAR / %x80-FF ) + defaults to short entry matching the response code + * explain: a detailed message defaults to the long entry + matching the response code. + + This sends an error response (so it must be called before any + output has been generated), logs the error, and finally sends + a piece of HTML explaining the error to the user. + + 'u'Send and log an error reply. + + Arguments are + * code: an HTTP error code + 3 digits + * message: a simple optional 1 line reason phrase. + *( HTAB / SP / VCHAR / %x80-FF ) + defaults to short entry matching the response code + * explain: a detailed message defaults to the long entry + matching the response code. + + This sends an error response (so it must be called before any + output has been generated), logs the error, and finally sends + a piece of HTML explaining the error to the user. + + 'b'code %d, message %s'u'code %d, message %s'b'code'b'explain'u'explain'b'Add the response header to the headers buffer and log the + response code. + + Also send two standard headers with the server software + version and the current date. + + 'u'Add the response header to the headers buffer and log the + response code. + + Also send two standard headers with the server software + version and the current date. + + 'b'Server'u'Server'b'Send the response header only.'u'Send the response header only.'b'_headers_buffer'u'_headers_buffer'b'%s %d %s +'u'%s %d %s +'b'Send a MIME header to the headers buffer.'u'Send a MIME header to the headers buffer.'b'Send the blank line ending the MIME headers.'u'Send the blank line ending the MIME headers.'b'Log an accepted request. + + This is called by send_response(). + + 'u'Log an accepted request. + + This is called by send_response(). + + 'b'"%s" %s %s'u'"%s" %s %s'b'Log an error. + + This is called when a request cannot be fulfilled. By + default it passes the message on to log_message(). + + Arguments are the same as for log_message(). + + XXX This should go to the separate error log. + + 'u'Log an error. + + This is called when a request cannot be fulfilled. By + default it passes the message on to log_message(). + + Arguments are the same as for log_message(). + + XXX This should go to the separate error log. + + 'b'Log an arbitrary message. + + This is used by all other logging functions. Override + it if you have specific logging wishes. + + The first argument, FORMAT, is a format string for the + message to be logged. If the format string contains + any % escapes requiring parameters, they should be + specified as subsequent arguments (it's just like + printf!). + + The client ip and current date/time are prefixed to + every message. + + 'u'Log an arbitrary message. + + This is used by all other logging functions. Override + it if you have specific logging wishes. + + The first argument, FORMAT, is a format string for the + message to be logged. If the format string contains + any % escapes requiring parameters, they should be + specified as subsequent arguments (it's just like + printf!). + + The client ip and current date/time are prefixed to + every message. + + 'b'%s - - [%s] %s +'u'%s - - [%s] %s +'b'Return the server software version string.'u'Return the server software version string.'b'Return the current date and time formatted for a message header.'u'Return the current date and time formatted for a message header.'b'Return the current time formatted for logging.'u'Return the current time formatted for logging.'b'%02d/%3s/%04d %02d:%02d:%02d'u'%02d/%3s/%04d %02d:%02d:%02d'b'Return the client address.'u'Return the client address.'b'Simple HTTP request handler with GET and HEAD commands. + + This serves files from the current directory and any of its + subdirectories. The MIME type for files is determined by + calling the .guess_type() method. + + The GET and HEAD requests are identical except that the HEAD + request omits the actual contents of the file. + + 'u'Simple HTTP request handler with GET and HEAD commands. + + This serves files from the current directory and any of its + subdirectories. The MIME type for files is determined by + calling the .guess_type() method. + + The GET and HEAD requests are identical except that the HEAD + request omits the actual contents of the file. + + 'b'SimpleHTTP/'u'SimpleHTTP/'b'Serve a GET request.'u'Serve a GET request.'b'Serve a HEAD request.'u'Serve a HEAD request.'b'Common code for GET and HEAD commands. + + This sends the response code and MIME headers. + + Return value is either a file object (which has to be copied + to the outputfile by the caller unless the command was HEAD, + and must be closed by the caller under all circumstances), or + None, in which case the caller has nothing further to do. + + 'u'Common code for GET and HEAD commands. + + This sends the response code and MIME headers. + + Return value is either a file object (which has to be copied + to the outputfile by the caller unless the command was HEAD, + and must be closed by the caller under all circumstances), or + None, in which case the caller has nothing further to do. + + 'b'Location'u'Location'b'index.html'u'index.html'b'index.htm'u'index.htm'b'File not found'u'File not found'b'If-Modified-Since'u'If-Modified-Since'b'If-None-Match'u'If-None-Match'b'Last-Modified'u'Last-Modified'b'Helper to produce a directory listing (absent index.html). + + Return value is either a file object, or None (indicating an + error). In either case, the headers are sent, making the + interface the same as for send_head(). + + 'u'Helper to produce a directory listing (absent index.html). + + Return value is either a file object, or None (indicating an + error). In either case, the headers are sent, making the + interface the same as for send_head(). + + 'b'No permission to list directory'u'No permission to list directory'b'Directory listing for %s'u'Directory listing for %s'b''u''b' +'u' +'b''u''b'%s +'u'%s +'b' +

%s

'u' +

%s

'b'
+
    'u'
    + +
    + + +'u'
+
+ + +'b'text/html; charset=%s'u'text/html; charset=%s'b'Translate a /-separated PATH to the local filename syntax. + + Components that mean special things to the local file system + (e.g. drive or directory names) are ignored. (XXX They should + probably be diagnosed.) + + 'u'Translate a /-separated PATH to the local filename syntax. + + Components that mean special things to the local file system + (e.g. drive or directory names) are ignored. (XXX They should + probably be diagnosed.) + + 'b'Copy all data between two file objects. + + The SOURCE argument is a file object open for reading + (or anything with a read() method) and the DESTINATION + argument is a file object open for writing (or + anything with a write() method). + + The only reason for overriding this would be to change + the block size or perhaps to replace newlines by CRLF + -- note however that this the default server uses this + to copy binary data as well. + + 'u'Copy all data between two file objects. + + The SOURCE argument is a file object open for reading + (or anything with a read() method) and the DESTINATION + argument is a file object open for writing (or + anything with a write() method). + + The only reason for overriding this would be to change + the block size or perhaps to replace newlines by CRLF + -- note however that this the default server uses this + to copy binary data as well. + + 'b'Guess the type of a file. + + Argument is a PATH (a filename). + + Return value is a string of the form type/subtype, + usable for a MIME Content-type header. + + The default implementation looks the file's extension + up in the table self.extensions_map, using application/octet-stream + as a default; however it would be permissible (if + slow) to look inside the data to make a better guess. + + 'u'Guess the type of a file. + + Argument is a PATH (a filename). + + Return value is a string of the form type/subtype, + usable for a MIME Content-type header. + + The default implementation looks the file's extension + up in the table self.extensions_map, using application/octet-stream + as a default; however it would be permissible (if + slow) to look inside the data to make a better guess. + + 'b' + Given a URL path, remove extra '/'s and '.' path elements and collapse + any '..' references and returns a collapsed path. + + Implements something akin to RFC-2396 5.2 step 6 to parse relative paths. + The utility of this function is limited to is_cgi method and helps + preventing some security attacks. + + Returns: The reconstituted URL, which will always start with a '/'. + + Raises: IndexError if too many '..' occur within the path. + + 'u' + Given a URL path, remove extra '/'s and '.' path elements and collapse + any '..' references and returns a collapsed path. + + Implements something akin to RFC-2396 5.2 step 6 to parse relative paths. + The utility of this function is limited to is_cgi method and helps + preventing some security attacks. + + Returns: The reconstituted URL, which will always start with a '/'. + + Raises: IndexError if too many '..' occur within the path. + + 'b'Internal routine to get nobody's uid'u'Internal routine to get nobody's uid'b'nobody'u'nobody'b'Test for executable file.'u'Test for executable file.'b'Complete HTTP server with GET, HEAD and POST commands. + + GET and HEAD also support running CGI scripts. + + The POST command is *only* implemented for CGI scripts. + + 'u'Complete HTTP server with GET, HEAD and POST commands. + + GET and HEAD also support running CGI scripts. + + The POST command is *only* implemented for CGI scripts. + + 'b'Serve a POST request. + + This is only implemented for CGI scripts. + + 'u'Serve a POST request. + + This is only implemented for CGI scripts. + + 'b'Can only POST to CGI scripts'u'Can only POST to CGI scripts'b'Version of send_head that support CGI scripts'u'Version of send_head that support CGI scripts'b'Test whether self.path corresponds to a CGI script. + + Returns True and updates the cgi_info attribute to the tuple + (dir, rest) if self.path requires running a CGI script. + Returns False otherwise. + + If any exception is raised, the caller should assume that + self.path was rejected as invalid and act accordingly. + + The default implementation tests whether the normalized url + path begins with one of the strings in self.cgi_directories + (and the next character is a '/' or the end of the string). + + 'u'Test whether self.path corresponds to a CGI script. + + Returns True and updates the cgi_info attribute to the tuple + (dir, rest) if self.path requires running a CGI script. + Returns False otherwise. + + If any exception is raised, the caller should assume that + self.path was rejected as invalid and act accordingly. + + The default implementation tests whether the normalized url + path begins with one of the strings in self.cgi_directories + (and the next character is a '/' or the end of the string). + + 'b'/cgi-bin'u'/cgi-bin'b'/htbin'u'/htbin'b'Test whether argument path is an executable file.'u'Test whether argument path is an executable file.'b'Test whether argument path is a Python script.'u'Test whether argument path is a Python script.'b'Execute a CGI script.'u'Execute a CGI script.'b'No such CGI script (%r)'u'No such CGI script (%r)'b'CGI script is not a plain file (%r)'u'CGI script is not a plain file (%r)'b'CGI script is not executable (%r)'u'CGI script is not executable (%r)'b'SERVER_SOFTWARE'u'SERVER_SOFTWARE'b'SERVER_NAME'u'SERVER_NAME'b'CGI/1.1'u'CGI/1.1'b'GATEWAY_INTERFACE'u'GATEWAY_INTERFACE'b'SERVER_PROTOCOL'u'SERVER_PROTOCOL'b'SERVER_PORT'u'SERVER_PORT'b'PATH_INFO'u'PATH_INFO'b'PATH_TRANSLATED'u'PATH_TRANSLATED'b'SCRIPT_NAME'u'SCRIPT_NAME'b'QUERY_STRING'u'QUERY_STRING'b'REMOTE_ADDR'u'REMOTE_ADDR'b'authorization'u'authorization'b'AUTH_TYPE'u'AUTH_TYPE'b'REMOTE_USER'u'REMOTE_USER'b'CONTENT_TYPE'u'CONTENT_TYPE'b'CONTENT_LENGTH'u'CONTENT_LENGTH'b'referer'u'referer'b'HTTP_REFERER'u'HTTP_REFERER'b'accept'u'accept'b' + 'u' + 'b'HTTP_ACCEPT'u'HTTP_ACCEPT'b'user-agent'u'user-agent'b'HTTP_USER_AGENT'u'HTTP_USER_AGENT'b'cookie'u'cookie'b'HTTP_COOKIE'u'HTTP_COOKIE'b'REMOTE_HOST'u'REMOTE_HOST'b'Script output follows'u'Script output follows'b'CGI script exit status %#x'u'CGI script exit status %#x'b'w.exe'u'w.exe'b'command: %s'u'command: %s'b'CGI script exited OK'u'CGI script exited OK'b'Test the HTTP request handler class. + + This runs an HTTP server on port 8000 (or the port argument). + + 'u'Test the HTTP request handler class. + + This runs an HTTP server on port 8000 (or the port argument). + + 'b'Serving HTTP on 'u'Serving HTTP on 'b' port 'u' port 'b' (http://'u' (http://'b'/) ...'u'/) ...'b' +Keyboard interrupt received, exiting.'u' +Keyboard interrupt received, exiting.'b'--cgi'u'--cgi'b'Run as CGI Server'u'Run as CGI Server'b'--bind'u'--bind'b'ADDRESS'u'ADDRESS'b'Specify alternate bind address [default: all interfaces]'u'Specify alternate bind address [default: all interfaces]'b'--directory'u'--directory'b'Specify alternative directory [default:current directory]'u'Specify alternative directory [default:current directory]'b'port'u'port'b'Specify alternate port [default: 8000]'u'Specify alternate port [default: 8000]'A lexical analyzer class for simple shell-like syntaxes.punctuation_charsabcdfeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'abcdfeghijklmnopqrstuvwxyz''ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ''ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'whitespace_splitquotesescapedquotespushbackfilestack();<>|&_punctuation_chars_pushback_chars~-./*?=Push a token onto the stack popped by the get_token methodshlex: pushing token push_sourcenewstreamnewfilePush an input source onto the lexer's input source stack.shlex: pushing to file %sshlex: pushing to stream %spop_sourcePop the input source stack.shlex: popping to %s, line %dGet a token from the input stream (or from stack if it's nonempty)shlex: popping token read_tokensourcehookshlex: token=shlex: token=EOFquotedescapedstatenextcharshlex: in state %r I see character: %rshlex: I see whitespace in whitespace stateshlex: I see EOF in quotes stateNo closing quotationshlex: I see EOF in escape stateNo escaped charactershlex: I see whitespace in word stateshlex: I see punctuation in word stateshlex: raw token=shlex: raw token=EOFHook called on a filename to be sourced.error_leaderEmit a C-compiler-like, Emacs-friendly error-message leader."%s", line %d: Split the string *s* using shell-like syntax.lexsplit_commandReturn a shell-escaped string from *split_command*.[^\w@%+=:,./-]_find_unsafeReturn a shell-escaped version of the string *s*._print_tokensToken: # Input stacking and error message cleanup added by ESR, March 2000# push_source() and pop_source() made explicit by ESR, January 2001.# Posix compliance, split(), string arguments, and# iterator interface by Gustavo Niemeyer, April 2003.# changes to tokenize more like Posix shells by Vinay Sajip, July 2016.# _pushback_chars is a push back queue used by lookahead logic# these chars added because allowed in file names, args, wildcards#remove any punctuation chars from wordchars# No pushback. Get a token.# Handle inclusions# Maybe we got EOF instead?# Neither inclusion nor EOF# past end of file# end of file# emit current token# XXX what error should be raised here?# In posix shells, only the quote itself or the escape# character may be escaped within quotes.# This implements cpp-like semantics for relative-path inclusion.# use single quotes, and put single quotes into double quotes# the string $'b is then quoted as '$'"'"'b'b'A lexical analyzer class for simple shell-like syntaxes.'u'A lexical analyzer class for simple shell-like syntaxes.'b'shlex'u'shlex'b'abcdfeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'u'abcdfeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'b'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'u'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'b'();<>|&'u'();<>|&'b'~-./*?='u'~-./*?='b'Push a token onto the stack popped by the get_token method'u'Push a token onto the stack popped by the get_token method'b'shlex: pushing token 'u'shlex: pushing token 'b'Push an input source onto the lexer's input source stack.'u'Push an input source onto the lexer's input source stack.'b'shlex: pushing to file %s'u'shlex: pushing to file %s'b'shlex: pushing to stream %s'u'shlex: pushing to stream %s'b'Pop the input source stack.'u'Pop the input source stack.'b'shlex: popping to %s, line %d'u'shlex: popping to %s, line %d'b'Get a token from the input stream (or from stack if it's nonempty)'u'Get a token from the input stream (or from stack if it's nonempty)'b'shlex: popping token 'u'shlex: popping token 'b'shlex: token='u'shlex: token='b'shlex: token=EOF'u'shlex: token=EOF'b'shlex: in state %r I see character: %r'u'shlex: in state %r I see character: %r'b'shlex: I see whitespace in whitespace state'u'shlex: I see whitespace in whitespace state'b'shlex: I see EOF in quotes state'u'shlex: I see EOF in quotes state'b'No closing quotation'u'No closing quotation'b'shlex: I see EOF in escape state'u'shlex: I see EOF in escape state'b'No escaped character'u'No escaped character'b'shlex: I see whitespace in word state'u'shlex: I see whitespace in word state'b'shlex: I see punctuation in word state'u'shlex: I see punctuation in word state'b'shlex: raw token='u'shlex: raw token='b'shlex: raw token=EOF'u'shlex: raw token=EOF'b'Hook called on a filename to be sourced.'u'Hook called on a filename to be sourced.'b'Emit a C-compiler-like, Emacs-friendly error-message leader.'u'Emit a C-compiler-like, Emacs-friendly error-message leader.'b'"%s", line %d: 'u'"%s", line %d: 'b'Split the string *s* using shell-like syntax.'u'Split the string *s* using shell-like syntax.'b'Return a shell-escaped string from *split_command*.'u'Return a shell-escaped string from *split_command*.'b'[^\w@%+=:,./-]'u'[^\w@%+=:,./-]'b'Return a shell-escaped version of the string *s*.'u'Return a shell-escaped version of the string *s*.'b''''u''''b'Token: 'u'Token: 'Utility functions for copying and archiving files and directory trees. + +XXX The functions here don't copy the resource fork or other metadata on Mac. + +_ZLIB_SUPPORTED_BZ2_SUPPORTED_LZMA_SUPPORTED_WINDOWSCOPY_BUFSIZE_USE_CP_SENDFILE_HAS_FCOPYFILE.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC_WIN_DEFAULT_PATHEXTcopymodecopystatcopy2copytreeSpecialFileErrorExecErrormake_archiveget_archive_formatsregister_archive_formatunregister_archive_formatget_unpack_formatsregister_unpack_formatunregister_unpack_formatunpack_archiveSameFileErrorRaised when source and destination are the same file.Raised when trying to do a kind of operation (e.g. copying) which is + not supported on a special file (e.g. a named pipe)Raised when a command could not be executedReadErrorRaised when an archive cannot be readRegistryErrorRaised when a registry operation with the archiving + and unpacking registries fails_GiveupOnFastCopyRaised as a signal to fallback on using raw read()/write() + file copy when fast-copy functions fail to do so. + _fastcopy_fcopyfileCopy a regular file content or metadata by using high-performance + fcopyfile(3) syscall (macOS). + infdoutfd_fastcopy_sendfileCopy data from one regular mmap-like fd to another by using + high-performance sendfile(2) syscall. + This should work on Linux >= 2.6.33 only. + sent_copyfileobj_readintoreadinto()/memoryview() based variant of copyfileobj(). + *fsrc* must support readinto() method and both files must be + open in binary mode. + fsrc_readintofdst_writesmvcopy data from file-like object fsrc to file-like object fdstfsrc_read_samefile_islinkCopy data from src to dst in the most efficient way possible. + + If follow_symlinks is not set and src is a symbolic link, a new + symlink will be created instead of copying the file it points to. + + shutil.copyfile{!r} and {!r} are the same filefile_size`%s` is a named pipeCopy mode bits from src to dst. + + If follow_symlinks is not set, symlinks aren't followed if and only + if both `src` and `dst` are symlinks. If `lchmod` isn't available + (e.g. Linux) this method does nothing. + + shutil.copymodestat_funcchmod_funclistxattr_copyxattrCopy extended filesystem attributes from `src` to `dst`. + + Overwrite existing attributes. + + If `follow_symlinks` is false, symlinks won't be followed. + + getxattrCopy file metadata + + Copy the permission bits, last access time, last modification time, and + flags from `src` to `dst`. On Linux, copystat() also copies the "extended + attributes" where possible. The file contents, owner, and group are + unaffected. `src` and `dst` are path-like objects or path names given as + strings. + + If the optional flag `follow_symlinks` is not set, symlinks aren't + followed if and only if both `src` and `dst` are symlinks. + shutil.copystat_nopfollowCopy data and mode bits ("cp src dst"). Return the file's destination. + + The destination may be a directory. + + If follow_symlinks is false, symlinks won't be followed. This + resembles GNU's "cp -P src dst". + + If source and destination are the same file, a SameFileError will be + raised. + + Copy data and metadata. Return the file's destination. + + Metadata is copied with copystat(). Please see the copystat function + for more information. + + The destination may be a directory. + + If follow_symlinks is false, symlinks won't be followed. This + resembles GNU's "cp -P src dst". + Function that can be used as copytree() ignore parameter. + + Patterns is a sequence of glob-style patterns + that are used to exclude files_ignore_patternsignored_names_copytreesymlinkscopy_functionignore_dangling_symlinksdirs_exist_okuse_srcentrysrcentrysrcnamedstnamesrcobjst_reparse_tagIO_REPARSE_TAG_MOUNT_POINTlinktoRecursively copy a directory tree and return the destination directory. + + dirs_exist_ok dictates whether to raise an exception in case dst or any + missing parent directory already exists. + + If exception(s) occur, an Error is raised with a list of reasons. + + If the optional symlinks flag is true, symbolic links in the + source tree result in symbolic links in the destination tree; if + it is false, the contents of the files pointed to by symbolic + links are copied. If the file pointed by the symlink doesn't + exist, an exception will be added in the list of errors raised in + an Error exception at the end of the copy process. + + You can set the optional ignore_dangling_symlinks flag to true if you + want to silence this exception. Notice that this has no effect on + platforms that don't support os.symlink. + + The optional ignore argument is a callable. If given, it + is called with the `src` parameter, which is the directory + being visited by copytree(), and `names` which is the list of + `src` contents, as returned by os.listdir(): + + callable(src, names) -> ignored_names + + Since copytree() is called recursively, the callable will be + called once for each directory that is copied. It returns a + list of names relative to the `src` directory that should + not be copied. + + The optional copy_function argument is a callable that will be used + to copy each file. It will be called with the source path and the + destination path as arguments. By default, copy2() is used, but any + function that supports the same signature (like copy()) can be used. + + shutil.copytreeitrst_file_attributes_rmtree_isdirFILE_ATTRIBUTE_REPARSE_POINT_rmtree_islink_rmtree_unsafeCannot call rmtree on a symbolic link_rmtree_safe_fd"Cannot call rmtree on a symbolic ""link"_use_fd_functionsRecursively delete a directory tree. + + If ignore_errors is set, errors are ignored; otherwise, if onerror + is set, it is called to handle the error with arguments (func, + path, exc_info) where func is platform and implementation dependent; + path is the argument to that function that caused it to fail; and + exc_info is a tuple returned by sys.exc_info(). If ignore_errors + is false and onerror is None, an exception is raised. + + shutil.rmtreeavoids_symlink_attacks_basenameRecursively move a file or directory to another location. This is + similar to the Unix "mv" command. Return the file or directory's + destination. + + If the destination is a directory or a symlink to a directory, the source + is moved inside the directory. The destination path must not already + exist. + + If the destination already exists but is not a directory, it may be + overwritten depending on os.rename() semantics. + + If the destination is on our current filesystem, then rename() is used. + Otherwise, src is copied to the destination and then removed. Symlinks are + recreated under the new name if os.rename() fails because of cross + filesystem renames. + + The optional `copy_function` argument is a callable that will be used + to copy the source or it will be delegated to `copytree`. + By default, copy2() is used, but any function that supports the same + signature (like copy()) can be used. + + A lot more could be done here... A look at a mv.c shows a lot of + the issues this implementation glosses over. + + shutil.movereal_dstDestination path '%s' already exists_destinsrcCannot move a directory '%s' into itself '%s'."Cannot move a directory '%s' into itself"" '%s'."_is_immutableCannot move the non-empty directory '%s': Lacking write permission to '%s'."Cannot move the non-empty directory ""'%s': Lacking write permission to '%s'."immutable_states_get_gidReturns a gid, given a group name._get_uidReturns an uid, given a user name._make_tarballbase_nameCreate a (possibly compressed) tar file from all the files under + 'base_dir'. + + 'compress' must be "gzip" (the default), "bzip2", "xz", or None. + + 'owner' and 'group' can be used to define an owner and a group for the + archive that is being built. If not provided, the current owner and group + will be used. + + The output tar file will be named 'base_name' + ".tar", possibly plus + the appropriate compression extension (".gz", ".bz2", or ".xz"). + + Returns the output filename. + tar_compressiongzbad value for 'compress', or compression format not supported : {0}"bad value for 'compress', or compression format not ""supported : {0}"tarfilecompress_extarchive_namearchive_dirCreating tar archiveuid_set_uid_gidtarinfognamew|%star_make_zipfileCreate a zip file from all the files under 'base_dir'. + + The output zip file will be named 'base_name' + ".zip". Returns the + name of the output zip file. + zipfilezip_filenamecreating '%s' and adding '%s' to itZipFileZIP_DEFLATEDzfadding '%s'uncompressed tar file_ARCHIVE_FORMATSgzip'ed tar-filegztarZIP filebzip2'ed tar-filebztarxz'ed tar-filexztarReturns a list of supported formats for archiving and unarchiving. + + Each element of the returned sequence is a tuple (name, description) + Registers an archive format. + + name is the name of the format. function is the callable that will be + used to create archives. If provided, extra_args is a sequence of + (name, value) tuples that will be passed as arguments to the callable. + description can be provided to describe the format, and will be returned + by the get_archive_formats() function. + The %s object is not callableextra_args needs to be a sequenceextra_args elements are : (arg_name, value)root_dirCreate an archive file (eg. zip or tar). + + 'base_name' is the name of the file to create, minus any format-specific + extension; 'format' is the archive format: one of "zip", "tar", "gztar", + "bztar", or "xztar". Or any other registered format. + + 'root_dir' is a directory that will be the root directory of the + archive; ie. we typically chdir into 'root_dir' before creating the + archive. 'base_dir' is the directory where we start archiving from; + ie. 'base_dir' will be the common prefix of all files and + directories in the archive. 'root_dir' and 'base_dir' both default + to the current directory. Returns the name of the archive file. + + 'owner' and 'group' are used when creating a tar archive. By default, + uses the current owner and group. + shutil.make_archivesave_cwdchanging into '%s'format_infounknown archive format '%s'changing back to '%s'Returns a list of supported formats for unpacking. + + Each element of the returned sequence is a tuple + (name, extensions, description) + _UNPACK_FORMATS_check_unpack_optionsChecks what gets registered as an unpacker.existing_extensions%s is already registered for "%s"The registered function must be a callableRegisters an unpack format. + + `name` is the name of the format. `extensions` is a list of extensions + corresponding to the format. + + `function` is the callable that will be + used to unpack archives. The callable will receive archives to unpack. + If it's unable to handle an archive, it needs to raise a ReadError + exception. + + If provided, `extra_args` is a sequence of + (name, value) tuples that will be passed as arguments to the callable. + description can be provided to describe the format, and will be returned + by the get_unpack_formats() function. + Removes the pack format from the registry._ensure_directoryEnsure that the parent directory of `path` exists_unpack_zipfileextract_dirUnpack zip `filename` to `extract_dir` + is_zipfile%s is not a zip fileinfolist_unpack_tarfileUnpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir` + tarobjTarError%s is not a compressed or uncompressed tar fileextractall_find_unpack_formatUnpack an archive. + + `filename` is the name of the archive. + + `extract_dir` is the name of the target directory, where the archive + is unpacked. If not provided, the current working directory is used. + + `format` is the archive format: one of "zip", "tar", "gztar", "bztar", + or "xztar". Or any other registered format. If not provided, + unpack_archive will use the filename extension and see if an unpacker + was registered for that extension. + + In case none is found, a ValueError is raised. + shutil.unpack_archiveUnknown unpack format '{0}'Unknown archive format '{0}'disk_usagetotal used free_ntuple_diskusageTotal space in bytesUsed space in bytesusedFree space in bytesfreeReturn disk usage statistics about the given path. + + Returned value is a named tuple with attributes 'total', 'used' and + 'free', which are the amount of total, used and free space, in bytes. + Return disk usage statistics about the given path. + + Returned values is a named tuple with attributes 'total', 'used' and + 'free', which are the amount of total, used and free space, in bytes. + _getdiskusageChange owner user and group of the given path. + + user and group can be the uid/gid or the user/group names, and in that case, + they are converted to their respective uid/gid. + shutil.chownuser and/or group must be set_userno such user: {!r}no such group: {!r}Get the size of the terminal window. + + For each of the two dimensions, the environment variable, COLUMNS + and LINES respectively, is checked. If the variable is defined and + the value is a positive integer, it is used. + + When COLUMNS or LINES is not defined, which is the common case, + the terminal connected to sys.__stdout__ is queried + by invoking os.get_terminal_size. + + If the terminal size cannot be successfully queried, either because + the system doesn't support querying, or because we are not + connected to a terminal, the value given in fallback parameter + is used. Fallback defaults to (80, 24) which is the default + size used by many terminal emulators. + + The value returned is a named tuple of type os.terminal_size. + _access_checkGiven a command, mode, and a PATH string, return the path which + conforms to the given mode on the PATH, or None if there is no such + file. + + `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result + of os.environ.get("PATH"), or can be overridden with a custom search + path. + + use_bytesCS_PATHPATHEXTpathext_sourcepathextthefile# macOS# CMD defaults in Windows 10# disk_usage is added later, if available on the platform# not a regular file# Note: copyfileobj() is left alone in order to not introduce any# unexpected breakage. Possible risks by using zero-copy calls# in copyfileobj() are:# - fdst cannot be open in "a"(ppend) mode# - fsrc and fdst may be open in "t"(ext) mode# - fsrc may be a BufferedReader (which hides unread data in a buffer),# GzipFile (which decompresses data), HTTPResponse (which decodes# chunks).# - possibly others (e.g. encrypted fs/partition?)# Hopefully the whole file will be copied in a single call.# sendfile() is called in a loop 'till EOF is reached (0 return)# so a bufsize smaller or bigger than the actual file size# should not make any difference, also in case the file content# changes while being copied.# min 8MiB# 128MiB# On 32-bit architectures truncate to 1GiB to avoid OverflowError,# see bpo-38319.# ...in oder to have a more informative exception.# sendfile() on this platform (probably Linux < 2.6.33)# does not support copies between regular files (only# sockets).# filesystem is full# Give up on first call and if no data was copied.# Localize variable access to minimize overhead.# Macintosh, Unix.# All other platforms: check for same pathname.# File most likely does not exist# XXX What about other special files? (sockets, devices...)# Windows, see:# https://github.com/python/cpython/pull/7160#discussion_r195405230# follow symlinks (aka don't not follow symlinks)# use the real function if it exists# use the real function only if it exists# *and* it supports follow_symlinks# We must copy extended attributes before the file is (potentially)# chmod()'ed read-only, otherwise setxattr() will error with -EACCES.# if we got a NotImplementedError, it's because# * follow_symlinks=False,# * lchown() is unavailable, and# * either# * fchownat() is unavailable or# * fchownat() doesn't implement AT_SYMLINK_NOFOLLOW.# (it returned ENOSUP.)# therefore we're out of options--we simply cannot chown the# symlink. give up, suppress the error.# (which is what shutil always did in this circumstance.)# Special check for directory junctions, which appear as# symlinks but we want to recurse.# We can't just leave it to `copy_function` because legacy# code with a custom `copy_function` may rely on copytree# doing the right thing.# ignore dangling symlink if the flag is on# otherwise let the copy occur. copy2 will raise an error# Will raise a SpecialFileError for unsupported file types# catch the Error from the recursive copytree so that we can# continue with other files# Copying file access times may fail on Windows# Special handling for directory junctions to make them behave like# symlinks for shutil.rmtree, since in general they do not appear as# regular links.# version vulnerable to race conditions# This can only happen if someone replaces# a directory with a symlink after the call to# os.scandir or entry.is_dir above.# Version using fd-based APIs to protect against races# os.scandir or stat.S_ISDIR above.# While the unsafe rmtree works fine on bytes, the fd based does not.# symlinks to directories are forbidden, see bug #1669# can't continue even if onerror hook returns# Allow introspection of whether or not the hardening against symlink# attacks is supported on the current platform# A basename() variant which first strips the trailing slash, if present.# Thus we always get the last component of the path, even for directories.# We might be on a case insensitive filesystem,# perform the rename anyway.# late import for breaking circular dependency# creating the tarball# first make sure no other unpacker is registered for this extension# don't extract absolute paths or ones with .. in them# file# we need to look at the registered unpackers supported extensions# -1 means don't change it# user can either be an int (the uid) or a string (the system username)# columns, lines are the working values# only query if necessary# stdout is None, closed, detached, or not a terminal, or# os.get_terminal_size() is unsupported# Check that a given file can be accessed with the correct mode.# Additionally check that `file` is not a directory, as on Windows# directories pass the os.access check.# If we're given a path with a directory part, look it up directly rather# than referring to PATH directories. This includes checking relative to the# current directory, e.g. ./script# os.confstr() or CS_PATH is not available# bpo-35755: Don't use os.defpath if the PATH environment variable is# set to an empty string# PATH='' doesn't match, whereas PATH=':' looks in the current directory# The current directory takes precedence on Windows.# PATHEXT is necessary to check on Windows.# See if the given file matches any of the expected path extensions.# This will allow us to short circuit when given "python.exe".# If it does match, only test that one, otherwise we have to try# others.# On other platforms you don't have things like PATHEXT to tell you# what file suffixes are executable, so just pass on cmd as-is.b'Utility functions for copying and archiving files and directory trees. + +XXX The functions here don't copy the resource fork or other metadata on Mac. + +'u'Utility functions for copying and archiving files and directory trees. + +XXX The functions here don't copy the resource fork or other metadata on Mac. + +'b'sendfile'u'sendfile'b'_fcopyfile'u'_fcopyfile'b'.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC'u'.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC'b'copyfileobj'u'copyfileobj'b'copyfile'u'copyfile'b'copymode'u'copymode'b'copystat'u'copystat'b'copy2'u'copy2'b'copytree'u'copytree'b'SpecialFileError'u'SpecialFileError'b'ExecError'u'ExecError'b'make_archive'u'make_archive'b'get_archive_formats'u'get_archive_formats'b'register_archive_format'u'register_archive_format'b'unregister_archive_format'u'unregister_archive_format'b'get_unpack_formats'u'get_unpack_formats'b'register_unpack_format'u'register_unpack_format'b'unregister_unpack_format'u'unregister_unpack_format'b'unpack_archive'u'unpack_archive'b'ignore_patterns'u'ignore_patterns'b'which'u'which'b'get_terminal_size'u'get_terminal_size'b'SameFileError'u'SameFileError'b'Raised when source and destination are the same file.'u'Raised when source and destination are the same file.'b'Raised when trying to do a kind of operation (e.g. copying) which is + not supported on a special file (e.g. a named pipe)'u'Raised when trying to do a kind of operation (e.g. copying) which is + not supported on a special file (e.g. a named pipe)'b'Raised when a command could not be executed'u'Raised when a command could not be executed'b'Raised when an archive cannot be read'u'Raised when an archive cannot be read'b'Raised when a registry operation with the archiving + and unpacking registries fails'u'Raised when a registry operation with the archiving + and unpacking registries fails'b'Raised as a signal to fallback on using raw read()/write() + file copy when fast-copy functions fail to do so. + 'u'Raised as a signal to fallback on using raw read()/write() + file copy when fast-copy functions fail to do so. + 'b'Copy a regular file content or metadata by using high-performance + fcopyfile(3) syscall (macOS). + 'u'Copy a regular file content or metadata by using high-performance + fcopyfile(3) syscall (macOS). + 'b'Copy data from one regular mmap-like fd to another by using + high-performance sendfile(2) syscall. + This should work on Linux >= 2.6.33 only. + 'u'Copy data from one regular mmap-like fd to another by using + high-performance sendfile(2) syscall. + This should work on Linux >= 2.6.33 only. + 'b'readinto()/memoryview() based variant of copyfileobj(). + *fsrc* must support readinto() method and both files must be + open in binary mode. + 'u'readinto()/memoryview() based variant of copyfileobj(). + *fsrc* must support readinto() method and both files must be + open in binary mode. + 'b'copy data from file-like object fsrc to file-like object fdst'u'copy data from file-like object fsrc to file-like object fdst'b'Copy data from src to dst in the most efficient way possible. + + If follow_symlinks is not set and src is a symbolic link, a new + symlink will be created instead of copying the file it points to. + + 'u'Copy data from src to dst in the most efficient way possible. + + If follow_symlinks is not set and src is a symbolic link, a new + symlink will be created instead of copying the file it points to. + + 'b'shutil.copyfile'u'shutil.copyfile'b'{!r} and {!r} are the same file'u'{!r} and {!r} are the same file'b'`%s` is a named pipe'u'`%s` is a named pipe'b'Copy mode bits from src to dst. + + If follow_symlinks is not set, symlinks aren't followed if and only + if both `src` and `dst` are symlinks. If `lchmod` isn't available + (e.g. Linux) this method does nothing. + + 'u'Copy mode bits from src to dst. + + If follow_symlinks is not set, symlinks aren't followed if and only + if both `src` and `dst` are symlinks. If `lchmod` isn't available + (e.g. Linux) this method does nothing. + + 'b'shutil.copymode'u'shutil.copymode'b'lchmod'u'lchmod'b'listxattr'u'listxattr'b'Copy extended filesystem attributes from `src` to `dst`. + + Overwrite existing attributes. + + If `follow_symlinks` is false, symlinks won't be followed. + + 'u'Copy extended filesystem attributes from `src` to `dst`. + + Overwrite existing attributes. + + If `follow_symlinks` is false, symlinks won't be followed. + + 'b'Copy file metadata + + Copy the permission bits, last access time, last modification time, and + flags from `src` to `dst`. On Linux, copystat() also copies the "extended + attributes" where possible. The file contents, owner, and group are + unaffected. `src` and `dst` are path-like objects or path names given as + strings. + + If the optional flag `follow_symlinks` is not set, symlinks aren't + followed if and only if both `src` and `dst` are symlinks. + 'u'Copy file metadata + + Copy the permission bits, last access time, last modification time, and + flags from `src` to `dst`. On Linux, copystat() also copies the "extended + attributes" where possible. The file contents, owner, and group are + unaffected. `src` and `dst` are path-like objects or path names given as + strings. + + If the optional flag `follow_symlinks` is not set, symlinks aren't + followed if and only if both `src` and `dst` are symlinks. + 'b'shutil.copystat'u'shutil.copystat'b'st_flags'u'st_flags'b'EOPNOTSUPP'u'EOPNOTSUPP'b'ENOTSUP'u'ENOTSUP'b'Copy data and mode bits ("cp src dst"). Return the file's destination. + + The destination may be a directory. + + If follow_symlinks is false, symlinks won't be followed. This + resembles GNU's "cp -P src dst". + + If source and destination are the same file, a SameFileError will be + raised. + + 'u'Copy data and mode bits ("cp src dst"). Return the file's destination. + + The destination may be a directory. + + If follow_symlinks is false, symlinks won't be followed. This + resembles GNU's "cp -P src dst". + + If source and destination are the same file, a SameFileError will be + raised. + + 'b'Copy data and metadata. Return the file's destination. + + Metadata is copied with copystat(). Please see the copystat function + for more information. + + The destination may be a directory. + + If follow_symlinks is false, symlinks won't be followed. This + resembles GNU's "cp -P src dst". + 'u'Copy data and metadata. Return the file's destination. + + Metadata is copied with copystat(). Please see the copystat function + for more information. + + The destination may be a directory. + + If follow_symlinks is false, symlinks won't be followed. This + resembles GNU's "cp -P src dst". + 'b'Function that can be used as copytree() ignore parameter. + + Patterns is a sequence of glob-style patterns + that are used to exclude files'u'Function that can be used as copytree() ignore parameter. + + Patterns is a sequence of glob-style patterns + that are used to exclude files'b'winerror'u'winerror'b'Recursively copy a directory tree and return the destination directory. + + dirs_exist_ok dictates whether to raise an exception in case dst or any + missing parent directory already exists. + + If exception(s) occur, an Error is raised with a list of reasons. + + If the optional symlinks flag is true, symbolic links in the + source tree result in symbolic links in the destination tree; if + it is false, the contents of the files pointed to by symbolic + links are copied. If the file pointed by the symlink doesn't + exist, an exception will be added in the list of errors raised in + an Error exception at the end of the copy process. + + You can set the optional ignore_dangling_symlinks flag to true if you + want to silence this exception. Notice that this has no effect on + platforms that don't support os.symlink. + + The optional ignore argument is a callable. If given, it + is called with the `src` parameter, which is the directory + being visited by copytree(), and `names` which is the list of + `src` contents, as returned by os.listdir(): + + callable(src, names) -> ignored_names + + Since copytree() is called recursively, the callable will be + called once for each directory that is copied. It returns a + list of names relative to the `src` directory that should + not be copied. + + The optional copy_function argument is a callable that will be used + to copy each file. It will be called with the source path and the + destination path as arguments. By default, copy2() is used, but any + function that supports the same signature (like copy()) can be used. + + 'u'Recursively copy a directory tree and return the destination directory. + + dirs_exist_ok dictates whether to raise an exception in case dst or any + missing parent directory already exists. + + If exception(s) occur, an Error is raised with a list of reasons. + + If the optional symlinks flag is true, symbolic links in the + source tree result in symbolic links in the destination tree; if + it is false, the contents of the files pointed to by symbolic + links are copied. If the file pointed by the symlink doesn't + exist, an exception will be added in the list of errors raised in + an Error exception at the end of the copy process. + + You can set the optional ignore_dangling_symlinks flag to true if you + want to silence this exception. Notice that this has no effect on + platforms that don't support os.symlink. + + The optional ignore argument is a callable. If given, it + is called with the `src` parameter, which is the directory + being visited by copytree(), and `names` which is the list of + `src` contents, as returned by os.listdir(): + + callable(src, names) -> ignored_names + + Since copytree() is called recursively, the callable will be + called once for each directory that is copied. It returns a + list of names relative to the `src` directory that should + not be copied. + + The optional copy_function argument is a callable that will be used + to copy each file. It will be called with the source path and the + destination path as arguments. By default, copy2() is used, but any + function that supports the same signature (like copy()) can be used. + + 'b'shutil.copytree'u'shutil.copytree'b'st_file_attributes'u'st_file_attributes'b'Cannot call rmtree on a symbolic link'u'Cannot call rmtree on a symbolic link'b'Recursively delete a directory tree. + + If ignore_errors is set, errors are ignored; otherwise, if onerror + is set, it is called to handle the error with arguments (func, + path, exc_info) where func is platform and implementation dependent; + path is the argument to that function that caused it to fail; and + exc_info is a tuple returned by sys.exc_info(). If ignore_errors + is false and onerror is None, an exception is raised. + + 'u'Recursively delete a directory tree. + + If ignore_errors is set, errors are ignored; otherwise, if onerror + is set, it is called to handle the error with arguments (func, + path, exc_info) where func is platform and implementation dependent; + path is the argument to that function that caused it to fail; and + exc_info is a tuple returned by sys.exc_info(). If ignore_errors + is false and onerror is None, an exception is raised. + + 'b'shutil.rmtree'u'shutil.rmtree'b'Recursively move a file or directory to another location. This is + similar to the Unix "mv" command. Return the file or directory's + destination. + + If the destination is a directory or a symlink to a directory, the source + is moved inside the directory. The destination path must not already + exist. + + If the destination already exists but is not a directory, it may be + overwritten depending on os.rename() semantics. + + If the destination is on our current filesystem, then rename() is used. + Otherwise, src is copied to the destination and then removed. Symlinks are + recreated under the new name if os.rename() fails because of cross + filesystem renames. + + The optional `copy_function` argument is a callable that will be used + to copy the source or it will be delegated to `copytree`. + By default, copy2() is used, but any function that supports the same + signature (like copy()) can be used. + + A lot more could be done here... A look at a mv.c shows a lot of + the issues this implementation glosses over. + + 'u'Recursively move a file or directory to another location. This is + similar to the Unix "mv" command. Return the file or directory's + destination. + + If the destination is a directory or a symlink to a directory, the source + is moved inside the directory. The destination path must not already + exist. + + If the destination already exists but is not a directory, it may be + overwritten depending on os.rename() semantics. + + If the destination is on our current filesystem, then rename() is used. + Otherwise, src is copied to the destination and then removed. Symlinks are + recreated under the new name if os.rename() fails because of cross + filesystem renames. + + The optional `copy_function` argument is a callable that will be used + to copy the source or it will be delegated to `copytree`. + By default, copy2() is used, but any function that supports the same + signature (like copy()) can be used. + + A lot more could be done here... A look at a mv.c shows a lot of + the issues this implementation glosses over. + + 'b'shutil.move'u'shutil.move'b'Destination path '%s' already exists'u'Destination path '%s' already exists'b'Cannot move a directory '%s' into itself '%s'.'u'Cannot move a directory '%s' into itself '%s'.'b'Cannot move the non-empty directory '%s': Lacking write permission to '%s'.'u'Cannot move the non-empty directory '%s': Lacking write permission to '%s'.'b'Returns a gid, given a group name.'u'Returns a gid, given a group name.'b'Returns an uid, given a user name.'u'Returns an uid, given a user name.'b'Create a (possibly compressed) tar file from all the files under + 'base_dir'. + + 'compress' must be "gzip" (the default), "bzip2", "xz", or None. + + 'owner' and 'group' can be used to define an owner and a group for the + archive that is being built. If not provided, the current owner and group + will be used. + + The output tar file will be named 'base_name' + ".tar", possibly plus + the appropriate compression extension (".gz", ".bz2", or ".xz"). + + Returns the output filename. + 'u'Create a (possibly compressed) tar file from all the files under + 'base_dir'. + + 'compress' must be "gzip" (the default), "bzip2", "xz", or None. + + 'owner' and 'group' can be used to define an owner and a group for the + archive that is being built. If not provided, the current owner and group + will be used. + + The output tar file will be named 'base_name' + ".tar", possibly plus + the appropriate compression extension (".gz", ".bz2", or ".xz"). + + Returns the output filename. + 'b'gz'u'gz'b'bad value for 'compress', or compression format not supported : {0}'u'bad value for 'compress', or compression format not supported : {0}'b'Creating tar archive'u'Creating tar archive'b'w|%s'u'w|%s'b'Create a zip file from all the files under 'base_dir'. + + The output zip file will be named 'base_name' + ".zip". Returns the + name of the output zip file. + 'u'Create a zip file from all the files under 'base_dir'. + + The output zip file will be named 'base_name' + ".zip". Returns the + name of the output zip file. + 'b'creating '%s' and adding '%s' to it'u'creating '%s' and adding '%s' to it'b'adding '%s''u'adding '%s''b'uncompressed tar file'u'uncompressed tar file'b'tar'u'tar'b'gzip'ed tar-file'u'gzip'ed tar-file'b'gztar'u'gztar'b'ZIP file'u'ZIP file'b'bzip2'ed tar-file'u'bzip2'ed tar-file'b'bztar'u'bztar'b'xz'ed tar-file'u'xz'ed tar-file'b'xztar'u'xztar'b'Returns a list of supported formats for archiving and unarchiving. + + Each element of the returned sequence is a tuple (name, description) + 'u'Returns a list of supported formats for archiving and unarchiving. + + Each element of the returned sequence is a tuple (name, description) + 'b'Registers an archive format. + + name is the name of the format. function is the callable that will be + used to create archives. If provided, extra_args is a sequence of + (name, value) tuples that will be passed as arguments to the callable. + description can be provided to describe the format, and will be returned + by the get_archive_formats() function. + 'u'Registers an archive format. + + name is the name of the format. function is the callable that will be + used to create archives. If provided, extra_args is a sequence of + (name, value) tuples that will be passed as arguments to the callable. + description can be provided to describe the format, and will be returned + by the get_archive_formats() function. + 'b'The %s object is not callable'u'The %s object is not callable'b'extra_args needs to be a sequence'u'extra_args needs to be a sequence'b'extra_args elements are : (arg_name, value)'u'extra_args elements are : (arg_name, value)'b'Create an archive file (eg. zip or tar). + + 'base_name' is the name of the file to create, minus any format-specific + extension; 'format' is the archive format: one of "zip", "tar", "gztar", + "bztar", or "xztar". Or any other registered format. + + 'root_dir' is a directory that will be the root directory of the + archive; ie. we typically chdir into 'root_dir' before creating the + archive. 'base_dir' is the directory where we start archiving from; + ie. 'base_dir' will be the common prefix of all files and + directories in the archive. 'root_dir' and 'base_dir' both default + to the current directory. Returns the name of the archive file. + + 'owner' and 'group' are used when creating a tar archive. By default, + uses the current owner and group. + 'u'Create an archive file (eg. zip or tar). + + 'base_name' is the name of the file to create, minus any format-specific + extension; 'format' is the archive format: one of "zip", "tar", "gztar", + "bztar", or "xztar". Or any other registered format. + + 'root_dir' is a directory that will be the root directory of the + archive; ie. we typically chdir into 'root_dir' before creating the + archive. 'base_dir' is the directory where we start archiving from; + ie. 'base_dir' will be the common prefix of all files and + directories in the archive. 'root_dir' and 'base_dir' both default + to the current directory. Returns the name of the archive file. + + 'owner' and 'group' are used when creating a tar archive. By default, + uses the current owner and group. + 'b'shutil.make_archive'u'shutil.make_archive'b'changing into '%s''u'changing into '%s''b'dry_run'u'dry_run'b'logger'u'logger'b'unknown archive format '%s''u'unknown archive format '%s''b'owner'u'owner'b'changing back to '%s''u'changing back to '%s''b'Returns a list of supported formats for unpacking. + + Each element of the returned sequence is a tuple + (name, extensions, description) + 'u'Returns a list of supported formats for unpacking. + + Each element of the returned sequence is a tuple + (name, extensions, description) + 'b'Checks what gets registered as an unpacker.'u'Checks what gets registered as an unpacker.'b'%s is already registered for "%s"'u'%s is already registered for "%s"'b'The registered function must be a callable'u'The registered function must be a callable'b'Registers an unpack format. + + `name` is the name of the format. `extensions` is a list of extensions + corresponding to the format. + + `function` is the callable that will be + used to unpack archives. The callable will receive archives to unpack. + If it's unable to handle an archive, it needs to raise a ReadError + exception. + + If provided, `extra_args` is a sequence of + (name, value) tuples that will be passed as arguments to the callable. + description can be provided to describe the format, and will be returned + by the get_unpack_formats() function. + 'u'Registers an unpack format. + + `name` is the name of the format. `extensions` is a list of extensions + corresponding to the format. + + `function` is the callable that will be + used to unpack archives. The callable will receive archives to unpack. + If it's unable to handle an archive, it needs to raise a ReadError + exception. + + If provided, `extra_args` is a sequence of + (name, value) tuples that will be passed as arguments to the callable. + description can be provided to describe the format, and will be returned + by the get_unpack_formats() function. + 'b'Removes the pack format from the registry.'u'Removes the pack format from the registry.'b'Ensure that the parent directory of `path` exists'u'Ensure that the parent directory of `path` exists'b'Unpack zip `filename` to `extract_dir` + 'u'Unpack zip `filename` to `extract_dir` + 'b'%s is not a zip file'u'%s is not a zip file'b'Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir` + 'u'Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir` + 'b'%s is not a compressed or uncompressed tar file'u'%s is not a compressed or uncompressed tar file'b'Unpack an archive. + + `filename` is the name of the archive. + + `extract_dir` is the name of the target directory, where the archive + is unpacked. If not provided, the current working directory is used. + + `format` is the archive format: one of "zip", "tar", "gztar", "bztar", + or "xztar". Or any other registered format. If not provided, + unpack_archive will use the filename extension and see if an unpacker + was registered for that extension. + + In case none is found, a ValueError is raised. + 'u'Unpack an archive. + + `filename` is the name of the archive. + + `extract_dir` is the name of the target directory, where the archive + is unpacked. If not provided, the current working directory is used. + + `format` is the archive format: one of "zip", "tar", "gztar", "bztar", + or "xztar". Or any other registered format. If not provided, + unpack_archive will use the filename extension and see if an unpacker + was registered for that extension. + + In case none is found, a ValueError is raised. + 'b'shutil.unpack_archive'u'shutil.unpack_archive'b'Unknown unpack format '{0}''u'Unknown unpack format '{0}''b'Unknown archive format '{0}''u'Unknown archive format '{0}''b'disk_usage'u'disk_usage'b'total used free'u'total used free'b'Total space in bytes'u'Total space in bytes'b'Used space in bytes'u'Used space in bytes'b'Free space in bytes'u'Free space in bytes'b'Return disk usage statistics about the given path. + + Returned value is a named tuple with attributes 'total', 'used' and + 'free', which are the amount of total, used and free space, in bytes. + 'u'Return disk usage statistics about the given path. + + Returned value is a named tuple with attributes 'total', 'used' and + 'free', which are the amount of total, used and free space, in bytes. + 'b'Return disk usage statistics about the given path. + + Returned values is a named tuple with attributes 'total', 'used' and + 'free', which are the amount of total, used and free space, in bytes. + 'u'Return disk usage statistics about the given path. + + Returned values is a named tuple with attributes 'total', 'used' and + 'free', which are the amount of total, used and free space, in bytes. + 'b'Change owner user and group of the given path. + + user and group can be the uid/gid or the user/group names, and in that case, + they are converted to their respective uid/gid. + 'u'Change owner user and group of the given path. + + user and group can be the uid/gid or the user/group names, and in that case, + they are converted to their respective uid/gid. + 'b'shutil.chown'u'shutil.chown'b'user and/or group must be set'u'user and/or group must be set'b'no such user: {!r}'u'no such user: {!r}'b'no such group: {!r}'u'no such group: {!r}'b'Get the size of the terminal window. + + For each of the two dimensions, the environment variable, COLUMNS + and LINES respectively, is checked. If the variable is defined and + the value is a positive integer, it is used. + + When COLUMNS or LINES is not defined, which is the common case, + the terminal connected to sys.__stdout__ is queried + by invoking os.get_terminal_size. + + If the terminal size cannot be successfully queried, either because + the system doesn't support querying, or because we are not + connected to a terminal, the value given in fallback parameter + is used. Fallback defaults to (80, 24) which is the default + size used by many terminal emulators. + + The value returned is a named tuple of type os.terminal_size. + 'u'Get the size of the terminal window. + + For each of the two dimensions, the environment variable, COLUMNS + and LINES respectively, is checked. If the variable is defined and + the value is a positive integer, it is used. + + When COLUMNS or LINES is not defined, which is the common case, + the terminal connected to sys.__stdout__ is queried + by invoking os.get_terminal_size. + + If the terminal size cannot be successfully queried, either because + the system doesn't support querying, or because we are not + connected to a terminal, the value given in fallback parameter + is used. Fallback defaults to (80, 24) which is the default + size used by many terminal emulators. + + The value returned is a named tuple of type os.terminal_size. + 'b'Given a command, mode, and a PATH string, return the path which + conforms to the given mode on the PATH, or None if there is no such + file. + + `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result + of os.environ.get("PATH"), or can be overridden with a custom search + path. + + 'u'Given a command, mode, and a PATH string, return the path which + conforms to the given mode on the PATH, or None if there is no such + file. + + `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result + of os.environ.get("PATH"), or can be overridden with a custom search + path. + + 'b'CS_PATH'u'CS_PATH'b'PATHEXT'u'PATHEXT'u'shutil'_wraps_IntEnumSignalsSIG_CTRL_HandlersSigmasks_int_to_enumenum_klassConvert a numeric value to an IntEnum member. + If it's not a known member, return the numeric value itself. + _enum_to_intConvert an IntEnum member to a numeric value. + If it's not an IntEnum member return the value itself. + signalnumhowsigs_setsigsetretsigb'Signals'u'Signals'b'SIG_'u'SIG_'b'CTRL_'u'CTRL_'b'Handlers'u'Handlers'b'SIG_DFL'u'SIG_DFL'b'SIG_IGN'u'SIG_IGN'b'Sigmasks'u'Sigmasks'b'SIG_BLOCK'u'SIG_BLOCK'b'SIG_UNBLOCK'u'SIG_UNBLOCK'b'SIG_SETMASK'u'SIG_SETMASK'b'Convert a numeric value to an IntEnum member. + If it's not a known member, return the numeric value itself. + 'u'Convert a numeric value to an IntEnum member. + If it's not a known member, return the numeric value itself. + 'b'Convert an IntEnum member to a numeric value. + If it's not an IntEnum member return the value itself. + 'u'Convert an IntEnum member to a numeric value. + If it's not an IntEnum member return the value itself. + 'b'sigpending'u'sigpending'b'sigwait'u'sigwait'b'valid_signals'u'valid_signals'_InterruptHandlerdefault_handlercalledoriginal_handlerunused_signumunused_frameexpected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object"expected SIGINT signal handler to be ""signal.SIG_IGN, signal.SIG_DFL, or a ""callable object"installed_handler_results_interrupt_handler# Pretend it's signal.default_int_handler instead.# Not quite the same thing as SIG_IGN, but the closest we# can make it: do nothing.# if we aren't the installed handler, then delegate immediately# to the default handlerb'expected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object'u'expected SIGINT signal handler to be signal.SIG_IGN, signal.SIG_DFL, or a callable object'u'unittest.signals'u'signals'This module provides socket operations and some related functions. +On Unix, it supports IP (Internet Protocol) and Unix domain sockets. +On other systems, it only supports IP. Functions specific for a +socket are available as methods of the socket object. + +Functions: + +socket() -- create a new socket object +socketpair() -- create a pair of new socket objects [*] +fromfd() -- create a socket object from an open file descriptor [*] +fromshare() -- create a socket object from data received from socket.share() [*] +gethostname() -- return the current hostname +gethostbyname() -- map a hostname to its IP number +gethostbyaddr() -- map an IP number or hostname to DNS info +getservbyname() -- map a service name and a protocol name to a port number +getprotobyname() -- map a protocol name (e.g. 'tcp') to a number +ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order +htons(), htonl() -- convert 16, 32 bit int from host to network byte order +inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format +inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) +socket.getdefaulttimeout() -- get the default timeout value +socket.setdefaulttimeout() -- set the default timeout value +create_connection() -- connects to an address, with an optional timeout and + optional source address. + + [*] not available on all platforms! + +Special objects: + +SocketType -- type object for socket objects +error -- exception raised for I/O errors +has_ipv6 -- boolean value indicating if IPv6 is supported + +IntEnum constants: + +AF_INET, AF_UNIX -- socket domains (first argument to socket() call) +SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) + +Integer constants: + +Many other constants may be defined; these may be used in calls to +the setsockopt() and getsockopt() methods. +has_dualstack_ipv6AddressFamilySocketKindAF_SOCK_MsgFlagMSG_AddressInfoAI__LOCALHOST_LOCALHOST_V6_intenum_converterConvert a numeric family value to an IntEnum member. + + If it's not a known member, return the numeric value itself. + _realsocketerrorTabSpecified event object handle is invalid.Insufficient memory available.One or more parameters are invalid.Overlapped operation aborted.995Overlapped I/O event object not in signaled state.996Overlapped operation will complete later.997The operation was interrupted.10004A bad file handle was passed.10009Permission denied.10013A fault occurred on the network??10014An invalid operation was attempted.10022Too many open files.10024The socket operation would block10035A blocking operation is already in progress.10036Operation already in progress.10037Socket operation on nonsocket.10038Destination address required.10039Message too long.10040Protocol wrong type for socket.10041Bad protocol option.10042Protocol not supported.10043Socket type not supported.10044Operation not supported.10045Protocol family not supported.10046Address family not supported by protocol family.10047The network address is in use.10048Cannot assign requested address.10049Network is down.10050Network is unreachable.10051Network dropped connection on reset.10052Software caused connection abort.10053The connection has been reset.10054No buffer space available.10055Socket is already connected.10056Socket is not connected.10057The network has been shut down.10058Too many references.10059The operation timed out.10060Connection refused.10061Cannot translate name.10062The name is too long.10063The host is down.10064The host is unreachable.10065Directory not empty.10066Too many processes.10067User quota exceeded.10068Disk quota exceeded.10069Stale file handle reference.10070Item is remote.10071Network subsystem is unavailable.10091Winsock.dll version out of range.10092Successful WSAStartup not yet performed.10093Graceful shutdown in progress.10101No more results from WSALookupServiceNext.10102Call has been canceled.10103Procedure call table is invalid.10104Service provider is invalid.10105Service provider failed to initialize.10106System call failure.10107Service not found.10108Class type not found.1010910110Call was canceled.10111Database query was refused.10112Host not found.11001Nonauthoritative host not found.11002This is a nonrecoverable error.11003Valid name, no data record requested type.QoS receivers.11005QoS senders.11006No QoS senders.11007QoS no receivers.11008QoS request confirmed.11009QoS admission error.11010QoS policy failure.11011QoS bad style.11012QoS bad object.11013QoS traffic control error.11014QoS generic error.11015QoS service type error.11016QoS flowspec error.11017Invalid QoS provider buffer.11018Invalid QoS filter style.1101911020Incorrect QoS filter count.11021Invalid QoS object length.11022Incorrect QoS flow count.11023Unrecognized QoS object.11024Invalid QoS policy object.11025Invalid QoS flow descriptor.11026Invalid QoS provider-specific flowspec.11027Invalid QoS provider-specific filterspec.11028Invalid QoS shape discard mode object.11029Invalid QoS shaping rate object.11030Reserved policy QoS element type.11031_GiveupOnSendfileA subclass of _socket.socket adding the makefile() method._io_refsWrap __repr__() to reveal the real class name and socket + address(es). + <%s.%s%s fd=%i, family=%s, type=%s, proto=%i [closed], laddr=%sraddr, raddr=%sdup() -> socket object + + Duplicate the socket. Return a new socket object connected to the same + system resource. The new socket is non-inheritable. + accept() -> (socket object, address info) + + Wait for an incoming connection. Return a new socket + representing the connection, and the address of the client. + For IP sockets, the address info is a pair (hostaddr, port). + makefile(...) -> an I/O stream connected to the socket + + The arguments are as for io.open() after the filename, except the only + supported mode values are 'r' (default), 'w' and 'b'. + invalid mode %r (only r, w, b allowed)readingrawmodeSocketIOunbuffered streams must be binary_sendfile_use_sendfilesocknonon-blocking sockets are not supportedselector_selectos_sendfiletimed outos.sendfile() not available on this platform_sendfile_use_sendsock_sendsendfile(file[, offset[, count]]) -> sent + + Send a file until EOF is reached by using high-performance + os.sendfile() and return the total number of bytes which + were sent. + *file* must be a regular file object opened in binary mode. + If os.sendfile() is not available (e.g. Windows) or file is + not a regular file socket.send() will be used instead. + *offset* tells from where to start reading the file. + If specified, *count* is the total number of bytes to transmit + as opposed to sending the file until EOF is reached. + File position is updated on return or also in case of error in + which case file.tell() can be used to figure out the number of + bytes which were sent. + The socket must be of SOCK_STREAM type. + Non-blocking sockets are not supported. + _decref_socketios_real_close_ssdetach() -> file descriptor + + Close the socket object without closing the underlying file descriptor. + The object cannot be used after this call, but the file descriptor + can be reused for other purposes. The file descriptor is returned. + Read-only access to the address family for this socket. + Read-only access to the socket type. + get_handle_inheritableset_handle_inheritableGet the inheritable flag of the socketSet the inheritable flag of the socket fromfd(fd, family, type[, proto]) -> socket object + + Create a socket object from a duplicate of the given file + descriptor. The remaining arguments are the same as for socket(). + nfd fromshare(info) -> socket object + + Create a socket object from the bytes object returned by + socket.share(pid). + socketpair([family[, type[, proto]]]) -> (socket object, socket object) + + Create a pair of socket objects from the sockets returned by the platform + socketpair() function. + The arguments are the same as for socket() except the default family is + AF_UNIX if defined on the platform; otherwise, the default is AF_INET. + Only AF_INET and AF_INET6 socket address families are supported"Only AF_INET and AF_INET6 socket address families ""are supported"Only SOCK_STREAM socket type is supportedOnly protocol zero is supportedlsockssocksocketpair([family[, type[, proto]]]) -> (socket object, socket object) +Create a pair of socket objects from the sockets returned by the platform +socketpair() function. +The arguments are the same as for socket() except the default family is AF_UNIX +if defined on the platform; otherwise, the default is AF_INET. +_blocking_errnosRaw I/O implementation for stream sockets. + + This class supports the makefile() method on sockets. It provides + the raw I/O interface on top of a socket object. + invalid mode: %r_reading_writing_timeout_occurredRead up to len(b) bytes into the writable buffer *b* and return + the number of bytes read. If the socket is non-blocking and no bytes + are available, None is returned. + + If *b* is non-empty, a 0 return value indicates that the connection + was shutdown at the other end. + cannot read from timed out objectWrite the given bytes or bytearray object *b* to the socket + and return the number of bytes written. This can be less than + len(b) if not all data could be written. If the socket is + non-blocking and no bytes could be written None is returned. + True if the SocketIO is open for reading. + I/O operation on closed socket.True if the SocketIO is open for writing. + True if the SocketIO is open for seeking. + Return the file descriptor of the underlying socket. + Close the SocketIO object. This doesn't close the underlying + socket, except if all references to it have disappeared. + Get fully qualified domain name from name. + + An empty argument is interpreted as meaning the local host. + + First the hostname returned by gethostbyaddr() is checked, then + possibly existing aliases. In case no FQDN is available, hostname + from gethostname() is returned. + 0.0.0.0ipaddrsConnect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + A host of '' or port 0 tells the OS to use the default. + Return True if the platform supports creating a SOCK_STREAM socket + which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections. + dualstack_ipv6Convenience function which creates a SOCK_STREAM type socket + bound to *address* (a 2-tuple (host, port)) and return the socket + object. + + *family* should be either AF_INET or AF_INET6. + *backlog* is the queue size passed to socket.listen(). + *reuse_port* dictates whether to use the SO_REUSEPORT socket option. + *dualstack_ipv6*: if true and the platform supports it, it will + create an AF_INET6 socket able to accept both IPv4 or IPv6 + connections. When false it will explicitly disable this option on + platforms that enable it by default (e.g. Linux). + + >>> with create_server(('', 8000)) as server: + ... while True: + ... conn, addr = server.accept() + ... # handle new connection + SO_REUSEPORT not supported on this platformdualstack_ipv6 not supported on this platformdualstack_ipv6 requires AF_INET6 family%s (while attempting to bind on address %r)Resolve host and port into list of address info entries. + + Translate the host/port argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + host is a domain name, a string representation of an IPv4/v6 address or + None. port is a string service name such as 'http', a numeric port number or + None. By passing None as the value of host and port, you can pass NULL to + the underlying C API. + + The family, type and proto arguments can be optionally specified in order to + narrow the list of addresses returned. Passing zero as a value for each of + these arguments selects the full range of results. + addrlist# Wrapper module for _socket, providing some additional facilities# implemented in Python.# Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for# nicer string representations.# Note that _socket only knows about the integer values. The public interface# in this module understands the enums and translates them back from integers# where needed (e.g. .family property of a socket object).# WSA error codes# WSAEFAULT# For user code address family and type values are IntEnum members, but# for the underlying _socket.socket they're just integers. The# constructor of _socket.socket converts the given argument to an# integer automatically.# Issue #7995: if no default timeout is set and the listening# socket had a (non-zero) timeout, force the new socket in blocking# mode to override platform-specific socket flags inheritance.# XXX refactor to share code?# Truncate to 1GiB to avoid OverflowError, see bpo-38319.# poll/select have the advantage of not requiring any# extra file descriptor, contrarily to epoll/kqueue# (also, they require a single syscall).# localize variable access to minimize overhead# Block until the socket is ready to send some# data; avoids hogging CPU resources.# We can get here for different reasons, the main# one being 'file' is not a regular mmap(2)-like# file, in which case we'll fall back on using# plain send().# This function should not reference any globals. See issue #808164.# Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain.# We create a connected TCP socket. Note the trick with# setblocking(False) that prevents us from having to create a thread.# On IPv6, ignore flow_info and scope_id# One might wonder why not let FileIO do the job instead. There are two# main reasons why FileIO is not adapted:# - it wouldn't work under Windows (where you can't used read() and# write() on a socket handle)# - it wouldn't work with socket timeouts (FileIO would ignore the# timeout and consider the socket non-blocking)# XXX More docs# XXX what about EINTR?# Break explicitly a reference cycle# Note about Windows. We don't set SO_REUSEADDR because:# 1) It's unnecessary: bind() will succeed even in case of a# previous closed socket on the same address and still in# TIME_WAIT state.# 2) If set, another socket is free to bind() on the same# address, effectively preventing this one from accepting# connections. Also, it may set the process in a state where# it'll no longer respond to any signals or graceful kills.# See: msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx# Fail later on bind(), for platforms which may not# support this option.# We override this function since we want to translate the numeric family# and socket type values to enum constants.b'This module provides socket operations and some related functions. +On Unix, it supports IP (Internet Protocol) and Unix domain sockets. +On other systems, it only supports IP. Functions specific for a +socket are available as methods of the socket object. + +Functions: + +socket() -- create a new socket object +socketpair() -- create a pair of new socket objects [*] +fromfd() -- create a socket object from an open file descriptor [*] +fromshare() -- create a socket object from data received from socket.share() [*] +gethostname() -- return the current hostname +gethostbyname() -- map a hostname to its IP number +gethostbyaddr() -- map an IP number or hostname to DNS info +getservbyname() -- map a service name and a protocol name to a port number +getprotobyname() -- map a protocol name (e.g. 'tcp') to a number +ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order +htons(), htonl() -- convert 16, 32 bit int from host to network byte order +inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format +inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) +socket.getdefaulttimeout() -- get the default timeout value +socket.setdefaulttimeout() -- set the default timeout value +create_connection() -- connects to an address, with an optional timeout and + optional source address. + + [*] not available on all platforms! + +Special objects: + +SocketType -- type object for socket objects +error -- exception raised for I/O errors +has_ipv6 -- boolean value indicating if IPv6 is supported + +IntEnum constants: + +AF_INET, AF_UNIX -- socket domains (first argument to socket() call) +SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) + +Integer constants: + +Many other constants may be defined; these may be used in calls to +the setsockopt() and getsockopt() methods. +'u'This module provides socket operations and some related functions. +On Unix, it supports IP (Internet Protocol) and Unix domain sockets. +On other systems, it only supports IP. Functions specific for a +socket are available as methods of the socket object. + +Functions: + +socket() -- create a new socket object +socketpair() -- create a pair of new socket objects [*] +fromfd() -- create a socket object from an open file descriptor [*] +fromshare() -- create a socket object from data received from socket.share() [*] +gethostname() -- return the current hostname +gethostbyname() -- map a hostname to its IP number +gethostbyaddr() -- map an IP number or hostname to DNS info +getservbyname() -- map a service name and a protocol name to a port number +getprotobyname() -- map a protocol name (e.g. 'tcp') to a number +ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order +htons(), htonl() -- convert 16, 32 bit int from host to network byte order +inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format +inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) +socket.getdefaulttimeout() -- get the default timeout value +socket.setdefaulttimeout() -- set the default timeout value +create_connection() -- connects to an address, with an optional timeout and + optional source address. + + [*] not available on all platforms! + +Special objects: + +SocketType -- type object for socket objects +error -- exception raised for I/O errors +has_ipv6 -- boolean value indicating if IPv6 is supported + +IntEnum constants: + +AF_INET, AF_UNIX -- socket domains (first argument to socket() call) +SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) + +Integer constants: + +Many other constants may be defined; these may be used in calls to +the setsockopt() and getsockopt() methods. +'b'EBADF'u'EBADF'b'EAGAIN'u'EAGAIN'b'EWOULDBLOCK'u'EWOULDBLOCK'b'getfqdn'u'getfqdn'b'create_connection'u'create_connection'b'create_server'u'create_server'b'has_dualstack_ipv6'u'has_dualstack_ipv6'b'AddressFamily'u'AddressFamily'b'SocketKind'u'SocketKind'b'AF_'u'AF_'b'SOCK_'u'SOCK_'b'MsgFlag'u'MsgFlag'b'MSG_'u'MSG_'b'AddressInfo'u'AddressInfo'b'AI_'u'AI_'b'Convert a numeric family value to an IntEnum member. + + If it's not a known member, return the numeric value itself. + 'u'Convert a numeric family value to an IntEnum member. + + If it's not a known member, return the numeric value itself. + 'b'Specified event object handle is invalid.'u'Specified event object handle is invalid.'b'Insufficient memory available.'u'Insufficient memory available.'b'One or more parameters are invalid.'u'One or more parameters are invalid.'b'Overlapped operation aborted.'u'Overlapped operation aborted.'b'Overlapped I/O event object not in signaled state.'u'Overlapped I/O event object not in signaled state.'b'Overlapped operation will complete later.'u'Overlapped operation will complete later.'b'The operation was interrupted.'u'The operation was interrupted.'b'A bad file handle was passed.'u'A bad file handle was passed.'b'Permission denied.'u'Permission denied.'b'A fault occurred on the network??'u'A fault occurred on the network??'b'An invalid operation was attempted.'u'An invalid operation was attempted.'b'Too many open files.'u'Too many open files.'b'The socket operation would block'u'The socket operation would block'b'A blocking operation is already in progress.'u'A blocking operation is already in progress.'b'Operation already in progress.'u'Operation already in progress.'b'Socket operation on nonsocket.'u'Socket operation on nonsocket.'b'Destination address required.'u'Destination address required.'b'Message too long.'u'Message too long.'b'Protocol wrong type for socket.'u'Protocol wrong type for socket.'b'Bad protocol option.'u'Bad protocol option.'b'Protocol not supported.'u'Protocol not supported.'b'Socket type not supported.'u'Socket type not supported.'b'Operation not supported.'u'Operation not supported.'b'Protocol family not supported.'u'Protocol family not supported.'b'Address family not supported by protocol family.'u'Address family not supported by protocol family.'b'The network address is in use.'u'The network address is in use.'b'Cannot assign requested address.'u'Cannot assign requested address.'b'Network is down.'u'Network is down.'b'Network is unreachable.'u'Network is unreachable.'b'Network dropped connection on reset.'u'Network dropped connection on reset.'b'Software caused connection abort.'u'Software caused connection abort.'b'The connection has been reset.'u'The connection has been reset.'b'No buffer space available.'u'No buffer space available.'b'Socket is already connected.'u'Socket is already connected.'b'Socket is not connected.'u'Socket is not connected.'b'The network has been shut down.'u'The network has been shut down.'b'Too many references.'u'Too many references.'b'The operation timed out.'u'The operation timed out.'b'Connection refused.'b'Cannot translate name.'u'Cannot translate name.'b'The name is too long.'u'The name is too long.'b'The host is down.'u'The host is down.'b'The host is unreachable.'u'The host is unreachable.'b'Directory not empty.'u'Directory not empty.'b'Too many processes.'u'Too many processes.'b'User quota exceeded.'u'User quota exceeded.'b'Disk quota exceeded.'u'Disk quota exceeded.'b'Stale file handle reference.'u'Stale file handle reference.'b'Item is remote.'u'Item is remote.'b'Network subsystem is unavailable.'u'Network subsystem is unavailable.'b'Winsock.dll version out of range.'u'Winsock.dll version out of range.'b'Successful WSAStartup not yet performed.'u'Successful WSAStartup not yet performed.'b'Graceful shutdown in progress.'u'Graceful shutdown in progress.'b'No more results from WSALookupServiceNext.'u'No more results from WSALookupServiceNext.'b'Call has been canceled.'u'Call has been canceled.'b'Procedure call table is invalid.'u'Procedure call table is invalid.'b'Service provider is invalid.'u'Service provider is invalid.'b'Service provider failed to initialize.'u'Service provider failed to initialize.'b'System call failure.'u'System call failure.'b'Service not found.'u'Service not found.'b'Class type not found.'u'Class type not found.'b'Call was canceled.'u'Call was canceled.'b'Database query was refused.'u'Database query was refused.'b'Host not found.'u'Host not found.'b'Nonauthoritative host not found.'u'Nonauthoritative host not found.'b'This is a nonrecoverable error.'u'This is a nonrecoverable error.'b'Valid name, no data record requested type.'u'Valid name, no data record requested type.'b'QoS receivers.'u'QoS receivers.'b'QoS senders.'u'QoS senders.'b'No QoS senders.'u'No QoS senders.'b'QoS no receivers.'u'QoS no receivers.'b'QoS request confirmed.'u'QoS request confirmed.'b'QoS admission error.'u'QoS admission error.'b'QoS policy failure.'u'QoS policy failure.'b'QoS bad style.'u'QoS bad style.'b'QoS bad object.'u'QoS bad object.'b'QoS traffic control error.'u'QoS traffic control error.'b'QoS generic error.'u'QoS generic error.'b'QoS service type error.'u'QoS service type error.'b'QoS flowspec error.'u'QoS flowspec error.'b'Invalid QoS provider buffer.'u'Invalid QoS provider buffer.'b'Invalid QoS filter style.'u'Invalid QoS filter style.'b'Incorrect QoS filter count.'u'Incorrect QoS filter count.'b'Invalid QoS object length.'u'Invalid QoS object length.'b'Incorrect QoS flow count.'u'Incorrect QoS flow count.'b'Unrecognized QoS object.'u'Unrecognized QoS object.'b'Invalid QoS policy object.'u'Invalid QoS policy object.'b'Invalid QoS flow descriptor.'u'Invalid QoS flow descriptor.'b'Invalid QoS provider-specific flowspec.'u'Invalid QoS provider-specific flowspec.'b'Invalid QoS provider-specific filterspec.'u'Invalid QoS provider-specific filterspec.'b'Invalid QoS shape discard mode object.'u'Invalid QoS shape discard mode object.'b'Invalid QoS shaping rate object.'u'Invalid QoS shaping rate object.'b'Reserved policy QoS element type.'u'Reserved policy QoS element type.'b'errorTab'u'errorTab'b'A subclass of _socket.socket adding the makefile() method.'u'A subclass of _socket.socket adding the makefile() method.'b'_io_refs'u'_io_refs'b'_closed'u'_closed'b'Wrap __repr__() to reveal the real class name and socket + address(es). + 'u'Wrap __repr__() to reveal the real class name and socket + address(es). + 'b'<%s.%s%s fd=%i, family=%s, type=%s, proto=%i'u'<%s.%s%s fd=%i, family=%s, type=%s, proto=%i'b' [closed]'u' [closed]'b', laddr=%s'u', laddr=%s'b', raddr=%s'u', raddr=%s'b'dup() -> socket object + + Duplicate the socket. Return a new socket object connected to the same + system resource. The new socket is non-inheritable. + 'u'dup() -> socket object + + Duplicate the socket. Return a new socket object connected to the same + system resource. The new socket is non-inheritable. + 'b'accept() -> (socket object, address info) + + Wait for an incoming connection. Return a new socket + representing the connection, and the address of the client. + For IP sockets, the address info is a pair (hostaddr, port). + 'u'accept() -> (socket object, address info) + + Wait for an incoming connection. Return a new socket + representing the connection, and the address of the client. + For IP sockets, the address info is a pair (hostaddr, port). + 'b'makefile(...) -> an I/O stream connected to the socket + + The arguments are as for io.open() after the filename, except the only + supported mode values are 'r' (default), 'w' and 'b'. + 'u'makefile(...) -> an I/O stream connected to the socket + + The arguments are as for io.open() after the filename, except the only + supported mode values are 'r' (default), 'w' and 'b'. + 'b'invalid mode %r (only r, w, b allowed)'u'invalid mode %r (only r, w, b allowed)'b'unbuffered streams must be binary'u'unbuffered streams must be binary'b'non-blocking sockets are not supported'u'non-blocking sockets are not supported'b'timed out'u'timed out'b'os.sendfile() not available on this platform'u'os.sendfile() not available on this platform'b'sendfile(file[, offset[, count]]) -> sent + + Send a file until EOF is reached by using high-performance + os.sendfile() and return the total number of bytes which + were sent. + *file* must be a regular file object opened in binary mode. + If os.sendfile() is not available (e.g. Windows) or file is + not a regular file socket.send() will be used instead. + *offset* tells from where to start reading the file. + If specified, *count* is the total number of bytes to transmit + as opposed to sending the file until EOF is reached. + File position is updated on return or also in case of error in + which case file.tell() can be used to figure out the number of + bytes which were sent. + The socket must be of SOCK_STREAM type. + Non-blocking sockets are not supported. + 'u'sendfile(file[, offset[, count]]) -> sent + + Send a file until EOF is reached by using high-performance + os.sendfile() and return the total number of bytes which + were sent. + *file* must be a regular file object opened in binary mode. + If os.sendfile() is not available (e.g. Windows) or file is + not a regular file socket.send() will be used instead. + *offset* tells from where to start reading the file. + If specified, *count* is the total number of bytes to transmit + as opposed to sending the file until EOF is reached. + File position is updated on return or also in case of error in + which case file.tell() can be used to figure out the number of + bytes which were sent. + The socket must be of SOCK_STREAM type. + Non-blocking sockets are not supported. + 'b'detach() -> file descriptor + + Close the socket object without closing the underlying file descriptor. + The object cannot be used after this call, but the file descriptor + can be reused for other purposes. The file descriptor is returned. + 'u'detach() -> file descriptor + + Close the socket object without closing the underlying file descriptor. + The object cannot be used after this call, but the file descriptor + can be reused for other purposes. The file descriptor is returned. + 'b'Read-only access to the address family for this socket. + 'u'Read-only access to the address family for this socket. + 'b'Read-only access to the socket type. + 'u'Read-only access to the socket type. + 'b'Get the inheritable flag of the socket'u'Get the inheritable flag of the socket'b'Set the inheritable flag of the socket'u'Set the inheritable flag of the socket'b' fromfd(fd, family, type[, proto]) -> socket object + + Create a socket object from a duplicate of the given file + descriptor. The remaining arguments are the same as for socket(). + 'u' fromfd(fd, family, type[, proto]) -> socket object + + Create a socket object from a duplicate of the given file + descriptor. The remaining arguments are the same as for socket(). + 'b' fromshare(info) -> socket object + + Create a socket object from the bytes object returned by + socket.share(pid). + 'u' fromshare(info) -> socket object + + Create a socket object from the bytes object returned by + socket.share(pid). + 'b'fromshare'u'fromshare'b'socketpair'u'socketpair'b'socketpair([family[, type[, proto]]]) -> (socket object, socket object) + + Create a pair of socket objects from the sockets returned by the platform + socketpair() function. + The arguments are the same as for socket() except the default family is + AF_UNIX if defined on the platform; otherwise, the default is AF_INET. + 'u'socketpair([family[, type[, proto]]]) -> (socket object, socket object) + + Create a pair of socket objects from the sockets returned by the platform + socketpair() function. + The arguments are the same as for socket() except the default family is + AF_UNIX if defined on the platform; otherwise, the default is AF_INET. + 'b'Only AF_INET and AF_INET6 socket address families are supported'u'Only AF_INET and AF_INET6 socket address families are supported'b'Only SOCK_STREAM socket type is supported'u'Only SOCK_STREAM socket type is supported'b'Only protocol zero is supported'u'Only protocol zero is supported'b'socketpair([family[, type[, proto]]]) -> (socket object, socket object) +Create a pair of socket objects from the sockets returned by the platform +socketpair() function. +The arguments are the same as for socket() except the default family is AF_UNIX +if defined on the platform; otherwise, the default is AF_INET. +'u'socketpair([family[, type[, proto]]]) -> (socket object, socket object) +Create a pair of socket objects from the sockets returned by the platform +socketpair() function. +The arguments are the same as for socket() except the default family is AF_UNIX +if defined on the platform; otherwise, the default is AF_INET. +'b'Raw I/O implementation for stream sockets. + + This class supports the makefile() method on sockets. It provides + the raw I/O interface on top of a socket object. + 'u'Raw I/O implementation for stream sockets. + + This class supports the makefile() method on sockets. It provides + the raw I/O interface on top of a socket object. + 'b'invalid mode: %r'u'invalid mode: %r'b'Read up to len(b) bytes into the writable buffer *b* and return + the number of bytes read. If the socket is non-blocking and no bytes + are available, None is returned. + + If *b* is non-empty, a 0 return value indicates that the connection + was shutdown at the other end. + 'u'Read up to len(b) bytes into the writable buffer *b* and return + the number of bytes read. If the socket is non-blocking and no bytes + are available, None is returned. + + If *b* is non-empty, a 0 return value indicates that the connection + was shutdown at the other end. + 'b'cannot read from timed out object'u'cannot read from timed out object'b'Write the given bytes or bytearray object *b* to the socket + and return the number of bytes written. This can be less than + len(b) if not all data could be written. If the socket is + non-blocking and no bytes could be written None is returned. + 'u'Write the given bytes or bytearray object *b* to the socket + and return the number of bytes written. This can be less than + len(b) if not all data could be written. If the socket is + non-blocking and no bytes could be written None is returned. + 'b'True if the SocketIO is open for reading. + 'u'True if the SocketIO is open for reading. + 'b'I/O operation on closed socket.'u'I/O operation on closed socket.'b'True if the SocketIO is open for writing. + 'u'True if the SocketIO is open for writing. + 'b'True if the SocketIO is open for seeking. + 'u'True if the SocketIO is open for seeking. + 'b'Return the file descriptor of the underlying socket. + 'u'Return the file descriptor of the underlying socket. + 'b'Close the SocketIO object. This doesn't close the underlying + socket, except if all references to it have disappeared. + 'u'Close the SocketIO object. This doesn't close the underlying + socket, except if all references to it have disappeared. + 'b'Get fully qualified domain name from name. + + An empty argument is interpreted as meaning the local host. + + First the hostname returned by gethostbyaddr() is checked, then + possibly existing aliases. In case no FQDN is available, hostname + from gethostname() is returned. + 'u'Get fully qualified domain name from name. + + An empty argument is interpreted as meaning the local host. + + First the hostname returned by gethostbyaddr() is checked, then + possibly existing aliases. In case no FQDN is available, hostname + from gethostname() is returned. + 'b'0.0.0.0'u'0.0.0.0'b'Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + A host of '' or port 0 tells the OS to use the default. + 'u'Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + A host of '' or port 0 tells the OS to use the default. + 'b'Return True if the platform supports creating a SOCK_STREAM socket + which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections. + 'u'Return True if the platform supports creating a SOCK_STREAM socket + which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections. + 'b'IPV6_V6ONLY'u'IPV6_V6ONLY'b'Convenience function which creates a SOCK_STREAM type socket + bound to *address* (a 2-tuple (host, port)) and return the socket + object. + + *family* should be either AF_INET or AF_INET6. + *backlog* is the queue size passed to socket.listen(). + *reuse_port* dictates whether to use the SO_REUSEPORT socket option. + *dualstack_ipv6*: if true and the platform supports it, it will + create an AF_INET6 socket able to accept both IPv4 or IPv6 + connections. When false it will explicitly disable this option on + platforms that enable it by default (e.g. Linux). + + >>> with create_server(('', 8000)) as server: + ... while True: + ... conn, addr = server.accept() + ... # handle new connection + 'u'Convenience function which creates a SOCK_STREAM type socket + bound to *address* (a 2-tuple (host, port)) and return the socket + object. + + *family* should be either AF_INET or AF_INET6. + *backlog* is the queue size passed to socket.listen(). + *reuse_port* dictates whether to use the SO_REUSEPORT socket option. + *dualstack_ipv6*: if true and the platform supports it, it will + create an AF_INET6 socket able to accept both IPv4 or IPv6 + connections. When false it will explicitly disable this option on + platforms that enable it by default (e.g. Linux). + + >>> with create_server(('', 8000)) as server: + ... while True: + ... conn, addr = server.accept() + ... # handle new connection + 'b'SO_REUSEPORT not supported on this platform'u'SO_REUSEPORT not supported on this platform'b'dualstack_ipv6 not supported on this platform'u'dualstack_ipv6 not supported on this platform'b'dualstack_ipv6 requires AF_INET6 family'u'dualstack_ipv6 requires AF_INET6 family'b'%s (while attempting to bind on address %r)'u'%s (while attempting to bind on address %r)'b'Resolve host and port into list of address info entries. + + Translate the host/port argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + host is a domain name, a string representation of an IPv4/v6 address or + None. port is a string service name such as 'http', a numeric port number or + None. By passing None as the value of host and port, you can pass NULL to + the underlying C API. + + The family, type and proto arguments can be optionally specified in order to + narrow the list of addresses returned. Passing zero as a value for each of + these arguments selects the full range of results. + 'u'Resolve host and port into list of address info entries. + + Translate the host/port argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + host is a domain name, a string representation of an IPv4/v6 address or + None. port is a string service name such as 'http', a numeric port number or + None. By passing None as the value of host and port, you can pass NULL to + the underlying C API. + + The family, type and proto arguments can be optionally specified in order to + narrow the list of addresses returned. Passing zero as a value for each of + these arguments selects the full range of results. + 'Generic socket server classes. + +This module tries to capture the various aspects of defining a server: + +For socket-based servers: + +- address family: + - AF_INET{,6}: IP (Internet Protocol) sockets (default) + - AF_UNIX: Unix domain sockets + - others, e.g. AF_DECNET are conceivable (see +- socket type: + - SOCK_STREAM (reliable stream, e.g. TCP) + - SOCK_DGRAM (datagrams, e.g. UDP) + +For request-based servers (including socket-based): + +- client address verification before further looking at the request + (This is actually a hook for any processing that needs to look + at the request before anything else, e.g. logging) +- how to handle multiple requests: + - synchronous (one request is handled at a time) + - forking (each request is handled by a new process) + - threading (each request is handled by a new thread) + +The classes in this module favor the server type that is simplest to +write: a synchronous TCP/IP server. This is bad class design, but +saves some typing. (There's also the issue that a deep class hierarchy +slows down method lookups.) + +There are five classes in an inheritance diagram, four of which represent +synchronous servers of four types: + + +------------+ + | BaseServer | + +------------+ + | + v + +-----------+ +------------------+ + | TCPServer |------->| UnixStreamServer | + +-----------+ +------------------+ + | + v + +-----------+ +--------------------+ + | UDPServer |------->| UnixDatagramServer | + +-----------+ +--------------------+ + +Note that UnixDatagramServer derives from UDPServer, not from +UnixStreamServer -- the only difference between an IP and a Unix +stream server is the address family, which is simply repeated in both +unix server classes. + +Forking and threading versions of each type of server can be created +using the ForkingMixIn and ThreadingMixIn mix-in classes. For +instance, a threading UDP server class is created as follows: + + class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass + +The Mix-in class must come first, since it overrides a method defined +in UDPServer! Setting the various member variables also changes +the behavior of the underlying server mechanism. + +To implement a service, you must derive a class from +BaseRequestHandler and redefine its handle() method. You can then run +various versions of the service by combining one of the server classes +with your request handler class. + +The request handler class must be different for datagram or stream +services. This can be hidden by using the request handler +subclasses StreamRequestHandler or DatagramRequestHandler. + +Of course, you still have to use your head! + +For instance, it makes no sense to use a forking server if the service +contains state in memory that can be modified by requests (since the +modifications in the child process would never reach the initial state +kept in the parent process and passed to each child). In this case, +you can use a threading server, but you will probably have to use +locks to avoid two requests that come in nearly simultaneous to apply +conflicting changes to the server state. + +On the other hand, if you are building e.g. an HTTP server, where all +data is stored externally (e.g. in the file system), a synchronous +class will essentially render the service "deaf" while one request is +being handled -- which may be for a very long time if a client is slow +to read all the data it has requested. Here a threading or forking +server is appropriate. + +In some cases, it may be appropriate to process part of a request +synchronously, but to finish processing in a forked child depending on +the request data. This can be implemented by using a synchronous +server and doing an explicit fork in the request handler class +handle() method. + +Another approach to handling multiple simultaneous requests in an +environment that supports neither threads nor fork (or where these are +too expensive or inappropriate for the service) is to maintain an +explicit table of partially finished requests and to use a selector to +decide which request to work on next (or whether to handle a new +incoming request). This is particularly important for stream services +where each client can potentially be connected for a long time (if +threads or subprocesses cannot be used). + +Future work: +- Standard classes for Sun RPC (which uses either UDP or TCP) +- Standard mix-in classes to implement various authentication + and encryption schemes + +XXX Open problems: +- What to do with out-of-band data? + +BaseServer: +- split generic "request" functionality out into BaseServer class. + Copyright (C) 2000 Luke Kenneth Casson Leighton + + example: read entries from a SQL database (requires overriding + get_request() to return a table entry from the database). + entry is processed by a RequestHandlerClass. + +0.4BaseServerUDPServerThreadingUDPServerThreadingTCPServerBaseRequestHandlerDatagramRequestHandlerForkingUDPServerForkingTCPServerForkingMixInUnixStreamServerUnixDatagramServerThreadingUnixStreamServerThreadingUnixDatagramServer_ServerSelectorBase class for server classes. + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass) + - serve_forever(poll_interval=0.5) + - shutdown() + - handle_request() # if you do not use serve_forever() + - fileno() -> int # for selector + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - handle_timeout() + - verify_request(request, client_address) + - server_close() + - process_request(request, client_address) + - shutdown_request(request) + - close_request(request) + - service_actions() + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - timeout + - address_family + - socket_type + - allow_reuse_address + + Instance variables: + + - RequestHandlerClass + - socket + + RequestHandlerClassConstructor. May be extended, do not override.__is_shut_down__shutdown_requestCalled by constructor to activate the server. + + May be overridden. + + poll_intervalHandle one request at a time until shutdown. + + Polls for shutdown every poll_interval seconds. Ignores + self.timeout. If you need to do periodic tasks, do them in + another thread. + _handle_request_noblockservice_actionsStops the serve_forever loop. + + Blocks until the loop has finished. This must be called while + serve_forever() is running in another thread, or it will + deadlock. + Called by the serve_forever() loop. + + May be overridden by a subclass / Mixin to implement any code that + needs to be run during the loop. + Handle one request, possibly blocking. + + Respects self.timeout. + handle_timeoutHandle one request, without blocking. + + I assume that selector.select() has returned that the socket is + readable before this function was called, so there should be no risk of + blocking in get_request(). + get_requestverify_requestshutdown_requestCalled if no new request arrives within self.timeout. + + Overridden by ForkingMixIn. + Verify the request. May be overridden. + + Return True if we should proceed with this request. + + Call finish_request. + + Overridden by ForkingMixIn and ThreadingMixIn. + + finish_requestCalled to clean-up the server. + + May be overridden. + + Finish one request by instantiating RequestHandlerClass.Called to shutdown and close an individual request.close_requestCalled to clean up an individual request.Handle an error gracefully. May be overridden. + + The default is to print a traceback and continue. + + Exception happened during processing of request fromBase class for various socket-based server classes. + + Defaults to synchronous IP stream (i.e., TCP). + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass, bind_and_activate=True) + - serve_forever(poll_interval=0.5) + - shutdown() + - handle_request() # if you don't use serve_forever() + - fileno() -> int # for selector + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - handle_timeout() + - verify_request(request, client_address) + - process_request(request, client_address) + - shutdown_request(request) + - close_request(request) + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - timeout + - address_family + - socket_type + - request_queue_size (only for stream sockets) + - allow_reuse_address + + Instance variables: + + - server_address + - RequestHandlerClass + - socket + + socket_typerequest_queue_sizebind_and_activateCalled by constructor to bind the socket. + + May be overridden. + + Return socket file number. + + Interface required by selector. + + Get the request and client address from the socket. + + May be overridden. + + UDP server class.max_packet_sizeclient_addrMix-in class to handle each request in a new process.max_childrenblock_on_closecollect_childrenblockingInternal routine to wait for children that have exited.Wait for zombies after self.timeout seconds of inactivity. + + May be extended, do not override. + Collect the zombie child processes regularly in the ForkingMixIn. + + service_actions is called in the BaseServer's serve_forever loop. + Fork a new subprocess to process the request._Threads + Joinable list of all non-daemon threads. + reap_NoThreads + Degenerate version of _Threads. + Mix-in class to handle each request in a new thread._threadsprocess_request_threadSame as in BaseServer but as a thread. + + In addition, exception handling is done here. + + Start a new thread to process the request.Base class for request handler classes. + + This class is instantiated for each request to be handled. The + constructor sets the instance variables request, client_address + and server, and then calls the handle() method. To implement a + specific service, all you need to do is to derive a class which + defines a handle() method. + + The handle() method can find the request as self.request, the + client address as self.client_address, and the server (in case it + needs access to per-server information) as self.server. Since a + separate instance is created for each request, the handle() method + can define other arbitrary instance variables. + + Define self.rfile and self.wfile for stream sockets.wbufsizedisable_nagle_algorithm_SocketWriterSimple writable BufferedIOBase implementation for a socket + + Does not hold data in a buffer, avoiding any need to call flush().Define self.rfile and self.wfile for datagram sockets.packet# Author of the BaseServer patch: Luke Kenneth Casson Leighton# poll/select have the advantage of not requiring any extra file descriptor,# contrarily to epoll/kqueue (also, they require a single syscall).# XXX: Consider using another file descriptor or connecting to the# socket to wake this up instead of polling. Polling reduces our# responsiveness to a shutdown request and wastes cpu at all other# times.# bpo-35017: shutdown() called during select(), exit immediately.# The distinction between handling, getting, processing and finishing a# request is fairly arbitrary. Remember:# - handle_request() is the top-level call. It calls selector.select(),# get_request(), verify_request() and process_request()# - get_request() is different for stream or datagram sockets# - process_request() is the place that may fork a new process or create a# new thread to finish the request# - finish_request() instantiates the request handler class; this# constructor will handle the request all by itself# Support people who used socket.settimeout() to escape# handle_request before self.timeout was available.# Wait until a request arrives or the timeout expires - the loop is# necessary to accommodate early wakeups due to EINTR.#explicitly shutdown. socket.close() merely releases#the socket and waits for GC to perform the actual close.#some platforms may raise ENOTCONN here# No need to call listen() for UDP.# No need to shutdown anything.# No need to close anything.# If true, server_close() waits until all child processes complete.# If we're above the max number of children, wait and reap them until# we go back below threshold. Note that we use waitpid(-1) below to be# able to collect children in size() syscalls instead# of size(): the downside is that this might reap children# which we didn't spawn, which is why we only resort to this when we're# above max_children.# we don't have any children, we're done# Now reap all defunct children.# if the child hasn't exited yet, pid will be 0 and ignored by# discard() below# someone else reaped it# Parent process# Child process.# This must never return, hence os._exit()!# Decides how threads will act upon termination of the# main process# If true, server_close() waits until all non-daemonic threads terminate.# Threads object# used by server_close() to wait for all threads completion.# The following two classes make it possible to use the same service# class for stream or datagram servers.# Each class sets up these instance variables:# - rfile: a file object from which receives the request is read# - wfile: a file object to which the reply is written# When the handle() method returns, wfile is flushed properly# Default buffer sizes for rfile, wfile.# We default rfile to buffered because otherwise it could be# really slow for large data (a getc() call per byte); we make# wfile unbuffered because (a) often after a write() we want to# read and we need to flush the line; (b) big writes to unbuffered# files are typically optimized by stdio even when big reads# aren't.# A timeout to apply to the request socket, if not None.# Disable nagle algorithm for this socket, if True.# Use only when wbufsize != 0, to avoid small packets.# A final socket error may have occurred here, such as# the local error ECONNABORTED.b'Generic socket server classes. + +This module tries to capture the various aspects of defining a server: + +For socket-based servers: + +- address family: + - AF_INET{,6}: IP (Internet Protocol) sockets (default) + - AF_UNIX: Unix domain sockets + - others, e.g. AF_DECNET are conceivable (see +- socket type: + - SOCK_STREAM (reliable stream, e.g. TCP) + - SOCK_DGRAM (datagrams, e.g. UDP) + +For request-based servers (including socket-based): + +- client address verification before further looking at the request + (This is actually a hook for any processing that needs to look + at the request before anything else, e.g. logging) +- how to handle multiple requests: + - synchronous (one request is handled at a time) + - forking (each request is handled by a new process) + - threading (each request is handled by a new thread) + +The classes in this module favor the server type that is simplest to +write: a synchronous TCP/IP server. This is bad class design, but +saves some typing. (There's also the issue that a deep class hierarchy +slows down method lookups.) + +There are five classes in an inheritance diagram, four of which represent +synchronous servers of four types: + + +------------+ + | BaseServer | + +------------+ + | + v + +-----------+ +------------------+ + | TCPServer |------->| UnixStreamServer | + +-----------+ +------------------+ + | + v + +-----------+ +--------------------+ + | UDPServer |------->| UnixDatagramServer | + +-----------+ +--------------------+ + +Note that UnixDatagramServer derives from UDPServer, not from +UnixStreamServer -- the only difference between an IP and a Unix +stream server is the address family, which is simply repeated in both +unix server classes. + +Forking and threading versions of each type of server can be created +using the ForkingMixIn and ThreadingMixIn mix-in classes. For +instance, a threading UDP server class is created as follows: + + class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass + +The Mix-in class must come first, since it overrides a method defined +in UDPServer! Setting the various member variables also changes +the behavior of the underlying server mechanism. + +To implement a service, you must derive a class from +BaseRequestHandler and redefine its handle() method. You can then run +various versions of the service by combining one of the server classes +with your request handler class. + +The request handler class must be different for datagram or stream +services. This can be hidden by using the request handler +subclasses StreamRequestHandler or DatagramRequestHandler. + +Of course, you still have to use your head! + +For instance, it makes no sense to use a forking server if the service +contains state in memory that can be modified by requests (since the +modifications in the child process would never reach the initial state +kept in the parent process and passed to each child). In this case, +you can use a threading server, but you will probably have to use +locks to avoid two requests that come in nearly simultaneous to apply +conflicting changes to the server state. + +On the other hand, if you are building e.g. an HTTP server, where all +data is stored externally (e.g. in the file system), a synchronous +class will essentially render the service "deaf" while one request is +being handled -- which may be for a very long time if a client is slow +to read all the data it has requested. Here a threading or forking +server is appropriate. + +In some cases, it may be appropriate to process part of a request +synchronously, but to finish processing in a forked child depending on +the request data. This can be implemented by using a synchronous +server and doing an explicit fork in the request handler class +handle() method. + +Another approach to handling multiple simultaneous requests in an +environment that supports neither threads nor fork (or where these are +too expensive or inappropriate for the service) is to maintain an +explicit table of partially finished requests and to use a selector to +decide which request to work on next (or whether to handle a new +incoming request). This is particularly important for stream services +where each client can potentially be connected for a long time (if +threads or subprocesses cannot be used). + +Future work: +- Standard classes for Sun RPC (which uses either UDP or TCP) +- Standard mix-in classes to implement various authentication + and encryption schemes + +XXX Open problems: +- What to do with out-of-band data? + +BaseServer: +- split generic "request" functionality out into BaseServer class. + Copyright (C) 2000 Luke Kenneth Casson Leighton + + example: read entries from a SQL database (requires overriding + get_request() to return a table entry from the database). + entry is processed by a RequestHandlerClass. + +'u'Generic socket server classes. + +This module tries to capture the various aspects of defining a server: + +For socket-based servers: + +- address family: + - AF_INET{,6}: IP (Internet Protocol) sockets (default) + - AF_UNIX: Unix domain sockets + - others, e.g. AF_DECNET are conceivable (see +- socket type: + - SOCK_STREAM (reliable stream, e.g. TCP) + - SOCK_DGRAM (datagrams, e.g. UDP) + +For request-based servers (including socket-based): + +- client address verification before further looking at the request + (This is actually a hook for any processing that needs to look + at the request before anything else, e.g. logging) +- how to handle multiple requests: + - synchronous (one request is handled at a time) + - forking (each request is handled by a new process) + - threading (each request is handled by a new thread) + +The classes in this module favor the server type that is simplest to +write: a synchronous TCP/IP server. This is bad class design, but +saves some typing. (There's also the issue that a deep class hierarchy +slows down method lookups.) + +There are five classes in an inheritance diagram, four of which represent +synchronous servers of four types: + + +------------+ + | BaseServer | + +------------+ + | + v + +-----------+ +------------------+ + | TCPServer |------->| UnixStreamServer | + +-----------+ +------------------+ + | + v + +-----------+ +--------------------+ + | UDPServer |------->| UnixDatagramServer | + +-----------+ +--------------------+ + +Note that UnixDatagramServer derives from UDPServer, not from +UnixStreamServer -- the only difference between an IP and a Unix +stream server is the address family, which is simply repeated in both +unix server classes. + +Forking and threading versions of each type of server can be created +using the ForkingMixIn and ThreadingMixIn mix-in classes. For +instance, a threading UDP server class is created as follows: + + class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass + +The Mix-in class must come first, since it overrides a method defined +in UDPServer! Setting the various member variables also changes +the behavior of the underlying server mechanism. + +To implement a service, you must derive a class from +BaseRequestHandler and redefine its handle() method. You can then run +various versions of the service by combining one of the server classes +with your request handler class. + +The request handler class must be different for datagram or stream +services. This can be hidden by using the request handler +subclasses StreamRequestHandler or DatagramRequestHandler. + +Of course, you still have to use your head! + +For instance, it makes no sense to use a forking server if the service +contains state in memory that can be modified by requests (since the +modifications in the child process would never reach the initial state +kept in the parent process and passed to each child). In this case, +you can use a threading server, but you will probably have to use +locks to avoid two requests that come in nearly simultaneous to apply +conflicting changes to the server state. + +On the other hand, if you are building e.g. an HTTP server, where all +data is stored externally (e.g. in the file system), a synchronous +class will essentially render the service "deaf" while one request is +being handled -- which may be for a very long time if a client is slow +to read all the data it has requested. Here a threading or forking +server is appropriate. + +In some cases, it may be appropriate to process part of a request +synchronously, but to finish processing in a forked child depending on +the request data. This can be implemented by using a synchronous +server and doing an explicit fork in the request handler class +handle() method. + +Another approach to handling multiple simultaneous requests in an +environment that supports neither threads nor fork (or where these are +too expensive or inappropriate for the service) is to maintain an +explicit table of partially finished requests and to use a selector to +decide which request to work on next (or whether to handle a new +incoming request). This is particularly important for stream services +where each client can potentially be connected for a long time (if +threads or subprocesses cannot be used). + +Future work: +- Standard classes for Sun RPC (which uses either UDP or TCP) +- Standard mix-in classes to implement various authentication + and encryption schemes + +XXX Open problems: +- What to do with out-of-band data? + +BaseServer: +- split generic "request" functionality out into BaseServer class. + Copyright (C) 2000 Luke Kenneth Casson Leighton + + example: read entries from a SQL database (requires overriding + get_request() to return a table entry from the database). + entry is processed by a RequestHandlerClass. + +'b'0.4'u'0.4'b'BaseServer'u'BaseServer'b'TCPServer'u'TCPServer'b'UDPServer'u'UDPServer'b'ThreadingUDPServer'u'ThreadingUDPServer'b'ThreadingTCPServer'u'ThreadingTCPServer'b'BaseRequestHandler'u'BaseRequestHandler'b'StreamRequestHandler'u'StreamRequestHandler'b'DatagramRequestHandler'u'DatagramRequestHandler'b'ThreadingMixIn'u'ThreadingMixIn'b'ForkingUDPServer'u'ForkingUDPServer'b'ForkingTCPServer'u'ForkingTCPServer'b'ForkingMixIn'u'ForkingMixIn'b'UnixStreamServer'u'UnixStreamServer'b'UnixDatagramServer'u'UnixDatagramServer'b'ThreadingUnixStreamServer'u'ThreadingUnixStreamServer'b'ThreadingUnixDatagramServer'u'ThreadingUnixDatagramServer'b'Base class for server classes. + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass) + - serve_forever(poll_interval=0.5) + - shutdown() + - handle_request() # if you do not use serve_forever() + - fileno() -> int # for selector + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - handle_timeout() + - verify_request(request, client_address) + - server_close() + - process_request(request, client_address) + - shutdown_request(request) + - close_request(request) + - service_actions() + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - timeout + - address_family + - socket_type + - allow_reuse_address + + Instance variables: + + - RequestHandlerClass + - socket + + 'u'Base class for server classes. + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass) + - serve_forever(poll_interval=0.5) + - shutdown() + - handle_request() # if you do not use serve_forever() + - fileno() -> int # for selector + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - handle_timeout() + - verify_request(request, client_address) + - server_close() + - process_request(request, client_address) + - shutdown_request(request) + - close_request(request) + - service_actions() + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - timeout + - address_family + - socket_type + - allow_reuse_address + + Instance variables: + + - RequestHandlerClass + - socket + + 'b'Constructor. May be extended, do not override.'u'Constructor. May be extended, do not override.'b'Called by constructor to activate the server. + + May be overridden. + + 'u'Called by constructor to activate the server. + + May be overridden. + + 'b'Handle one request at a time until shutdown. + + Polls for shutdown every poll_interval seconds. Ignores + self.timeout. If you need to do periodic tasks, do them in + another thread. + 'u'Handle one request at a time until shutdown. + + Polls for shutdown every poll_interval seconds. Ignores + self.timeout. If you need to do periodic tasks, do them in + another thread. + 'b'Stops the serve_forever loop. + + Blocks until the loop has finished. This must be called while + serve_forever() is running in another thread, or it will + deadlock. + 'u'Stops the serve_forever loop. + + Blocks until the loop has finished. This must be called while + serve_forever() is running in another thread, or it will + deadlock. + 'b'Called by the serve_forever() loop. + + May be overridden by a subclass / Mixin to implement any code that + needs to be run during the loop. + 'u'Called by the serve_forever() loop. + + May be overridden by a subclass / Mixin to implement any code that + needs to be run during the loop. + 'b'Handle one request, possibly blocking. + + Respects self.timeout. + 'u'Handle one request, possibly blocking. + + Respects self.timeout. + 'b'Handle one request, without blocking. + + I assume that selector.select() has returned that the socket is + readable before this function was called, so there should be no risk of + blocking in get_request(). + 'u'Handle one request, without blocking. + + I assume that selector.select() has returned that the socket is + readable before this function was called, so there should be no risk of + blocking in get_request(). + 'b'Called if no new request arrives within self.timeout. + + Overridden by ForkingMixIn. + 'u'Called if no new request arrives within self.timeout. + + Overridden by ForkingMixIn. + 'b'Verify the request. May be overridden. + + Return True if we should proceed with this request. + + 'u'Verify the request. May be overridden. + + Return True if we should proceed with this request. + + 'b'Call finish_request. + + Overridden by ForkingMixIn and ThreadingMixIn. + + 'u'Call finish_request. + + Overridden by ForkingMixIn and ThreadingMixIn. + + 'b'Called to clean-up the server. + + May be overridden. + + 'u'Called to clean-up the server. + + May be overridden. + + 'b'Finish one request by instantiating RequestHandlerClass.'u'Finish one request by instantiating RequestHandlerClass.'b'Called to shutdown and close an individual request.'u'Called to shutdown and close an individual request.'b'Called to clean up an individual request.'u'Called to clean up an individual request.'b'Handle an error gracefully. May be overridden. + + The default is to print a traceback and continue. + + 'u'Handle an error gracefully. May be overridden. + + The default is to print a traceback and continue. + + 'b'Exception happened during processing of request from'u'Exception happened during processing of request from'b'Base class for various socket-based server classes. + + Defaults to synchronous IP stream (i.e., TCP). + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass, bind_and_activate=True) + - serve_forever(poll_interval=0.5) + - shutdown() + - handle_request() # if you don't use serve_forever() + - fileno() -> int # for selector + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - handle_timeout() + - verify_request(request, client_address) + - process_request(request, client_address) + - shutdown_request(request) + - close_request(request) + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - timeout + - address_family + - socket_type + - request_queue_size (only for stream sockets) + - allow_reuse_address + + Instance variables: + + - server_address + - RequestHandlerClass + - socket + + 'u'Base class for various socket-based server classes. + + Defaults to synchronous IP stream (i.e., TCP). + + Methods for the caller: + + - __init__(server_address, RequestHandlerClass, bind_and_activate=True) + - serve_forever(poll_interval=0.5) + - shutdown() + - handle_request() # if you don't use serve_forever() + - fileno() -> int # for selector + + Methods that may be overridden: + + - server_bind() + - server_activate() + - get_request() -> request, client_address + - handle_timeout() + - verify_request(request, client_address) + - process_request(request, client_address) + - shutdown_request(request) + - close_request(request) + - handle_error() + + Methods for derived classes: + + - finish_request(request, client_address) + + Class variables that may be overridden by derived classes or + instances: + + - timeout + - address_family + - socket_type + - request_queue_size (only for stream sockets) + - allow_reuse_address + + Instance variables: + + - server_address + - RequestHandlerClass + - socket + + 'b'Called by constructor to bind the socket. + + May be overridden. + + 'u'Called by constructor to bind the socket. + + May be overridden. + + 'b'Return socket file number. + + Interface required by selector. + + 'u'Return socket file number. + + Interface required by selector. + + 'b'Get the request and client address from the socket. + + May be overridden. + + 'u'Get the request and client address from the socket. + + May be overridden. + + 'b'UDP server class.'u'UDP server class.'b'Mix-in class to handle each request in a new process.'u'Mix-in class to handle each request in a new process.'b'Internal routine to wait for children that have exited.'u'Internal routine to wait for children that have exited.'b'Wait for zombies after self.timeout seconds of inactivity. + + May be extended, do not override. + 'u'Wait for zombies after self.timeout seconds of inactivity. + + May be extended, do not override. + 'b'Collect the zombie child processes regularly in the ForkingMixIn. + + service_actions is called in the BaseServer's serve_forever loop. + 'u'Collect the zombie child processes regularly in the ForkingMixIn. + + service_actions is called in the BaseServer's serve_forever loop. + 'b'Fork a new subprocess to process the request.'u'Fork a new subprocess to process the request.'b' + Joinable list of all non-daemon threads. + 'u' + Joinable list of all non-daemon threads. + 'b' + Degenerate version of _Threads. + 'u' + Degenerate version of _Threads. + 'b'Mix-in class to handle each request in a new thread.'u'Mix-in class to handle each request in a new thread.'b'Same as in BaseServer but as a thread. + + In addition, exception handling is done here. + + 'u'Same as in BaseServer but as a thread. + + In addition, exception handling is done here. + + 'b'Start a new thread to process the request.'u'Start a new thread to process the request.'b'_threads'u'_threads'b'Base class for request handler classes. + + This class is instantiated for each request to be handled. The + constructor sets the instance variables request, client_address + and server, and then calls the handle() method. To implement a + specific service, all you need to do is to derive a class which + defines a handle() method. + + The handle() method can find the request as self.request, the + client address as self.client_address, and the server (in case it + needs access to per-server information) as self.server. Since a + separate instance is created for each request, the handle() method + can define other arbitrary instance variables. + + 'u'Base class for request handler classes. + + This class is instantiated for each request to be handled. The + constructor sets the instance variables request, client_address + and server, and then calls the handle() method. To implement a + specific service, all you need to do is to derive a class which + defines a handle() method. + + The handle() method can find the request as self.request, the + client address as self.client_address, and the server (in case it + needs access to per-server information) as self.server. Since a + separate instance is created for each request, the handle() method + can define other arbitrary instance variables. + + 'b'Define self.rfile and self.wfile for stream sockets.'u'Define self.rfile and self.wfile for stream sockets.'b'Simple writable BufferedIOBase implementation for a socket + + Does not hold data in a buffer, avoiding any need to call flush().'u'Simple writable BufferedIOBase implementation for a socket + + Does not hold data in a buffer, avoiding any need to call flush().'b'Define self.rfile and self.wfile for datagram sockets.'u'Define self.rfile and self.wfile for datagram sockets.'distutils.spawn + +Provides the 'spawn()' function, a front-end to various platform- +specific functions for launching another program in a sub-process. +Also provides the 'find_executable()' to search the path for a given +executable name. +Run another program, specified as a command list 'cmd', in a new process. + + 'cmd' is just the argument list for the new process, ie. + cmd[0] is the program to run and cmd[1:] are the rest of its arguments. + There is no way to run a program with a name different from that of its + executable. + + If 'search_path' is true (the default), the system's executable + search path will be used to find the program; otherwise, cmd[0] + must be the exact path to the executable. If 'dry_run' is true, + the command will not actually be run. + + Raise DistutilsExecError if running the program fails in any way; just + return on success. + _spawn_posix_spawn_ntdon't know how to spawn programs on platform '%s'_nt_quote_argsQuote command-line arguments for DOS/Windows conventions. + + Just wraps every argument which contains blanks in double quotes, and + returns a new argument list. + command %r failed: %scommand %r failed with exit status %d_cfg_target_cfg_target_splitexec_fncur_target$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'$MACOSX_DEPLOYMENT_TARGET mismatch: ''now "%s" but "%s" during configure'my_msgunable to execute %r: %s +unable to execute %r for unknown reasonscommand %r terminated by signal %dexit_statusunknown error executing %r: termination status %d# cmd is documented as a list, but just in case some code passes a tuple# in, protect our %-formatting code against horrible death# XXX this doesn't seem very robust to me -- but if the Windows guys# say it'll work, I guess I'll have to accept it. (What if an arg# contains quotes? What other magic characters, other than spaces,# have to be escaped? Is there an escaping mechanism other than# quoting?)# either we find one or it stays the same# spawn for NT requires a full path to the .exe# this seems to happen when the command isn't found# and this reflects the command running but failing# ensure that the deployment target of build process is not less# than that used when the interpreter was built. This ensures# extension modules are built with correct compatibility values# in the child# in the parent# Loop until the child either exits or is terminated by a signal# (ie. keep waiting if it's merely stopped)# hey, it succeeded!b'distutils.spawn + +Provides the 'spawn()' function, a front-end to various platform- +specific functions for launching another program in a sub-process. +Also provides the 'find_executable()' to search the path for a given +executable name. +'u'distutils.spawn + +Provides the 'spawn()' function, a front-end to various platform- +specific functions for launching another program in a sub-process. +Also provides the 'find_executable()' to search the path for a given +executable name. +'b'Run another program, specified as a command list 'cmd', in a new process. + + 'cmd' is just the argument list for the new process, ie. + cmd[0] is the program to run and cmd[1:] are the rest of its arguments. + There is no way to run a program with a name different from that of its + executable. + + If 'search_path' is true (the default), the system's executable + search path will be used to find the program; otherwise, cmd[0] + must be the exact path to the executable. If 'dry_run' is true, + the command will not actually be run. + + Raise DistutilsExecError if running the program fails in any way; just + return on success. + 'u'Run another program, specified as a command list 'cmd', in a new process. + + 'cmd' is just the argument list for the new process, ie. + cmd[0] is the program to run and cmd[1:] are the rest of its arguments. + There is no way to run a program with a name different from that of its + executable. + + If 'search_path' is true (the default), the system's executable + search path will be used to find the program; otherwise, cmd[0] + must be the exact path to the executable. If 'dry_run' is true, + the command will not actually be run. + + Raise DistutilsExecError if running the program fails in any way; just + return on success. + 'b'don't know how to spawn programs on platform '%s''u'don't know how to spawn programs on platform '%s''b'Quote command-line arguments for DOS/Windows conventions. + + Just wraps every argument which contains blanks in double quotes, and + returns a new argument list. + 'u'Quote command-line arguments for DOS/Windows conventions. + + Just wraps every argument which contains blanks in double quotes, and + returns a new argument list. + 'b'command %r failed: %s'u'command %r failed: %s'b'command %r failed with exit status %d'u'command %r failed with exit status %d'b'$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'u'$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'b'unable to execute %r: %s +'u'unable to execute %r: %s +'b'unable to execute %r for unknown reasons'u'unable to execute %r for unknown reasons'b'command %r terminated by signal %d'u'command %r terminated by signal %d'b'unknown error executing %r: termination status %d'u'unknown error executing %r: termination status %d'u'distutils.spawn'get_command_lineWINEXEWINSERVICEpythonservice.exepython.exe_python_exeis_forking + Return whether commandline indicates we are forking + --multiprocessing-fork + Run code for process object if this in not the main process + spawn_main + Returns prefix of command line used for spawning a child process + from multiprocessing.spawn import spawn_main; spawn_main(%s)pipe_handleparent_pidtracker_fd + Run code specified by data received over pipe + Not forkingSYNCHRONIZEnew_handleopen_osfhandlefrom_parentpreparation_data_check_not_importing_main + An attempt has been made to start a new process before the + current process has finished its bootstrapping phase. + + This probably means that you are not using fork to start your + child processes and you have forgotten to use the proper idiom + in the main module: + + if __name__ == '__main__': + freeze_support() + ... + + The "freeze_support()" line can be omitted if the program + is not going to be frozen to produce an executable. + Return info about parent needed by child to unpickle process object + _log_to_stderr_loggerlog_levelsys_argvorig_dirstart_methodmain_modulemain_mod_nameinit_main_from_nameinit_main_from_pathold_main_modules + Try to get current process ready to unpickle process object + _fixup_main_from_name_fixup_main_from_pathcurrent_mainmain_contentipython + Set sys.modules['__main__'] to module at main_path + # Code used to start processes when using the spawn or forkserver# start methods.# multiprocessing/spawn.py# _python_exe is the assumed path to the python executable.# People embedding Python want to modify it.# Figure out whether to initialise main in the subprocess as a module# or through direct execution (or to leave it alone entirely)# Prepare current process# Multiprocessing module helpers to fix up the main module in# spawned subprocesses# __main__.py files for packages, directories, zip archives, etc, run# their "main only" code unconditionally, so we don't even try to# populate anything in __main__, nor do we make any changes to# __main__ attributes# If this process was forked, __main__ may already be populated# Otherwise, __main__ may contain some non-main code where we need to# support unpickling it properly. We rerun it as __mp_main__ and make# the normal __main__ an alias to that# Unfortunately, the main ipython launch script historically had no# "if __name__ == '__main__'" guard, so we work around that# by treating it like a __main__.py file# See https://github.com/ipython/ipython/issues/4698# Otherwise, if __file__ already has the setting we expect,# there's nothing more to do# If the parent process has sent a path through rather than a module# name we assume it is an executable script that may contain# non-main code that needs to be executedb'_main'u'_main'b'freeze_support'u'freeze_support'b'set_executable'u'set_executable'b'get_executable'u'get_executable'b'get_preparation_data'u'get_preparation_data'b'get_command_line'u'get_command_line'b'import_main_path'u'import_main_path'b'pythonservice.exe'u'pythonservice.exe'b'python.exe'u'python.exe'b' + Return whether commandline indicates we are forking + 'u' + Return whether commandline indicates we are forking + 'b'--multiprocessing-fork'u'--multiprocessing-fork'b' + Run code for process object if this in not the main process + 'u' + Run code for process object if this in not the main process + 'b' + Returns prefix of command line used for spawning a child process + 'u' + Returns prefix of command line used for spawning a child process + 'b'from multiprocessing.spawn import spawn_main; spawn_main(%s)'u'from multiprocessing.spawn import spawn_main; spawn_main(%s)'b' + Run code specified by data received over pipe + 'u' + Run code specified by data received over pipe + 'b'Not forking'u'Not forking'b'_inheriting'u'_inheriting'b' + An attempt has been made to start a new process before the + current process has finished its bootstrapping phase. + + This probably means that you are not using fork to start your + child processes and you have forgotten to use the proper idiom + in the main module: + + if __name__ == '__main__': + freeze_support() + ... + + The "freeze_support()" line can be omitted if the program + is not going to be frozen to produce an executable.'u' + An attempt has been made to start a new process before the + current process has finished its bootstrapping phase. + + This probably means that you are not using fork to start your + child processes and you have forgotten to use the proper idiom + in the main module: + + if __name__ == '__main__': + freeze_support() + ... + + The "freeze_support()" line can be omitted if the program + is not going to be frozen to produce an executable.'b' + Return info about parent needed by child to unpickle process object + 'u' + Return info about parent needed by child to unpickle process object + 'b'log_level'u'log_level'b'init_main_from_name'u'init_main_from_name'b'init_main_from_path'u'init_main_from_path'b' + Try to get current process ready to unpickle process object + 'u' + Try to get current process ready to unpickle process object + 'b'log_to_stderr'u'log_to_stderr'b'sys_argv'u'sys_argv'b'dir'u'dir'b'orig_dir'u'orig_dir'b'start_method'u'start_method'b'ipython'u'ipython'b' + Set sys.modules['__main__'] to module at main_path + 'u' + Set sys.modules['__main__'] to module at main_path + 'u'multiprocessing.spawn'Internal support module for sreSRE module mismatchLITERALNOT_LITERAL_LITERAL_CODESREPEATMIN_REPEATMAX_REPEAT_REPEATING_CODES_SUCCESS_CODESASSERTASSERT_NOT_ASSERT_CODESANYIN_UNIT_CODES0x690x1310x733830x17f0xb50x3bc8370x3450x3b981260x1fbe9120x39081470x1fd39440x3b081630x1fe30x3b29760x3d00x3b50x3f50x3b80x3d10x3ba10080x3f00x3c00x3d60x3c110090x3f10x3c20x3c30x3c69810x3d577770x1e6178350x1e9b642610xfb05642620xfb06_equivalences_ignorecase_fixes_combine_flagsTYPE_FLAGSadd_flagsdel_flagsLITERAL_CODESREPEATING_CODESSUCCESS_CODESASSERT_CODESiscasedtolowerfixesavOP_LOCALE_IGNOREOP_IGNOREOP_UNICODE_IGNOREIN_UNI_IGNORENEGATE_optimize_charsethascasedIN_LOC_IGNOREIN_IGNORE_compile_charsetANY_ALLinternal: unsupported template operator %r_simpleREPEAT_ONEMIN_REPEAT_ONEMAX_UNTILMIN_UNTILgetwidthlook-behind requires fixed-width patternCALLATAT_MULTILINEAT_LOCALEAT_UNICODEtailappendJUMPCATEGORYCH_LOCALECH_UNICODEGROUPREFGROUPREF_LOC_IGNOREGROUPREF_IGNOREGROUPREF_UNI_IGNOREGROUPREF_EXISTSskipyesskipnointernal: unsupported operand type %rRANGERANGE_UNI_IGNORECHARSETBIGCHARSETinternal: unsupported set operator %rfixupcharmap652800xff00runs_mk_bitmap_bytes_to_codes_CODEBITSMAXCODE_BITS_TRANS_generate_overlap_table + Generate an overlap table for the following prefix. + An overlap table is a table of the same size as the prefix which + informs about the potential self-overlap for each index in the prefix: + - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...] + - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with + prefix[0:k] + _get_iscased_get_literal_prefixprefixappendprefix_skipflags1prefix_skip1got_all_get_charset_prefixcharsetappend_compile_infoSRE_INFO_PREFIXSRE_INFO_LITERALSRE_INFO_CHARSET_code_hex_code%#0*xdis_print_(to %d)%*d%s print_2OPCODESLITERAL_IGNORENOT_LITERAL_IGNORELITERAL_UNI_IGNORENOT_LITERAL_UNI_IGNORELITERAL_LOC_IGNORENOT_LITERAL_LOC_IGNORE%#02x (%r)ATCODESAT_CHCODESCATEGORY_%#02x %#02x (%r-%r)prefix_len prefix_skip prefix%#02x(%r) overlapgroupindexindexgroup# convert template to internal format# Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.# See the sre.py file for information on usage and redistribution.# Sets of lowercase characters which have the same uppercase.# LATIN SMALL LETTER I, LATIN SMALL LETTER DOTLESS I# iı# LATIN SMALL LETTER S, LATIN SMALL LETTER LONG S# sſ# MICRO SIGN, GREEK SMALL LETTER MU# µμ# COMBINING GREEK YPOGEGRAMMENI, GREEK SMALL LETTER IOTA, GREEK PROSGEGRAMMENI# \u0345ιι# GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS, GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA# ΐΐ# GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS, GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA# ΰΰ# GREEK SMALL LETTER BETA, GREEK BETA SYMBOL# βϐ# GREEK SMALL LETTER EPSILON, GREEK LUNATE EPSILON SYMBOL# εϵ# GREEK SMALL LETTER THETA, GREEK THETA SYMBOL# θϑ# GREEK SMALL LETTER KAPPA, GREEK KAPPA SYMBOL# κϰ# GREEK SMALL LETTER PI, GREEK PI SYMBOL# πϖ# GREEK SMALL LETTER RHO, GREEK RHO SYMBOL# ρϱ# GREEK SMALL LETTER FINAL SIGMA, GREEK SMALL LETTER SIGMA# ςσ# GREEK SMALL LETTER PHI, GREEK PHI SYMBOL# φϕ# LATIN SMALL LETTER S WITH DOT ABOVE, LATIN SMALL LETTER LONG S WITH DOT ABOVE# ṡẛ# LATIN SMALL LIGATURE LONG S T, LATIN SMALL LIGATURE ST# ſtst# Maps the lowercase code to lowercase codes which have the same uppercase.# internal: compile a (sub)pattern# ascii# _compile_info(code, p, _combine_flags(flags, add_flags, del_flags))# look ahead# look behind# _compile_info(code, av, flags)# end of branch# compile charset subprogram# internal: optimize character set# character set contains non-UCS1 character codes# Character set contains non-BMP character codes.# There are only two ranges of cased non-BMP characters:# 10400-1044F (Deseret) and 118A0-118DF (Warang Citi),# and for both ranges RANGE_UNI_IGNORE works.# compress character map# use literal/range# if the case was changed or new representation is more compact# else original character set is good enough# use bitmap# To represent a big charset, first a bitmap of all characters in the# set is constructed. Then, this bitmap is sliced into chunks of 256# characters, duplicate chunks are eliminated, and each chunk is# given a number. In the compiled expression, the charset is# represented by a 32-bit word sequence, consisting of one word for# the number of different chunks, a sequence of 256 bytes (64 words)# of chunk numbers indexed by their original chunk position, and a# sequence of 256-bit chunks (8 words each).# Compression is normally good: in a typical charset, large ranges of# Unicode will be either completely excluded (e.g. if only cyrillic# letters are to be matched), or completely included (e.g. if large# subranges of Kanji match). These ranges will be represented by# chunks of all one-bits or all zero-bits.# Matching can be also done efficiently: the more significant byte of# the Unicode character is an index into the chunk number, and the# less significant byte is a bit index in the chunk (just like the# CHARSET matching).# should be hashable# Convert block indices to word array# check if this subpattern is a "simple" operator# look for literal prefix# internal: compile an info block. in the current version,# this contains min/max pattern width, and an optional literal# prefix or a character map# look for a literal prefix# not used# if no prefix, look for charset prefix## if prefix:## print("*** PREFIX", prefix, prefix_skip)## if charset:## print("*** CHARSET", charset)# add an info block# literal flag# pattern length# add literal prefix# length# skip# generate overlap table# compile info block# compile the pattern# internal: convert pattern list to internal format# map in either directionb'Internal support module for sre'u'Internal support module for sre'b'SRE module mismatch'u'SRE module mismatch'b'internal: unsupported template operator %r'u'internal: unsupported template operator %r'b'look-behind requires fixed-width pattern'u'look-behind requires fixed-width pattern'b'internal: unsupported operand type %r'u'internal: unsupported operand type %r'b'internal: unsupported set operator %r'u'internal: unsupported set operator %r'b' + Generate an overlap table for the following prefix. + An overlap table is a table of the same size as the prefix which + informs about the potential self-overlap for each index in the prefix: + - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...] + - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with + prefix[0:k] + 'u' + Generate an overlap table for the following prefix. + An overlap table is a table of the same size as the prefix which + informs about the potential self-overlap for each index in the prefix: + - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...] + - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with + prefix[0:k] + 'b'%#0*x'u'%#0*x'b'(to %d)'u'(to %d)'b'%*d%s 'u'%*d%s 'b'%#02x (%r)'u'%#02x (%r)'b'AT_'u'AT_'b'CATEGORY_'u'CATEGORY_'b'%#02x %#02x (%r-%r)'u'%#02x %#02x (%r-%r)'b'branch'u'branch'b'MAXREPEAT'u'MAXREPEAT'b' prefix_skip'u' prefix_skip'b' prefix'u' prefix'b'%#02x'u'%#02x'b'(%r)'u'(%r)'b' overlap'u' overlap'u'sre_compile'Exception raised for invalid regular expressions. + + Attributes: + + msg: The unformatted error message + pattern: The regular expression pattern + pos: The index in the pattern where compilation failed (may be None) + lineno: The line corresponding to pos (may be None) + colno: The column corresponding to pos (may be None) + %s at position %dcolno%s (line %d, column %d)_NamedIntConstant_makecodes + FAILURE SUCCESS + + ANY ANY_ALL + ASSERT ASSERT_NOT + AT + BRANCH + CALL + CATEGORY + CHARSET BIGCHARSET + GROUPREF GROUPREF_EXISTS + IN + INFO + JUMP + LITERAL + MARK + MAX_UNTIL + MIN_UNTIL + NOT_LITERAL + NEGATE + RANGE + REPEAT + REPEAT_ONE + SUBPATTERN + MIN_REPEAT_ONE + + GROUPREF_IGNORE + IN_IGNORE + LITERAL_IGNORE + NOT_LITERAL_IGNORE + + GROUPREF_LOC_IGNORE + IN_LOC_IGNORE + LITERAL_LOC_IGNORE + NOT_LITERAL_LOC_IGNORE + + GROUPREF_UNI_IGNORE + IN_UNI_IGNORE + LITERAL_UNI_IGNORE + NOT_LITERAL_UNI_IGNORE + RANGE_UNI_IGNORE + + MIN_REPEAT MAX_REPEAT + + AT_BEGINNING AT_BEGINNING_LINE AT_BEGINNING_STRING + AT_BOUNDARY AT_NON_BOUNDARY + AT_END AT_END_LINE AT_END_STRING + + AT_LOC_BOUNDARY AT_LOC_NON_BOUNDARY + + AT_UNI_BOUNDARY AT_UNI_NON_BOUNDARY + + CATEGORY_DIGIT CATEGORY_NOT_DIGIT + CATEGORY_SPACE CATEGORY_NOT_SPACE + CATEGORY_WORD CATEGORY_NOT_WORD + CATEGORY_LINEBREAK CATEGORY_NOT_LINEBREAK + + CATEGORY_LOC_WORD CATEGORY_LOC_NOT_WORD + + CATEGORY_UNI_DIGIT CATEGORY_UNI_NOT_DIGIT + CATEGORY_UNI_SPACE CATEGORY_UNI_NOT_SPACE + CATEGORY_UNI_WORD CATEGORY_UNI_NOT_WORD + CATEGORY_UNI_LINEBREAK CATEGORY_UNI_NOT_LINEBREAK +AT_BEGINNING_LINEAT_BEGINNINGAT_END_LINEAT_ENDAT_LOC_BOUNDARYAT_BOUNDARYAT_LOC_NON_BOUNDARYAT_NON_BOUNDARYAT_UNI_BOUNDARYAT_UNI_NON_BOUNDARYCATEGORY_DIGITCATEGORY_NOT_DIGITCATEGORY_SPACECATEGORY_NOT_SPACECATEGORY_LOC_WORDCATEGORY_WORDCATEGORY_LOC_NOT_WORDCATEGORY_NOT_WORDCATEGORY_LINEBREAKCATEGORY_NOT_LINEBREAKCATEGORY_UNI_DIGITCATEGORY_UNI_NOT_DIGITCATEGORY_UNI_SPACECATEGORY_UNI_NOT_SPACECATEGORY_UNI_WORDCATEGORY_UNI_NOT_WORDCATEGORY_UNI_LINEBREAKCATEGORY_UNI_NOT_LINEBREAK#define %s_%s %d +sre_constants.h/* + * Secret Labs' Regular Expression Engine + * + * regular expression matching engine + * + * NOTE: This file is generated by sre_constants.py. If you need + * to change anything in here, edit sre_constants.py and run it. + * + * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. + * + * See the _sre.c file for information on usage and redistribution. + */ + +#define SRE_MAGIC %d +SRE_OPSRE#define SRE_FLAG_TEMPLATE %d +#define SRE_FLAG_IGNORECASE %d +#define SRE_FLAG_LOCALE %d +#define SRE_FLAG_MULTILINE %d +#define SRE_FLAG_DOTALL %d +#define SRE_FLAG_UNICODE %d +#define SRE_FLAG_VERBOSE %d +#define SRE_FLAG_DEBUG %d +#define SRE_FLAG_ASCII %d +#define SRE_INFO_PREFIX %d +#define SRE_INFO_LITERAL %d +#define SRE_INFO_CHARSET %d +# various symbols used by the regular expression engine.# run this script to update the _sre include files!# update when constants are added or removed# SRE standard exception (access as sre.error)# should this really be here?# operators# failure=0 success=1 (just because it looks better that way :-)# remove MIN_REPEAT and MAX_REPEAT# positions# categories# replacement operations for "ignore case" mode# flags# template mode (disable backtracking)# case insensitive# honour system locale# treat target as multiline string# treat target as a single string# use unicode "locale"# use ascii "locale"# flags for INFO primitive# has prefix# entire pattern is literal (given by prefix)# pattern starts with character from given setb'Exception raised for invalid regular expressions. + + Attributes: + + msg: The unformatted error message + pattern: The regular expression pattern + pos: The index in the pattern where compilation failed (may be None) + lineno: The line corresponding to pos (may be None) + colno: The column corresponding to pos (may be None) + 'u'Exception raised for invalid regular expressions. + + Attributes: + + msg: The unformatted error message + pattern: The regular expression pattern + pos: The index in the pattern where compilation failed (may be None) + lineno: The line corresponding to pos (may be None) + colno: The column corresponding to pos (may be None) + 'b're'b'%s at position %d'u'%s at position %d'b'%s (line %d, column %d)'u'%s (line %d, column %d)'b' + FAILURE SUCCESS + + ANY ANY_ALL + ASSERT ASSERT_NOT + AT + BRANCH + CALL + CATEGORY + CHARSET BIGCHARSET + GROUPREF GROUPREF_EXISTS + IN + INFO + JUMP + LITERAL + MARK + MAX_UNTIL + MIN_UNTIL + NOT_LITERAL + NEGATE + RANGE + REPEAT + REPEAT_ONE + SUBPATTERN + MIN_REPEAT_ONE + + GROUPREF_IGNORE + IN_IGNORE + LITERAL_IGNORE + NOT_LITERAL_IGNORE + + GROUPREF_LOC_IGNORE + IN_LOC_IGNORE + LITERAL_LOC_IGNORE + NOT_LITERAL_LOC_IGNORE + + GROUPREF_UNI_IGNORE + IN_UNI_IGNORE + LITERAL_UNI_IGNORE + NOT_LITERAL_UNI_IGNORE + RANGE_UNI_IGNORE + + MIN_REPEAT MAX_REPEAT +'u' + FAILURE SUCCESS + + ANY ANY_ALL + ASSERT ASSERT_NOT + AT + BRANCH + CALL + CATEGORY + CHARSET BIGCHARSET + GROUPREF GROUPREF_EXISTS + IN + INFO + JUMP + LITERAL + MARK + MAX_UNTIL + MIN_UNTIL + NOT_LITERAL + NEGATE + RANGE + REPEAT + REPEAT_ONE + SUBPATTERN + MIN_REPEAT_ONE + + GROUPREF_IGNORE + IN_IGNORE + LITERAL_IGNORE + NOT_LITERAL_IGNORE + + GROUPREF_LOC_IGNORE + IN_LOC_IGNORE + LITERAL_LOC_IGNORE + NOT_LITERAL_LOC_IGNORE + + GROUPREF_UNI_IGNORE + IN_UNI_IGNORE + LITERAL_UNI_IGNORE + NOT_LITERAL_UNI_IGNORE + RANGE_UNI_IGNORE + + MIN_REPEAT MAX_REPEAT +'b' + AT_BEGINNING AT_BEGINNING_LINE AT_BEGINNING_STRING + AT_BOUNDARY AT_NON_BOUNDARY + AT_END AT_END_LINE AT_END_STRING + + AT_LOC_BOUNDARY AT_LOC_NON_BOUNDARY + + AT_UNI_BOUNDARY AT_UNI_NON_BOUNDARY +'u' + AT_BEGINNING AT_BEGINNING_LINE AT_BEGINNING_STRING + AT_BOUNDARY AT_NON_BOUNDARY + AT_END AT_END_LINE AT_END_STRING + + AT_LOC_BOUNDARY AT_LOC_NON_BOUNDARY + + AT_UNI_BOUNDARY AT_UNI_NON_BOUNDARY +'b' + CATEGORY_DIGIT CATEGORY_NOT_DIGIT + CATEGORY_SPACE CATEGORY_NOT_SPACE + CATEGORY_WORD CATEGORY_NOT_WORD + CATEGORY_LINEBREAK CATEGORY_NOT_LINEBREAK + + CATEGORY_LOC_WORD CATEGORY_LOC_NOT_WORD + + CATEGORY_UNI_DIGIT CATEGORY_UNI_NOT_DIGIT + CATEGORY_UNI_SPACE CATEGORY_UNI_NOT_SPACE + CATEGORY_UNI_WORD CATEGORY_UNI_NOT_WORD + CATEGORY_UNI_LINEBREAK CATEGORY_UNI_NOT_LINEBREAK +'u' + CATEGORY_DIGIT CATEGORY_NOT_DIGIT + CATEGORY_SPACE CATEGORY_NOT_SPACE + CATEGORY_WORD CATEGORY_NOT_WORD + CATEGORY_LINEBREAK CATEGORY_NOT_LINEBREAK + + CATEGORY_LOC_WORD CATEGORY_LOC_NOT_WORD + + CATEGORY_UNI_DIGIT CATEGORY_UNI_NOT_DIGIT + CATEGORY_UNI_SPACE CATEGORY_UNI_NOT_SPACE + CATEGORY_UNI_WORD CATEGORY_UNI_NOT_WORD + CATEGORY_UNI_LINEBREAK CATEGORY_UNI_NOT_LINEBREAK +'b'#define %s_%s %d +'u'#define %s_%s %d +'b'sre_constants.h'u'sre_constants.h'b'/* + * Secret Labs' Regular Expression Engine + * + * regular expression matching engine + * + * NOTE: This file is generated by sre_constants.py. If you need + * to change anything in here, edit sre_constants.py and run it. + * + * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. + * + * See the _sre.c file for information on usage and redistribution. + */ + +'u'/* + * Secret Labs' Regular Expression Engine + * + * regular expression matching engine + * + * NOTE: This file is generated by sre_constants.py. If you need + * to change anything in here, edit sre_constants.py and run it. + * + * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved. + * + * See the _sre.c file for information on usage and redistribution. + */ + +'b'#define SRE_MAGIC %d +'u'#define SRE_MAGIC %d +'b'SRE_OP'u'SRE_OP'b'SRE'u'SRE'b'#define SRE_FLAG_TEMPLATE %d +'u'#define SRE_FLAG_TEMPLATE %d +'b'#define SRE_FLAG_IGNORECASE %d +'u'#define SRE_FLAG_IGNORECASE %d +'b'#define SRE_FLAG_LOCALE %d +'u'#define SRE_FLAG_LOCALE %d +'b'#define SRE_FLAG_MULTILINE %d +'u'#define SRE_FLAG_MULTILINE %d +'b'#define SRE_FLAG_DOTALL %d +'u'#define SRE_FLAG_DOTALL %d +'b'#define SRE_FLAG_UNICODE %d +'u'#define SRE_FLAG_UNICODE %d +'b'#define SRE_FLAG_VERBOSE %d +'u'#define SRE_FLAG_VERBOSE %d +'b'#define SRE_FLAG_DEBUG %d +'u'#define SRE_FLAG_DEBUG %d +'b'#define SRE_FLAG_ASCII %d +'u'#define SRE_FLAG_ASCII %d +'b'#define SRE_INFO_PREFIX %d +'u'#define SRE_INFO_PREFIX %d +'b'#define SRE_INFO_LITERAL %d +'u'#define SRE_INFO_LITERAL %d +'b'#define SRE_INFO_CHARSET %d +'u'#define SRE_INFO_CHARSET %d +'b'done'u'done'u'sre_constants'.\[{()*+?^$|SPECIAL_CHARS*+?{REPEAT_CHARSDIGITS01234567OCTDIGITS0123456789abcdefABCDEFHEXDIGITSabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZASCIILETTERS + WHITESPACE_REPEATCODES_UNITCODES\a\f\r\t\vESCAPESAT_BEGINNING_STRING\A\B\d\D\s\S\w\WAT_END_STRING\ZCATEGORIESFLAGSGLOBAL_FLAGSVerbosegroupwidthslookbehindgroupstoo many groupsogidredefinition of group name %r as group %d; was group %d"redefinition of group name %r as group %d; ""was group %d"checkgroupchecklookbehindgroupcannot refer to an open groupcannot refer to group defined in the same lookbehind subpattern'cannot refer to group defined in the same ''lookbehind subpattern'seqtypesORcondgroupitem_yesitem_noELSETokenizeristextdecoded_string__nextbad escape (end of pattern)thisgetwhilegetuntilmissing missing %s, unterminated name_class_escapeincomplete escape %smissing {character namecharnameundefined character name %r\N{}0o377octal escape value %s outside of range 0-0o377'octal escape value %s outside of ''range 0-0o377'bad escape %sinvalid group reference %d_uniq_parse_subnesteditemsappendsourcematchsubpatternappendsourceget_ord|)setappendPossible nested set at position %dnegateunterminated character set-&~|Possible set %s at position %dsymmetric differencethatPossible set difference at position %dbad character range %s-%sthe repetition number is too largemin repeat greater than max repeatunsupported quantifier %rnothing to repeatmultiple repeatunexpected end of patterngroup namebad character in group name %runknown group name %runknown extension ?Pmissing ), unterminated comment=!<=!unknown extension ? should move set optimization to compiler!# optimization# charmap optimization can't be added here because# global flags still are not known# repeat previous item# figure out which item to repeat# options# python extensions# named group: skip forward to end of name# named backreference# non-capturing group# comment# lookahead assertions# lookbehind# conditional backreference group# global flags# truncate long regexes# parse group contents# unpack non-capturing groups# Check and fix flags according to the type of pattern (str or bytes)# parse 're' pattern into list of (opcode, argument) tuples# the VERBOSE flag was switched on inside the pattern. to be# on the safe side, we'll parse the whole thing again...# parse 're' replacement string into list of literals and# group references# end of replacement string# group# The tokenizer implicitly decodes bytes objects as latin-1, we must# therefore re-encode the final representation.b'.\[{()*+?^$|'u'.\[{()*+?^$|'b'*+?{'u'*+?{'b'01234567'u'01234567'b'0123456789abcdefABCDEF'u'0123456789abcdefABCDEF'b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'b' + 'u' + 'b'\a'u'\a'b'\f'u'\f'b'\r'u'\r'b'\t'u'\t'b'\v'u'\v'b'\A'u'\A'b'\B'u'\B'b'\d'u'\d'b'\D'u'\D'b'\s'u'\s'b'\S'u'\S'b'\w'u'\w'b'\W'u'\W'b'\Z'u'\Z'b'too many groups'u'too many groups'b'redefinition of group name %r as group %d; was group %d'u'redefinition of group name %r as group %d; was group %d'b'cannot refer to an open group'u'cannot refer to an open group'b'cannot refer to group defined in the same lookbehind subpattern'u'cannot refer to group defined in the same lookbehind subpattern'b'OR'u'OR'b'ELSE'u'ELSE'b'bad escape (end of pattern)'u'bad escape (end of pattern)'b'missing 'u'missing 'b'missing %s, unterminated name'u'missing %s, unterminated name'b'incomplete escape %s'u'incomplete escape %s'b'missing {'u'missing {'b'character name'u'character name'b'undefined character name %r'u'undefined character name %r'b'\N{}'u'\N{}'b'octal escape value %s outside of range 0-0o377'u'octal escape value %s outside of range 0-0o377'b'bad escape %s'u'bad escape %s'b'invalid group reference %d'u'invalid group reference %d'b'|)'u'|)'b'Possible nested set at position %d'u'Possible nested set at position %d'b'unterminated character set'u'unterminated character set'b'-&~|'u'-&~|'b'Possible set %s at position %d'u'Possible set %s at position %d'b'difference'u'difference'b'intersection'u'intersection'b'symmetric difference'u'symmetric difference'b'union'u'union'b'Possible set difference at position %d'u'Possible set difference at position %d'b'bad character range %s-%s'u'bad character range %s-%s'b'the repetition number is too large'u'the repetition number is too large'b'min repeat greater than max repeat'u'min repeat greater than max repeat'b'unsupported quantifier %r'u'unsupported quantifier %r'b'nothing to repeat'u'nothing to repeat'b'multiple repeat'u'multiple repeat'b'unexpected end of pattern'u'unexpected end of pattern'b'group name'u'group name'b'bad character in group name %r'u'bad character in group name %r'b'unknown group name %r'u'unknown group name %r'b'unknown extension ?P'u'unknown extension ?P'b'missing ), unterminated comment'u'missing ), unterminated comment'b'=!<'u'=!<'b'=!'u'=!'b'unknown extension ?<'u'unknown extension ?<'b'missing ), unterminated subpattern'u'missing ), unterminated subpattern'b'bad group number'u'bad group number'b'conditional backref with more than two branches'u'conditional backref with more than two branches'b'Flags not at the start of the expression %r%s'u'Flags not at the start of the expression %r%s'b' (truncated)'u' (truncated)'b'unknown extension ?'u'unknown extension ?'b'unsupported special character %r'u'unsupported special character %r'b'bad inline flags: cannot use 'L' flag with a str pattern'u'bad inline flags: cannot use 'L' flag with a str pattern'b'bad inline flags: cannot use 'u' flag with a bytes pattern'u'bad inline flags: cannot use 'u' flag with a bytes pattern'b'bad inline flags: flags 'a', 'u' and 'L' are incompatible'u'bad inline flags: flags 'a', 'u' and 'L' are incompatible'b'missing -, : or )'u'missing -, : or )'b')-:'u')-:'b'unknown flag'u'unknown flag'b'bad inline flags: cannot turn on global flag'u'bad inline flags: cannot turn on global flag'b'missing flag'u'missing flag'b'bad inline flags: cannot turn off flags 'a', 'u' and 'L''u'bad inline flags: cannot turn off flags 'a', 'u' and 'L''b'missing :'u'missing :'b'bad inline flags: cannot turn off global flag'u'bad inline flags: cannot turn off global flag'b'bad inline flags: flag turned on and off'u'bad inline flags: flag turned on and off'b'cannot use LOCALE flag with a str pattern'u'cannot use LOCALE flag with a str pattern'b'ASCII and UNICODE flags are incompatible'u'ASCII and UNICODE flags are incompatible'b'cannot use UNICODE flag with a bytes pattern'u'cannot use UNICODE flag with a bytes pattern'b'ASCII and LOCALE flags are incompatible'u'ASCII and LOCALE flags are incompatible'b'unbalanced parenthesis'u'unbalanced parenthesis'b'missing <'u'missing <'u'sre_parse'This module provides some more Pythonic support for SSL. + +Object types: + + SSLSocket -- subtype of socket.socket which does SSL over the socket + +Exceptions: + + SSLError -- exception raised for I/O errors + +Functions: + + cert_time_to_seconds -- convert time string used for certificate + notBefore and notAfter functions to integer + seconds past the Epoch (the time values + returned from time.time()) + + fetch_server_certificate (HOST, PORT) -- fetch the certificate provided + by the server running on HOST at port PORT. No + validation of the certificate is performed. + +Integer constants: + +SSL_ERROR_ZERO_RETURN +SSL_ERROR_WANT_READ +SSL_ERROR_WANT_WRITE +SSL_ERROR_WANT_X509_LOOKUP +SSL_ERROR_SYSCALL +SSL_ERROR_SSL +SSL_ERROR_WANT_CONNECT + +SSL_ERROR_EOF +SSL_ERROR_INVALID_ERROR_CODE + +The following group define certificate requirements that one side is +allowing/requiring from the other side: + +CERT_NONE - no certificates from the other side are required (or will + be looked at if provided) +CERT_OPTIONAL - certificates are not required, but if provided will be + validated, and if validation fails, the connection will + also fail +CERT_REQUIRED - certificates are required, and will be validated, and + if validation fails, the connection will also fail + +The following constants identify various SSL protocol variants: + +PROTOCOL_SSLv2 +PROTOCOL_SSLv3 +PROTOCOL_SSLv23 +PROTOCOL_TLS +PROTOCOL_TLS_CLIENT +PROTOCOL_TLS_SERVER +PROTOCOL_TLSv1 +PROTOCOL_TLSv1_1 +PROTOCOL_TLSv1_2 + +The following constants identify various SSL alert message descriptions as per +http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 + +ALERT_DESCRIPTION_CLOSE_NOTIFY +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE +ALERT_DESCRIPTION_BAD_RECORD_MAC +ALERT_DESCRIPTION_RECORD_OVERFLOW +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE +ALERT_DESCRIPTION_HANDSHAKE_FAILURE +ALERT_DESCRIPTION_BAD_CERTIFICATE +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE +ALERT_DESCRIPTION_CERTIFICATE_REVOKED +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN +ALERT_DESCRIPTION_ILLEGAL_PARAMETER +ALERT_DESCRIPTION_UNKNOWN_CA +ALERT_DESCRIPTION_ACCESS_DENIED +ALERT_DESCRIPTION_DECODE_ERROR +ALERT_DESCRIPTION_DECRYPT_ERROR +ALERT_DESCRIPTION_PROTOCOL_VERSION +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY +ALERT_DESCRIPTION_INTERNAL_ERROR +ALERT_DESCRIPTION_USER_CANCELLED +ALERT_DESCRIPTION_NO_RENEGOTIATION +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE +ALERT_DESCRIPTION_UNRECOGNIZED_NAME +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY +_Enum_IntFlag_txt2obj_nid2objRAND_egd_SSLMethodPROTOCOL_OP_AlertDescriptionALERT_DESCRIPTION_SSLErrorNumberSSL_ERROR_VerifyFlagsVERIFY_VerifyModeCERT__PROTOCOL_NAMESPROTOCOL_SSLv2_SSLv2_IF_EXISTSTLSVersionMINIMUM_SUPPORTEDSSLv3TLSv1TLSv1_1TLSv1_2TLSv1_3MAXIMUM_SUPPORTED_TLSContentTypeContent types (record layer) + + See RFC 8446, section B.1 + CHANGE_CIPHER_SPECALERTHANDSHAKEAPPLICATION_DATAHEADER0x101INNER_CONTENT_TYPE_TLSAlertTypeAlert types for TLSContentType.ALERT messages + + See RFC 8466, section B.2 + CLOSE_NOTIFYUNEXPECTED_MESSAGEBAD_RECORD_MACDECRYPTION_FAILEDRECORD_OVERFLOWDECOMPRESSION_FAILUREHANDSHAKE_FAILURENO_CERTIFICATEBAD_CERTIFICATEUNSUPPORTED_CERTIFICATECERTIFICATE_REVOKEDCERTIFICATE_EXPIREDCERTIFICATE_UNKNOWNILLEGAL_PARAMETERUNKNOWN_CAACCESS_DENIEDDECODE_ERRORDECRYPT_ERROREXPORT_RESTRICTIONPROTOCOL_VERSIONINSUFFICIENT_SECURITYINAPPROPRIATE_FALLBACKUSER_CANCELEDNO_RENEGOTIATIONMISSING_EXTENSIONUNSUPPORTED_EXTENSIONCERTIFICATE_UNOBTAINABLEUNRECOGNIZED_NAMEBAD_CERTIFICATE_STATUS_RESPONSEBAD_CERTIFICATE_HASH_VALUEUNKNOWN_PSK_IDENTITYCERTIFICATE_REQUIRED120NO_APPLICATION_PROTOCOL_TLSMessageTypeMessage types (handshake protocol) + + See RFC 8446, section B.3 + HELLO_REQUESTCLIENT_HELLOSERVER_HELLOHELLO_VERIFY_REQUESTNEWSESSION_TICKETEND_OF_EARLY_DATAHELLO_RETRY_REQUESTENCRYPTED_EXTENSIONSCERTIFICATESERVER_KEY_EXCHANGECERTIFICATE_REQUESTSERVER_DONECERTIFICATE_VERIFYCLIENT_KEY_EXCHANGECERTIFICATE_URLCERTIFICATE_STATUSSUPPLEMENTAL_DATAKEY_UPDATENEXT_PROTOMESSAGE_HASH0x0101enum_certificatesenum_crlssocket_errortls-uniqueCHANNEL_BINDING_TYPESHAS_NEVER_CHECK_COMMON_NAME_RESTRICTED_SERVER_CIPHERSCertificateError_dnsname_matchMatching according to RFC 6125, section 6.4.3 + + - Hostnames are compared lower case. + - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE). + - Partial wildcards like 'www*.example.org', multiple wildcards, sole + wildcard or wildcards in labels other then the left-most label are not + supported and a CertificateError is raised. + - A wildcard must match at least one character. + too many wildcards in certificate DNS name: {!r}.dn_leftmostdn_remainderwildcard can only be present in the leftmost label: {!r}."wildcard can only be present in the leftmost label: ""{!r}."sole wildcard without additional labels are not support: {!r}."sole wildcard without additional labels are not support: "partial wildcards in leftmost label are not supported: {!r}."partial wildcards in leftmost label are not supported: "hostname_leftmosthostname_remainder_inet_patonipnameTry to convert an IP address to packed binary form + + Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6 + support. + {!r} is not a quad-dotted IPv4 address.{!r} is neither an IPv4 nor an IP6 address."{!r} is neither an IPv4 nor an IP6 ""address."{!r} is not an IPv4 address._ipaddress_matchcert_ipaddresshost_ipExact matching of IP addresses. + + RFC 6125 explicitly doesn't define an algorithm for this + (section 1.7.2 - "Out of Scope"). + ipmatch_hostnamecertVerify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed. + + The function matches IP addresses rather than dNSNames if hostname is a + valid ipaddress string. IPv4 addresses are supported on all platforms. + IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 + and inet_pton). + + CertificateError is raised on failure. On success, the function + returns nothing. + empty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIRED"empty or no certificate, match_hostname needs a ""SSL socket or SSL context with either ""CERT_OPTIONAL or CERT_REQUIRED"dnsnamessubjectAltNamesanDNSIP AddresscommonNamehostname %r doesn't match either of %s"hostname %r ""doesn't match either of %s"hostname %r doesn't match %r"doesn't match %r"no appropriate commonName or subjectAltName fields were found"no appropriate commonName or ""subjectAltName fields were found"DefaultVerifyPathscafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capath"cafile capath openssl_cafile_env openssl_cafile openssl_capath_env ""openssl_capath"Return paths to default cafile and capath. + _ASN1Objectnid shortname longname oidASN.1 object identifier lookup + oidfromnidnidCreate _ASN1Object from OpenSSL numeric ID + Create _ASN1Object from short name, long name or OID + SSLContext purpose flags with X509v3 Extended Key Usage objects + 1.3.6.1.5.5.7.3.11.3.6.1.5.5.7.3.2CLIENT_AUTHAn SSLContext holds various SSL-related configuration options and + data, such as certificates and possibly a private key.CAROOT_windows_cert_storessslsocket_classsslobject_class_encode_hostnamedo_handshake_on_connectsuppress_ragged_eofswrap_bioincomingoutgoingset_npn_protocolsnpn_protocolsprotosNPN protocols must be 1 to 255 in lengthset_servername_callbackserver_name_callbacknot a callable objectshim_cbsslobjservernamesslctxset_alpn_protocolsalpn_protocolsALPN protocols must be 1 to 255 in length_load_windows_store_certsstorenamepurposecertstrustx509_asnunable to enumerate Windows certificate storecadataload_default_certshostname_checks_common_namencsTLS message callback + + The message callback provides a debugging hook to analyze TLS + connections. The callback is called for any TLS protocol message + (header, handshake, alert, and more), but not for application data. + Due to technical limitations, the callback can't be used to filter + traffic or to abort a connection. Any exception raised in the + callback is delayed until the handshake, read, or write operation + has been performed. + + def msg_cb(conn, direction, version, content_type, msg_type, data): + pass + + conn + :class:`SSLSocket` or :class:`SSLObject` instance + direction + ``read`` or ``write`` + version + :class:`TLSVersion` enum member or int for unknown version. For a + frame header, it's the header version. + content_type + :class:`_TLSContentType` enum member or int for unsupported + content type. + msg_type + Either a :class:`_TLSContentType` enum number for a header + message, a :class:`_TLSAlertType` enum member for an alert + message, a :class:`_TLSMessageType` enum member for other + messages, or int for unsupported message types. + data + Raw, decrypted message content as bytes + is not callable.msg_typemsg_enumCreate a SSLContext object with default settings. + + NOTE: The protocol and settings may change anytime without prior + deprecation. The values represent a fair balance between maximum + compatibility and security. + SSLKEYLOGFILEkeylogfile_create_unverified_contextcert_reqsCreate a SSLContext object for Python stdlib modules + + All Python stdlib modules shall use this function to create SSLContext + objects in order to keep common settings in one place. The configuration + is less restrict than create_default_context()'s to increase backward + compatibility. + certfile must be specifiedSSLObjectThis class implements an interface on top of a low-level SSL object as + implemented by OpenSSL. This object captures the state of an SSL connection + but does not provide any network IO itself. IO needs to be performed + through separate "BIO" objects which are OpenSSL's IO abstraction layer. + + This class does not have a public constructor. Instances are returned by + ``SSLContext.wrap_bio``. This class is typically used by framework authors + that want to implement asynchronous IO for SSL through memory buffers. + + When compared to ``SSLSocket``, this object lacks the following features: + + * Any form of network IO, including methods such as ``recv`` and ``send``. + * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. + does not have a public constructor. Instances are returned by SSLContext.wrap_bio()." does not have a public ""constructor. Instances are returned by SSLContext.wrap_bio()."_sslobjThe SSLContext that is currently in use.The SSLSession for client socket.Was the client session reused during handshakeWhether this is a server-side socket.The currently set server hostname (for SNI), or ``None`` if no + server hostname is set.Read up to 'len' bytes from the SSL object and return them. + + If 'buffer' is provided, read into this buffer and return the number of + bytes read. + Write 'data' to the SSL object and return the number of bytes + written. + + The 'data' argument must support the buffer interface. + binary_formReturns a formatted version of the data in the certificate provided + by the other end of the SSL channel. + + Return None if no certificate was provided, {} if a certificate was + provided, but not validated. + selected_npn_protocolReturn the currently selected NPN protocol as a string, or ``None`` + if a next protocol was not negotiated or if NPN is not supported by one + of the peers.Return the currently selected ALPN protocol as a string, or ``None`` + if a next protocol was not negotiated or if ALPN is not supported by one + of the peers.Return the currently selected cipher as a 3-tuple ``(name, + ssl_version, secret_bits)``.Return a list of ciphers shared by the client during the handshake or + None if this is not a valid server connection. + Return the current compression algorithm in use, or ``None`` if + compression was not negotiated or not supported by one of the peers.Return the number of bytes that can be read immediately.Start the SSL/TLS handshake.Start the SSL shutdown handshake.cb_typeGet channel binding data for current connection. Raise ValueError + if the requested `cb_type` is not supported. Return bytes of the data + or None if the data is not available (e.g. before the handshake).Return a string identifying the protocol version used by the + current SSL channel. _sslcopydocCopy docstring from SSLObject to SSLSocketThis class implements a subtype of socket.socket that wraps + the underlying OS socket in an SSL context when necessary, and + provides read and write methods over that channel. does not have a public constructor. Instances are returned by SSLContext.wrap_socket()."constructor. Instances are returned by ""SSLContext.wrap_socket()."only stream sockets are supportedserver_hostname can only be specified in client mode"server_hostname can only be specified ""in client mode"session can only be specified in client mode"session can only be specified in ""client mode"check_hostname requires server_hostname_sessionconnected_connecteddo_handshake_on_connect should not be specified for non-blocking socketsCan't dup() %s instances_check_connectedRead up to LEN bytes and return them. + Return zero-length string on EOF.Read on closed or unwrapped SSL socket.Write DATA to the underlying SSL channel. Returns + number of bytes of DATA actually transmitted.Write on closed or unwrapped SSL socket.non-zero flags not allowed in calls to send() on %sflags_or_addrsendto not allowed on instances of %ssendmsg not allowed on instances of %snon-zero flags not allowed in calls to sendall() on %sSend a file, possibly by using os.sendfile() if this is a + clear-text socket. Return the total number of bytes sent. + non-zero flags not allowed in calls to recv() on %snon-zero flags not allowed in calls to recv_into() on %srecvfrom not allowed on instances of %srecvfrom_into not allowed on instances of %srecvmsg not allowed on instances of %srecvmsg_into not allowed on instances of %s"recvmsg_into not allowed on instances of "No SSL wrapper around _real_connectcan't connect in server-side modeattempt to connect already-connected SSLSocket!Connects to remote ADDR, and then wraps the connection in + an SSL channel.Accepts a new connection from a remote client, and returns + a tuple containing that new connection wrapped with a server-side + SSL channel, and the address of the remote client.newsock{0} channel binding type not implementedca_certscipherscertfile must be specified for server-side operations"certfile must be specified for server-side ""operations"cert_time_to_secondscert_timeReturn the time in seconds since the Epoch, given the timestring + representing the "notBefore" or "notAfter" date from a certificate + in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). + + "notBefore" or "notAfter" dates must use UTC (RFC 5280). + + Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + UTC should be specified as GMT (see ASN1_TIME_print()) + %d %H:%M:%S %Y GMTtime_formatmonth_numbertime data %r does not match format "%%b%s"'time data %r does not match ''format "%%b%s"'-----BEGIN CERTIFICATE-----PEM_HEADER-----END CERTIFICATE-----PEM_FOOTERDER_cert_to_PEM_certder_cert_bytesTakes a certificate in binary DER format and returns the + PEM version of it as a string.PEM_cert_to_DER_certpem_cert_stringTakes a certificate in ASCII PEM format and returns the + DER-encoded version of it as a byte sequenceInvalid PEM encoding; must start with %sInvalid PEM encoding; must end with %sget_server_certificateRetrieve the certificate from the server at the specified address, + and return it as a PEM-encoded string. + If 'ca_certs' is specified, validate the server cert against it. + If 'ssl_version' is specified, use it in the connection attempt.sslsockdercertget_protocol_nameprotocol_code# Wrapper module for _ssl, providing some additional facilities# implemented in Python. Written by Bill Janssen.# if we can't import it, let the error propagate# LibreSSL does not provide RAND_egd# pseudo content types# for DER-to-PEM translation# keep that public name in module namespace# speed up common case w/o wildcards# Only match wildcard in leftmost segment.# no right side# no partial wildcard matching# wildcard must match at least one char# inet_aton() also accepts strings like '1', '127.1', some also trailing# data like '127.0.0.1 whatever'.# not an IPv4 address# only accept injective ipnames# refuse for short IPv4 notation and additional trailing data# AF_INET6 not available# OpenSSL may add a trailing newline to a subjectAltName's IP address,# commonly woth IPv6 addresses. Strip off trailing \n.# Not an IP address (common case)# The subject is only checked when there is no dNSName entry# in subjectAltName# XXX according to RFC 2818, the most specific Common Name# must be used.# environment vars shadow paths# SSLSocket is assigned later.# SSLObject is assigned later.# SSLSocket class handles server_hostname encoding before it calls# ctx._wrap_socket()# Need to encode server_hostname here because _wrap_bio() can only# handle ASCII str.# CA certs are never PKCS#7 encoded# SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,# OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE# by default.# verify certs and host name in client mode# no explicit cafile, capath or cadata but the verify mode is# CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system# root CA certificates for the given purpose. This may fail silently.# OpenSSL 1.1.1 keylog file# load CA root certs# Used by http.client if no context is explicitly passed.# Backwards compatibility alias, even though it's not a public name.# See if we are connected# create the SSL object# non-blocking# raise an exception here if you wish to check for spurious closes# getpeername() will raise ENOTCONN if the socket is really# not connected; note that we can be connected even without# _connected being set, e.g. if connect() first returned# EAGAIN.# Ensure programs don't send data unencrypted if they try to# use this method.# os.sendfile() works with plain sockets only# Here we assume that the socket is client-side, and not# connected at the time of the call. We connect it, then wrap it.# Python does not support forward declaration of types.# some utility functions# NOTE: no month, fixed GMT# found valid month# return an integer, the previous mktime()-based implementation# returned a float (fractional seconds are always zero here).b'This module provides some more Pythonic support for SSL. + +Object types: + + SSLSocket -- subtype of socket.socket which does SSL over the socket + +Exceptions: + + SSLError -- exception raised for I/O errors + +Functions: + + cert_time_to_seconds -- convert time string used for certificate + notBefore and notAfter functions to integer + seconds past the Epoch (the time values + returned from time.time()) + + fetch_server_certificate (HOST, PORT) -- fetch the certificate provided + by the server running on HOST at port PORT. No + validation of the certificate is performed. + +Integer constants: + +SSL_ERROR_ZERO_RETURN +SSL_ERROR_WANT_READ +SSL_ERROR_WANT_WRITE +SSL_ERROR_WANT_X509_LOOKUP +SSL_ERROR_SYSCALL +SSL_ERROR_SSL +SSL_ERROR_WANT_CONNECT + +SSL_ERROR_EOF +SSL_ERROR_INVALID_ERROR_CODE + +The following group define certificate requirements that one side is +allowing/requiring from the other side: + +CERT_NONE - no certificates from the other side are required (or will + be looked at if provided) +CERT_OPTIONAL - certificates are not required, but if provided will be + validated, and if validation fails, the connection will + also fail +CERT_REQUIRED - certificates are required, and will be validated, and + if validation fails, the connection will also fail + +The following constants identify various SSL protocol variants: + +PROTOCOL_SSLv2 +PROTOCOL_SSLv3 +PROTOCOL_SSLv23 +PROTOCOL_TLS +PROTOCOL_TLS_CLIENT +PROTOCOL_TLS_SERVER +PROTOCOL_TLSv1 +PROTOCOL_TLSv1_1 +PROTOCOL_TLSv1_2 + +The following constants identify various SSL alert message descriptions as per +http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 + +ALERT_DESCRIPTION_CLOSE_NOTIFY +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE +ALERT_DESCRIPTION_BAD_RECORD_MAC +ALERT_DESCRIPTION_RECORD_OVERFLOW +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE +ALERT_DESCRIPTION_HANDSHAKE_FAILURE +ALERT_DESCRIPTION_BAD_CERTIFICATE +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE +ALERT_DESCRIPTION_CERTIFICATE_REVOKED +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN +ALERT_DESCRIPTION_ILLEGAL_PARAMETER +ALERT_DESCRIPTION_UNKNOWN_CA +ALERT_DESCRIPTION_ACCESS_DENIED +ALERT_DESCRIPTION_DECODE_ERROR +ALERT_DESCRIPTION_DECRYPT_ERROR +ALERT_DESCRIPTION_PROTOCOL_VERSION +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY +ALERT_DESCRIPTION_INTERNAL_ERROR +ALERT_DESCRIPTION_USER_CANCELLED +ALERT_DESCRIPTION_NO_RENEGOTIATION +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE +ALERT_DESCRIPTION_UNRECOGNIZED_NAME +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY +'u'This module provides some more Pythonic support for SSL. + +Object types: + + SSLSocket -- subtype of socket.socket which does SSL over the socket + +Exceptions: + + SSLError -- exception raised for I/O errors + +Functions: + + cert_time_to_seconds -- convert time string used for certificate + notBefore and notAfter functions to integer + seconds past the Epoch (the time values + returned from time.time()) + + fetch_server_certificate (HOST, PORT) -- fetch the certificate provided + by the server running on HOST at port PORT. No + validation of the certificate is performed. + +Integer constants: + +SSL_ERROR_ZERO_RETURN +SSL_ERROR_WANT_READ +SSL_ERROR_WANT_WRITE +SSL_ERROR_WANT_X509_LOOKUP +SSL_ERROR_SYSCALL +SSL_ERROR_SSL +SSL_ERROR_WANT_CONNECT + +SSL_ERROR_EOF +SSL_ERROR_INVALID_ERROR_CODE + +The following group define certificate requirements that one side is +allowing/requiring from the other side: + +CERT_NONE - no certificates from the other side are required (or will + be looked at if provided) +CERT_OPTIONAL - certificates are not required, but if provided will be + validated, and if validation fails, the connection will + also fail +CERT_REQUIRED - certificates are required, and will be validated, and + if validation fails, the connection will also fail + +The following constants identify various SSL protocol variants: + +PROTOCOL_SSLv2 +PROTOCOL_SSLv3 +PROTOCOL_SSLv23 +PROTOCOL_TLS +PROTOCOL_TLS_CLIENT +PROTOCOL_TLS_SERVER +PROTOCOL_TLSv1 +PROTOCOL_TLSv1_1 +PROTOCOL_TLSv1_2 + +The following constants identify various SSL alert message descriptions as per +http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 + +ALERT_DESCRIPTION_CLOSE_NOTIFY +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE +ALERT_DESCRIPTION_BAD_RECORD_MAC +ALERT_DESCRIPTION_RECORD_OVERFLOW +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE +ALERT_DESCRIPTION_HANDSHAKE_FAILURE +ALERT_DESCRIPTION_BAD_CERTIFICATE +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE +ALERT_DESCRIPTION_CERTIFICATE_REVOKED +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN +ALERT_DESCRIPTION_ILLEGAL_PARAMETER +ALERT_DESCRIPTION_UNKNOWN_CA +ALERT_DESCRIPTION_ACCESS_DENIED +ALERT_DESCRIPTION_DECODE_ERROR +ALERT_DESCRIPTION_DECRYPT_ERROR +ALERT_DESCRIPTION_PROTOCOL_VERSION +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY +ALERT_DESCRIPTION_INTERNAL_ERROR +ALERT_DESCRIPTION_USER_CANCELLED +ALERT_DESCRIPTION_NO_RENEGOTIATION +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE +ALERT_DESCRIPTION_UNRECOGNIZED_NAME +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY +'b'_SSLMethod'u'_SSLMethod'b'PROTOCOL_'u'PROTOCOL_'b'PROTOCOL_SSLv23'u'PROTOCOL_SSLv23'b'OP_'u'OP_'b'AlertDescription'u'AlertDescription'b'ALERT_DESCRIPTION_'u'ALERT_DESCRIPTION_'b'SSLErrorNumber'u'SSLErrorNumber'b'SSL_ERROR_'u'SSL_ERROR_'b'VerifyFlags'u'VerifyFlags'b'VERIFY_'u'VERIFY_'b'VerifyMode'u'VerifyMode'b'CERT_'u'CERT_'b'PROTOCOL_SSLv2'u'PROTOCOL_SSLv2'b'Content types (record layer) + + See RFC 8446, section B.1 + 'u'Content types (record layer) + + See RFC 8446, section B.1 + 'b'Alert types for TLSContentType.ALERT messages + + See RFC 8466, section B.2 + 'u'Alert types for TLSContentType.ALERT messages + + See RFC 8466, section B.2 + 'b'Message types (handshake protocol) + + See RFC 8446, section B.3 + 'u'Message types (handshake protocol) + + See RFC 8446, section B.3 + 'b'tls-unique'u'tls-unique'b'HOSTFLAG_NEVER_CHECK_SUBJECT'u'HOSTFLAG_NEVER_CHECK_SUBJECT'b'Matching according to RFC 6125, section 6.4.3 + + - Hostnames are compared lower case. + - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE). + - Partial wildcards like 'www*.example.org', multiple wildcards, sole + wildcard or wildcards in labels other then the left-most label are not + supported and a CertificateError is raised. + - A wildcard must match at least one character. + 'u'Matching according to RFC 6125, section 6.4.3 + + - Hostnames are compared lower case. + - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE). + - Partial wildcards like 'www*.example.org', multiple wildcards, sole + wildcard or wildcards in labels other then the left-most label are not + supported and a CertificateError is raised. + - A wildcard must match at least one character. + 'b'too many wildcards in certificate DNS name: {!r}.'u'too many wildcards in certificate DNS name: {!r}.'b'wildcard can only be present in the leftmost label: {!r}.'u'wildcard can only be present in the leftmost label: {!r}.'b'sole wildcard without additional labels are not support: {!r}.'u'sole wildcard without additional labels are not support: {!r}.'b'partial wildcards in leftmost label are not supported: {!r}.'u'partial wildcards in leftmost label are not supported: {!r}.'b'Try to convert an IP address to packed binary form + + Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6 + support. + 'u'Try to convert an IP address to packed binary form + + Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6 + support. + 'b'{!r} is not a quad-dotted IPv4 address.'u'{!r} is not a quad-dotted IPv4 address.'b'{!r} is neither an IPv4 nor an IP6 address.'u'{!r} is neither an IPv4 nor an IP6 address.'b'{!r} is not an IPv4 address.'u'{!r} is not an IPv4 address.'b'Exact matching of IP addresses. + + RFC 6125 explicitly doesn't define an algorithm for this + (section 1.7.2 - "Out of Scope"). + 'u'Exact matching of IP addresses. + + RFC 6125 explicitly doesn't define an algorithm for this + (section 1.7.2 - "Out of Scope"). + 'b'Verify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed. + + The function matches IP addresses rather than dNSNames if hostname is a + valid ipaddress string. IPv4 addresses are supported on all platforms. + IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 + and inet_pton). + + CertificateError is raised on failure. On success, the function + returns nothing. + 'u'Verify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed. + + The function matches IP addresses rather than dNSNames if hostname is a + valid ipaddress string. IPv4 addresses are supported on all platforms. + IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 + and inet_pton). + + CertificateError is raised on failure. On success, the function + returns nothing. + 'b'empty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIRED'u'empty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIRED'b'subjectAltName'u'subjectAltName'b'DNS'u'DNS'b'IP Address'u'IP Address'b'commonName'u'commonName'b'hostname %r doesn't match either of %s'u'hostname %r doesn't match either of %s'b'hostname %r doesn't match %r'u'hostname %r doesn't match %r'b'no appropriate commonName or subjectAltName fields were found'u'no appropriate commonName or subjectAltName fields were found'b'DefaultVerifyPaths'u'DefaultVerifyPaths'b'cafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capath'u'cafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capath'b'Return paths to default cafile and capath. + 'u'Return paths to default cafile and capath. + 'b'_ASN1Object'u'_ASN1Object'b'nid shortname longname oid'u'nid shortname longname oid'b'ASN.1 object identifier lookup + 'u'ASN.1 object identifier lookup + 'b'Create _ASN1Object from OpenSSL numeric ID + 'u'Create _ASN1Object from OpenSSL numeric ID + 'b'Create _ASN1Object from short name, long name or OID + 'u'Create _ASN1Object from short name, long name or OID + 'b'SSLContext purpose flags with X509v3 Extended Key Usage objects + 'u'SSLContext purpose flags with X509v3 Extended Key Usage objects + 'b'1.3.6.1.5.5.7.3.1'u'1.3.6.1.5.5.7.3.1'b'1.3.6.1.5.5.7.3.2'u'1.3.6.1.5.5.7.3.2'b'An SSLContext holds various SSL-related configuration options and + data, such as certificates and possibly a private key.'u'An SSLContext holds various SSL-related configuration options and + data, such as certificates and possibly a private key.'b'CA'u'CA'b'ROOT'u'ROOT'b'NPN protocols must be 1 to 255 in length'u'NPN protocols must be 1 to 255 in length'b'not a callable object'u'not a callable object'b'ALPN protocols must be 1 to 255 in length'u'ALPN protocols must be 1 to 255 in length'b'x509_asn'u'x509_asn'b'unable to enumerate Windows certificate store'u'unable to enumerate Windows certificate store'b'minimum_version'u'minimum_version'b'TLS message callback + + The message callback provides a debugging hook to analyze TLS + connections. The callback is called for any TLS protocol message + (header, handshake, alert, and more), but not for application data. + Due to technical limitations, the callback can't be used to filter + traffic or to abort a connection. Any exception raised in the + callback is delayed until the handshake, read, or write operation + has been performed. + + def msg_cb(conn, direction, version, content_type, msg_type, data): + pass + + conn + :class:`SSLSocket` or :class:`SSLObject` instance + direction + ``read`` or ``write`` + version + :class:`TLSVersion` enum member or int for unknown version. For a + frame header, it's the header version. + content_type + :class:`_TLSContentType` enum member or int for unsupported + content type. + msg_type + Either a :class:`_TLSContentType` enum number for a header + message, a :class:`_TLSAlertType` enum member for an alert + message, a :class:`_TLSMessageType` enum member for other + messages, or int for unsupported message types. + data + Raw, decrypted message content as bytes + 'u'TLS message callback + + The message callback provides a debugging hook to analyze TLS + connections. The callback is called for any TLS protocol message + (header, handshake, alert, and more), but not for application data. + Due to technical limitations, the callback can't be used to filter + traffic or to abort a connection. Any exception raised in the + callback is delayed until the handshake, read, or write operation + has been performed. + + def msg_cb(conn, direction, version, content_type, msg_type, data): + pass + + conn + :class:`SSLSocket` or :class:`SSLObject` instance + direction + ``read`` or ``write`` + version + :class:`TLSVersion` enum member or int for unknown version. For a + frame header, it's the header version. + content_type + :class:`_TLSContentType` enum member or int for unsupported + content type. + msg_type + Either a :class:`_TLSContentType` enum number for a header + message, a :class:`_TLSAlertType` enum member for an alert + message, a :class:`_TLSMessageType` enum member for other + messages, or int for unsupported message types. + data + Raw, decrypted message content as bytes + 'b' is not callable.'u' is not callable.'b'Create a SSLContext object with default settings. + + NOTE: The protocol and settings may change anytime without prior + deprecation. The values represent a fair balance between maximum + compatibility and security. + 'u'Create a SSLContext object with default settings. + + NOTE: The protocol and settings may change anytime without prior + deprecation. The values represent a fair balance between maximum + compatibility and security. + 'b'keylog_filename'u'keylog_filename'b'SSLKEYLOGFILE'u'SSLKEYLOGFILE'b'Create a SSLContext object for Python stdlib modules + + All Python stdlib modules shall use this function to create SSLContext + objects in order to keep common settings in one place. The configuration + is less restrict than create_default_context()'s to increase backward + compatibility. + 'u'Create a SSLContext object for Python stdlib modules + + All Python stdlib modules shall use this function to create SSLContext + objects in order to keep common settings in one place. The configuration + is less restrict than create_default_context()'s to increase backward + compatibility. + 'b'certfile must be specified'u'certfile must be specified'b'This class implements an interface on top of a low-level SSL object as + implemented by OpenSSL. This object captures the state of an SSL connection + but does not provide any network IO itself. IO needs to be performed + through separate "BIO" objects which are OpenSSL's IO abstraction layer. + + This class does not have a public constructor. Instances are returned by + ``SSLContext.wrap_bio``. This class is typically used by framework authors + that want to implement asynchronous IO for SSL through memory buffers. + + When compared to ``SSLSocket``, this object lacks the following features: + + * Any form of network IO, including methods such as ``recv`` and ``send``. + * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. + 'u'This class implements an interface on top of a low-level SSL object as + implemented by OpenSSL. This object captures the state of an SSL connection + but does not provide any network IO itself. IO needs to be performed + through separate "BIO" objects which are OpenSSL's IO abstraction layer. + + This class does not have a public constructor. Instances are returned by + ``SSLContext.wrap_bio``. This class is typically used by framework authors + that want to implement asynchronous IO for SSL through memory buffers. + + When compared to ``SSLSocket``, this object lacks the following features: + + * Any form of network IO, including methods such as ``recv`` and ``send``. + * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. + 'b' does not have a public constructor. Instances are returned by SSLContext.wrap_bio().'u' does not have a public constructor. Instances are returned by SSLContext.wrap_bio().'b'The SSLContext that is currently in use.'u'The SSLContext that is currently in use.'b'The SSLSession for client socket.'u'The SSLSession for client socket.'b'Was the client session reused during handshake'u'Was the client session reused during handshake'b'Whether this is a server-side socket.'b'The currently set server hostname (for SNI), or ``None`` if no + server hostname is set.'u'The currently set server hostname (for SNI), or ``None`` if no + server hostname is set.'b'Read up to 'len' bytes from the SSL object and return them. + + If 'buffer' is provided, read into this buffer and return the number of + bytes read. + 'u'Read up to 'len' bytes from the SSL object and return them. + + If 'buffer' is provided, read into this buffer and return the number of + bytes read. + 'b'Write 'data' to the SSL object and return the number of bytes + written. + + The 'data' argument must support the buffer interface. + 'u'Write 'data' to the SSL object and return the number of bytes + written. + + The 'data' argument must support the buffer interface. + 'b'Returns a formatted version of the data in the certificate provided + by the other end of the SSL channel. + + Return None if no certificate was provided, {} if a certificate was + provided, but not validated. + 'u'Returns a formatted version of the data in the certificate provided + by the other end of the SSL channel. + + Return None if no certificate was provided, {} if a certificate was + provided, but not validated. + 'b'Return the currently selected NPN protocol as a string, or ``None`` + if a next protocol was not negotiated or if NPN is not supported by one + of the peers.'u'Return the currently selected NPN protocol as a string, or ``None`` + if a next protocol was not negotiated or if NPN is not supported by one + of the peers.'b'Return the currently selected ALPN protocol as a string, or ``None`` + if a next protocol was not negotiated or if ALPN is not supported by one + of the peers.'u'Return the currently selected ALPN protocol as a string, or ``None`` + if a next protocol was not negotiated or if ALPN is not supported by one + of the peers.'b'Return the currently selected cipher as a 3-tuple ``(name, + ssl_version, secret_bits)``.'u'Return the currently selected cipher as a 3-tuple ``(name, + ssl_version, secret_bits)``.'b'Return a list of ciphers shared by the client during the handshake or + None if this is not a valid server connection. + 'u'Return a list of ciphers shared by the client during the handshake or + None if this is not a valid server connection. + 'b'Return the current compression algorithm in use, or ``None`` if + compression was not negotiated or not supported by one of the peers.'u'Return the current compression algorithm in use, or ``None`` if + compression was not negotiated or not supported by one of the peers.'b'Return the number of bytes that can be read immediately.'u'Return the number of bytes that can be read immediately.'b'Start the SSL/TLS handshake.'u'Start the SSL/TLS handshake.'b'Start the SSL shutdown handshake.'u'Start the SSL shutdown handshake.'b'Get channel binding data for current connection. Raise ValueError + if the requested `cb_type` is not supported. Return bytes of the data + or None if the data is not available (e.g. before the handshake).'u'Get channel binding data for current connection. Raise ValueError + if the requested `cb_type` is not supported. Return bytes of the data + or None if the data is not available (e.g. before the handshake).'b'Return a string identifying the protocol version used by the + current SSL channel. 'u'Return a string identifying the protocol version used by the + current SSL channel. 'b'Copy docstring from SSLObject to SSLSocket'u'Copy docstring from SSLObject to SSLSocket'b'This class implements a subtype of socket.socket that wraps + the underlying OS socket in an SSL context when necessary, and + provides read and write methods over that channel. 'u'This class implements a subtype of socket.socket that wraps + the underlying OS socket in an SSL context when necessary, and + provides read and write methods over that channel. 'b' does not have a public constructor. Instances are returned by SSLContext.wrap_socket().'u' does not have a public constructor. Instances are returned by SSLContext.wrap_socket().'b'only stream sockets are supported'u'only stream sockets are supported'b'server_hostname can only be specified in client mode'u'server_hostname can only be specified in client mode'b'session can only be specified in client mode'u'session can only be specified in client mode'b'check_hostname requires server_hostname'u'check_hostname requires server_hostname'b'do_handshake_on_connect should not be specified for non-blocking sockets'u'do_handshake_on_connect should not be specified for non-blocking sockets'b'Can't dup() %s instances'u'Can't dup() %s instances'b'Read up to LEN bytes and return them. + Return zero-length string on EOF.'u'Read up to LEN bytes and return them. + Return zero-length string on EOF.'b'Read on closed or unwrapped SSL socket.'u'Read on closed or unwrapped SSL socket.'b'Write DATA to the underlying SSL channel. Returns + number of bytes of DATA actually transmitted.'u'Write DATA to the underlying SSL channel. Returns + number of bytes of DATA actually transmitted.'b'Write on closed or unwrapped SSL socket.'u'Write on closed or unwrapped SSL socket.'b'non-zero flags not allowed in calls to send() on %s'u'non-zero flags not allowed in calls to send() on %s'b'sendto not allowed on instances of %s'u'sendto not allowed on instances of %s'b'sendmsg not allowed on instances of %s'u'sendmsg not allowed on instances of %s'b'non-zero flags not allowed in calls to sendall() on %s'u'non-zero flags not allowed in calls to sendall() on %s'b'Send a file, possibly by using os.sendfile() if this is a + clear-text socket. Return the total number of bytes sent. + 'u'Send a file, possibly by using os.sendfile() if this is a + clear-text socket. Return the total number of bytes sent. + 'b'non-zero flags not allowed in calls to recv() on %s'u'non-zero flags not allowed in calls to recv() on %s'b'non-zero flags not allowed in calls to recv_into() on %s'u'non-zero flags not allowed in calls to recv_into() on %s'b'recvfrom not allowed on instances of %s'u'recvfrom not allowed on instances of %s'b'recvfrom_into not allowed on instances of %s'u'recvfrom_into not allowed on instances of %s'b'recvmsg not allowed on instances of %s'u'recvmsg not allowed on instances of %s'b'recvmsg_into not allowed on instances of %s'u'recvmsg_into not allowed on instances of %s'b'No SSL wrapper around 'u'No SSL wrapper around 'b'can't connect in server-side mode'u'can't connect in server-side mode'b'attempt to connect already-connected SSLSocket!'u'attempt to connect already-connected SSLSocket!'b'Connects to remote ADDR, and then wraps the connection in + an SSL channel.'u'Connects to remote ADDR, and then wraps the connection in + an SSL channel.'b'Accepts a new connection from a remote client, and returns + a tuple containing that new connection wrapped with a server-side + SSL channel, and the address of the remote client.'u'Accepts a new connection from a remote client, and returns + a tuple containing that new connection wrapped with a server-side + SSL channel, and the address of the remote client.'b'{0} channel binding type not implemented'u'{0} channel binding type not implemented'b'certfile must be specified for server-side operations'u'certfile must be specified for server-side operations'b'Return the time in seconds since the Epoch, given the timestring + representing the "notBefore" or "notAfter" date from a certificate + in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). + + "notBefore" or "notAfter" dates must use UTC (RFC 5280). + + Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + UTC should be specified as GMT (see ASN1_TIME_print()) + 'u'Return the time in seconds since the Epoch, given the timestring + representing the "notBefore" or "notAfter" date from a certificate + in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). + + "notBefore" or "notAfter" dates must use UTC (RFC 5280). + + Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec + UTC should be specified as GMT (see ASN1_TIME_print()) + 'b' %d %H:%M:%S %Y GMT'u' %d %H:%M:%S %Y GMT'b'time data %r does not match format "%%b%s"'u'time data %r does not match format "%%b%s"'b'-----BEGIN CERTIFICATE-----'u'-----BEGIN CERTIFICATE-----'b'-----END CERTIFICATE-----'u'-----END CERTIFICATE-----'b'Takes a certificate in binary DER format and returns the + PEM version of it as a string.'u'Takes a certificate in binary DER format and returns the + PEM version of it as a string.'b'Takes a certificate in ASCII PEM format and returns the + DER-encoded version of it as a byte sequence'u'Takes a certificate in ASCII PEM format and returns the + DER-encoded version of it as a byte sequence'b'Invalid PEM encoding; must start with %s'u'Invalid PEM encoding; must start with %s'b'Invalid PEM encoding; must end with %s'u'Invalid PEM encoding; must end with %s'b'Retrieve the certificate from the server at the specified address, + and return it as a PEM-encoded string. + If 'ca_certs' is specified, validate the server cert against it. + If 'ssl_version' is specified, use it in the connection attempt.'u'Retrieve the certificate from the server at the specified address, + and return it as a PEM-encoded string. + If 'ca_certs' is specified, validate the server cert against it. + If 'ssl_version' is specified, use it in the connection attempt.'_create_transport_contextServer side SSL needs a valid SSLContextUNWRAPPED_UNWRAPPEDDO_HANDSHAKE_DO_HANDSHAKEWRAPPED_WRAPPEDSHUTDOWN_SHUTDOWN_SSLPipeAn SSL "Pipe". + + An SSL pipe allows you to communicate with an SSL/TLS protocol instance + through memory buffers. It can be used to implement a security layer for an + existing connection where you don't have access to the connection's file + descriptor, or for some reason you don't want to use it. + + An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode, + data is passed through untransformed. In wrapped mode, application level + data is encrypted to SSL record level data and vice versa. The SSL record + level is the lowest level in the SSL protocol suite and is what travels + as-is over the wire. + + An SslPipe initially is in "unwrapped" mode. To start SSL, call + do_handshake(). To shutdown SSL again, call unwrap(). + + The *context* argument specifies the ssl.SSLContext to use. + + The *server_side* argument indicates whether this is a server side or + client side transport. + + The optional *server_hostname* argument can be used to specify the + hostname you are connecting to. You may only specify this parameter if + the _ssl module supports Server Name Indication (SNI). + _server_side_server_hostname_incoming_outgoing_need_ssldata_handshake_cb_shutdown_cbThe SSL context passed to the constructor.ssl_objectThe internal ssl.SSLObject instance. + + Return None if the pipe is not wrapped. + need_ssldataWhether more record level data is needed to complete a handshake + that is currently in progress. + Whether a security layer is currently in effect. + + Return False during handshake. + Start the SSL handshake. + + Return a list of ssldata. A ssldata element is a list of buffers + + The optional *callback* argument can be used to install a callback that + will be called when the handshake is complete. The callback will be + called with None if successful, else an exception instance. + handshake in progress or completedfeed_ssldataonly_handshakessldataappdataStart the SSL shutdown sequence. + + Return a list of ssldata. A ssldata element is a list of buffers + + The optional *callback* argument can be used to install a callback that + will be called when the shutdown is complete. The callback will be + called without arguments. + no security layer presentshutdown in progressfeed_eofSend a potentially "ragged" EOF. + + This method will raise an SSL_ERROR_EOF exception if the EOF is + unexpected. + Feed SSL record level data into the pipe. + + The data must be a bytes instance. It is OK to send an empty bytes + instance. This can be used to get ssldata for a handshake initiated by + this endpoint. + + Return a (ssldata, appdata) tuple. The ssldata element is a list of + buffers containing SSL data that needs to be sent to the remote SSL. + + The appdata element is a list of buffers containing plaintext data that + needs to be forwarded to the application. The appdata list may contain + an empty buffer indicating an SSL "close_notify" alert. This alert must + be acknowledged by calling shutdown(). + exc_errnofeed_appdataFeed plaintext data into the pipe. + + Return an (ssldata, offset) tuple. The ssldata element is a list of + buffers containing record level data that needs to be sent to the + remote SSL instance. The offset is the number of plaintext bytes that + were processed, which may be less than the length of data. + + NOTE: In case of short writes, this call MUST be retried with the SAME + buffer passed into the *data* argument (i.e. the id() must be the + same). This is an OpenSSL requirement. A further particularity is that + a short write will always have offset == 0, because the _ssl module + does not enable partial writes. And even though the offset is zero, + there will still be encrypted data in ssldata. + PROTOCOL_IS_SHUTDOWN_SSLProtocolTransport_ssl_protocolGet optional transport information._get_extra_info_set_app_protocol_app_protocolClose the transport. + + Buffered data will be flushed asynchronously. No more data + will be received. After all buffered data is flushed, the + protocol's connection_lost() method will (eventually) called + with None as its argument. + _start_shutdownSSL transport has not been initialized yetPause the receiving end. + + No data will be passed to the protocol's data_received() + method until resume_reading() is called. + Resume the receiving end. + + Data received will once again be passed to the protocol's + data_received() method. + set_write_buffer_limitsSet the high- and low-water limits for write flow control. + + These two values control when to call the protocol's + pause_writing() and resume_writing() methods. If specified, + the low-water limit must be less than or equal to the + high-water limit. Neither value can be negative. + + The defaults are implementation-specific. If only the + high-water limit is given, the low-water limit defaults to an + implementation-specific value less than or equal to the + high-water limit. Setting high to zero forces low to zero as + well, and causes pause_writing() to be called whenever the + buffer becomes non-empty. Setting low to zero causes + resume_writing() to be called only once the buffer is empty. + Use of zero for either limit is generally sub-optimal as it + reduces opportunities for doing I/O and computation + concurrently. + Return the current size of the write buffer.Write some data bytes to the transport. + + This does not block; it buffers the data and arranges for it + to be sent out asynchronously. + data: expecting a bytes-like instance, got "data: expecting a bytes-like instance, ""got "_write_appdataReturn True if this transport supports write_eof(), False if not.Close the transport immediately. + + Buffered data will be lost. No more data will be received. + The protocol's connection_lost() method will (eventually) be + called with None as its argument. + _abortSSL protocol. + + Implementation of SSL on top of a socket using incoming and outgoing + buffers which are ssl.MemoryBIO objects. + app_protocolstdlib ssl module not availablessl_handshake_timeout should be a positive number, got "ssl_handshake_timeout should be a positive number, "_sslcontext_write_backlog_write_buffer_size_waiter_sslpipe_session_established_in_handshake_in_shutdown_call_connection_made_app_protocol_is_buffer_wakeup_waiterCalled when the low-level connection is made. + + Start the SSL handshake. + _start_handshakeCalled when the low-level connection is lost or closed. + + The argument is an exception object or None (the latter + meaning a regular EOF is received or the connection was + aborted or closed). + _handshake_timeout_handleCalled when the low-level transport's buffer goes over + the high-water mark. + Called when the low-level transport's buffer drains below + the low-water mark. + Called when some SSL data is received. + + The argument is a bytes object. + SSL error in data receivedapplication protocol failed to receive SSL dataCalled when the other end of the low-level stream + is half-closed. + + If this returns a false value (including None), the transport + will close itself. If it returns a true value, closing the + transport is up to the protocol. + returning true from eof_received() has no effect when using ssl'returning true from eof_received() ''has no effect when using ssl'_process_write_backlog%r starts SSL handshake_handshake_start_time_check_handshake_timeoutSSL handshake is taking longer than "SSL handshake is taking longer than " seconds: aborting the connection" seconds: ""aborting the connection"_on_handshake_completehandshake_excpeercertSSL handshake failed on verifying the certificateSSL handshake failed%r: SSL handshake took %.1f ms_finalizeFatal error on SSL transport# Client side may pass ssl=True to use a default# context; in that case the sslcontext passed is None.# The default is secure for client connections.# Python 3.4+: use up-to-date strong settings.# States of an _SSLPipe.# Buffer size passed to read()# If unwrapped, pass plaintext data straight through.# Call do_handshake() until it doesn't raise anymore.# Handshake done: execute the wrapped block# Main state: read data from SSL until close_notify# close_notify# Call shutdown() until it doesn't raise anymore.# Drain possible plaintext data after close_notify.# Check for record level data that needs to be sent back.# Happens for the initial handshake and renegotiations.# pass through data in unwrapped mode# It is not allowed to call write() after unwrap() until the# close_notify is acknowledged. We return the condition to the# caller as a short write.# See if there's any record level data back for us.# SSLProtocol instance# Required for sendfile fallback pause_writing/resume_writing logic# SSL-specific extra info. More info are set when the handshake# completes.# App data write buffering# _SSLPipe instance (None until the connection is made)# transport, ex: SelectorSocketTransport# Most likely an exception occurred while in SSL handshake.# Just mark the app transport as closed so that its __del__# doesn't complain.# transport closing, sslpipe is destroyed# (b'', 1) is a special value in _process_write_backlog() to do# the SSL handshake# Add extra info that becomes available after handshake.# In case transport.write() was already called. Don't call# immediately _process_write_backlog(), but schedule it:# _on_handshake_complete() can be called indirectly from# _process_write_backlog(), and _process_write_backlog() is not# reentrant.# Try to make progress on the write backlog.# A short write means that a write is blocked on a read# We need to enable reading if it is paused!# An entire chunk from the backlog was processed. We can# delete it and reduce the outstanding buffer size.# Exceptions will be re-raised in _on_handshake_complete.b'Server side SSL needs a valid SSLContext'u'Server side SSL needs a valid SSLContext'b'UNWRAPPED'u'UNWRAPPED'b'DO_HANDSHAKE'u'DO_HANDSHAKE'b'WRAPPED'u'WRAPPED'b'SHUTDOWN'u'SHUTDOWN'b'An SSL "Pipe". + + An SSL pipe allows you to communicate with an SSL/TLS protocol instance + through memory buffers. It can be used to implement a security layer for an + existing connection where you don't have access to the connection's file + descriptor, or for some reason you don't want to use it. + + An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode, + data is passed through untransformed. In wrapped mode, application level + data is encrypted to SSL record level data and vice versa. The SSL record + level is the lowest level in the SSL protocol suite and is what travels + as-is over the wire. + + An SslPipe initially is in "unwrapped" mode. To start SSL, call + do_handshake(). To shutdown SSL again, call unwrap(). + 'u'An SSL "Pipe". + + An SSL pipe allows you to communicate with an SSL/TLS protocol instance + through memory buffers. It can be used to implement a security layer for an + existing connection where you don't have access to the connection's file + descriptor, or for some reason you don't want to use it. + + An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode, + data is passed through untransformed. In wrapped mode, application level + data is encrypted to SSL record level data and vice versa. The SSL record + level is the lowest level in the SSL protocol suite and is what travels + as-is over the wire. + + An SslPipe initially is in "unwrapped" mode. To start SSL, call + do_handshake(). To shutdown SSL again, call unwrap(). + 'b' + The *context* argument specifies the ssl.SSLContext to use. + + The *server_side* argument indicates whether this is a server side or + client side transport. + + The optional *server_hostname* argument can be used to specify the + hostname you are connecting to. You may only specify this parameter if + the _ssl module supports Server Name Indication (SNI). + 'u' + The *context* argument specifies the ssl.SSLContext to use. + + The *server_side* argument indicates whether this is a server side or + client side transport. + + The optional *server_hostname* argument can be used to specify the + hostname you are connecting to. You may only specify this parameter if + the _ssl module supports Server Name Indication (SNI). + 'b'The SSL context passed to the constructor.'u'The SSL context passed to the constructor.'b'The internal ssl.SSLObject instance. + + Return None if the pipe is not wrapped. + 'u'The internal ssl.SSLObject instance. + + Return None if the pipe is not wrapped. + 'b'Whether more record level data is needed to complete a handshake + that is currently in progress.'u'Whether more record level data is needed to complete a handshake + that is currently in progress.'b' + Whether a security layer is currently in effect. + + Return False during handshake. + 'u' + Whether a security layer is currently in effect. + + Return False during handshake. + 'b'Start the SSL handshake. + + Return a list of ssldata. A ssldata element is a list of buffers + + The optional *callback* argument can be used to install a callback that + will be called when the handshake is complete. The callback will be + called with None if successful, else an exception instance. + 'u'Start the SSL handshake. + + Return a list of ssldata. A ssldata element is a list of buffers + + The optional *callback* argument can be used to install a callback that + will be called when the handshake is complete. The callback will be + called with None if successful, else an exception instance. + 'b'handshake in progress or completed'u'handshake in progress or completed'b'Start the SSL shutdown sequence. + + Return a list of ssldata. A ssldata element is a list of buffers + + The optional *callback* argument can be used to install a callback that + will be called when the shutdown is complete. The callback will be + called without arguments. + 'u'Start the SSL shutdown sequence. + + Return a list of ssldata. A ssldata element is a list of buffers + + The optional *callback* argument can be used to install a callback that + will be called when the shutdown is complete. The callback will be + called without arguments. + 'b'no security layer present'u'no security layer present'b'shutdown in progress'u'shutdown in progress'b'Send a potentially "ragged" EOF. + + This method will raise an SSL_ERROR_EOF exception if the EOF is + unexpected. + 'u'Send a potentially "ragged" EOF. + + This method will raise an SSL_ERROR_EOF exception if the EOF is + unexpected. + 'b'Feed SSL record level data into the pipe. + + The data must be a bytes instance. It is OK to send an empty bytes + instance. This can be used to get ssldata for a handshake initiated by + this endpoint. + + Return a (ssldata, appdata) tuple. The ssldata element is a list of + buffers containing SSL data that needs to be sent to the remote SSL. + + The appdata element is a list of buffers containing plaintext data that + needs to be forwarded to the application. The appdata list may contain + an empty buffer indicating an SSL "close_notify" alert. This alert must + be acknowledged by calling shutdown(). + 'u'Feed SSL record level data into the pipe. + + The data must be a bytes instance. It is OK to send an empty bytes + instance. This can be used to get ssldata for a handshake initiated by + this endpoint. + + Return a (ssldata, appdata) tuple. The ssldata element is a list of + buffers containing SSL data that needs to be sent to the remote SSL. + + The appdata element is a list of buffers containing plaintext data that + needs to be forwarded to the application. The appdata list may contain + an empty buffer indicating an SSL "close_notify" alert. This alert must + be acknowledged by calling shutdown(). + 'b'Feed plaintext data into the pipe. + + Return an (ssldata, offset) tuple. The ssldata element is a list of + buffers containing record level data that needs to be sent to the + remote SSL instance. The offset is the number of plaintext bytes that + were processed, which may be less than the length of data. + + NOTE: In case of short writes, this call MUST be retried with the SAME + buffer passed into the *data* argument (i.e. the id() must be the + same). This is an OpenSSL requirement. A further particularity is that + a short write will always have offset == 0, because the _ssl module + does not enable partial writes. And even though the offset is zero, + there will still be encrypted data in ssldata. + 'u'Feed plaintext data into the pipe. + + Return an (ssldata, offset) tuple. The ssldata element is a list of + buffers containing record level data that needs to be sent to the + remote SSL instance. The offset is the number of plaintext bytes that + were processed, which may be less than the length of data. + + NOTE: In case of short writes, this call MUST be retried with the SAME + buffer passed into the *data* argument (i.e. the id() must be the + same). This is an OpenSSL requirement. A further particularity is that + a short write will always have offset == 0, because the _ssl module + does not enable partial writes. And even though the offset is zero, + there will still be encrypted data in ssldata. + 'b'PROTOCOL_IS_SHUTDOWN'u'PROTOCOL_IS_SHUTDOWN'b'Get optional transport information.'u'Get optional transport information.'b'Close the transport. + + Buffered data will be flushed asynchronously. No more data + will be received. After all buffered data is flushed, the + protocol's connection_lost() method will (eventually) called + with None as its argument. + 'u'Close the transport. + + Buffered data will be flushed asynchronously. No more data + will be received. After all buffered data is flushed, the + protocol's connection_lost() method will (eventually) called + with None as its argument. + 'b'SSL transport has not been initialized yet'u'SSL transport has not been initialized yet'b'Pause the receiving end. + + No data will be passed to the protocol's data_received() + method until resume_reading() is called. + 'u'Pause the receiving end. + + No data will be passed to the protocol's data_received() + method until resume_reading() is called. + 'b'Resume the receiving end. + + Data received will once again be passed to the protocol's + data_received() method. + 'u'Resume the receiving end. + + Data received will once again be passed to the protocol's + data_received() method. + 'b'Set the high- and low-water limits for write flow control. + + These two values control when to call the protocol's + pause_writing() and resume_writing() methods. If specified, + the low-water limit must be less than or equal to the + high-water limit. Neither value can be negative. + + The defaults are implementation-specific. If only the + high-water limit is given, the low-water limit defaults to an + implementation-specific value less than or equal to the + high-water limit. Setting high to zero forces low to zero as + well, and causes pause_writing() to be called whenever the + buffer becomes non-empty. Setting low to zero causes + resume_writing() to be called only once the buffer is empty. + Use of zero for either limit is generally sub-optimal as it + reduces opportunities for doing I/O and computation + concurrently. + 'u'Set the high- and low-water limits for write flow control. + + These two values control when to call the protocol's + pause_writing() and resume_writing() methods. If specified, + the low-water limit must be less than or equal to the + high-water limit. Neither value can be negative. + + The defaults are implementation-specific. If only the + high-water limit is given, the low-water limit defaults to an + implementation-specific value less than or equal to the + high-water limit. Setting high to zero forces low to zero as + well, and causes pause_writing() to be called whenever the + buffer becomes non-empty. Setting low to zero causes + resume_writing() to be called only once the buffer is empty. + Use of zero for either limit is generally sub-optimal as it + reduces opportunities for doing I/O and computation + concurrently. + 'b'Return the current size of the write buffer.'u'Return the current size of the write buffer.'b'Write some data bytes to the transport. + + This does not block; it buffers the data and arranges for it + to be sent out asynchronously. + 'u'Write some data bytes to the transport. + + This does not block; it buffers the data and arranges for it + to be sent out asynchronously. + 'b'data: expecting a bytes-like instance, got 'u'data: expecting a bytes-like instance, got 'b'Return True if this transport supports write_eof(), False if not.'u'Return True if this transport supports write_eof(), False if not.'b'Close the transport immediately. + + Buffered data will be lost. No more data will be received. + The protocol's connection_lost() method will (eventually) be + called with None as its argument. + 'u'Close the transport immediately. + + Buffered data will be lost. No more data will be received. + The protocol's connection_lost() method will (eventually) be + called with None as its argument. + 'b'SSL protocol. + + Implementation of SSL on top of a socket using incoming and outgoing + buffers which are ssl.MemoryBIO objects. + 'u'SSL protocol. + + Implementation of SSL on top of a socket using incoming and outgoing + buffers which are ssl.MemoryBIO objects. + 'b'stdlib ssl module not available'u'stdlib ssl module not available'b'ssl_handshake_timeout should be a positive number, got 'u'ssl_handshake_timeout should be a positive number, got 'b'Called when the low-level connection is made. + + Start the SSL handshake. + 'u'Called when the low-level connection is made. + + Start the SSL handshake. + 'b'Called when the low-level connection is lost or closed. + + The argument is an exception object or None (the latter + meaning a regular EOF is received or the connection was + aborted or closed). + 'u'Called when the low-level connection is lost or closed. + + The argument is an exception object or None (the latter + meaning a regular EOF is received or the connection was + aborted or closed). + 'b'_handshake_timeout_handle'u'_handshake_timeout_handle'b'Called when the low-level transport's buffer goes over + the high-water mark. + 'u'Called when the low-level transport's buffer goes over + the high-water mark. + 'b'Called when the low-level transport's buffer drains below + the low-water mark. + 'u'Called when the low-level transport's buffer drains below + the low-water mark. + 'b'Called when some SSL data is received. + + The argument is a bytes object. + 'u'Called when some SSL data is received. + + The argument is a bytes object. + 'b'SSL error in data received'u'SSL error in data received'b'application protocol failed to receive SSL data'u'application protocol failed to receive SSL data'b'Called when the other end of the low-level stream + is half-closed. + + If this returns a false value (including None), the transport + will close itself. If it returns a true value, closing the + transport is up to the protocol. + 'u'Called when the other end of the low-level stream + is half-closed. + + If this returns a false value (including None), the transport + will close itself. If it returns a true value, closing the + transport is up to the protocol. + 'b'returning true from eof_received() has no effect when using ssl'u'returning true from eof_received() has no effect when using ssl'b'%r starts SSL handshake'u'%r starts SSL handshake'b'SSL handshake is taking longer than 'u'SSL handshake is taking longer than 'b' seconds: aborting the connection'u' seconds: aborting the connection'b'SSL handshake failed on verifying the certificate'u'SSL handshake failed on verifying the certificate'b'SSL handshake failed'u'SSL handshake failed'b'%r: SSL handshake took %.1f ms'u'%r: SSL handshake took %.1f ms'b'Fatal error on SSL transport'u'Fatal error on SSL transport'u'asyncio.sslproto'u'sslproto'Support for running coroutines in parallel with staggered start times.exceptions_modOptionalAnycoro_fnsRun coroutines with staggered start times and take the first to finish. + + This method takes an iterable of coroutine functions. The first one is + started immediately. From then on, whenever the immediately preceding one + fails (raises an exception), or when *delay* seconds has passed, the next + coroutine is started. This continues until one of the coroutines complete + successfully, in which case all others are cancelled, or until all + coroutines fail. + + The coroutines provided should be well-behaved in the following way: + + * They should only ``return`` if completed successfully. + + * They should always raise an exception if they did not complete + successfully. In particular, if they handle cancellation, they should + probably reraise, like this:: + + try: + # do work + except asyncio.CancelledError: + # undo partially completed work + raise + + Args: + coro_fns: an iterable of coroutine functions, i.e. callables that + return a coroutine object when called. Use ``functools.partial`` or + lambdas to pass arguments. + + delay: amount of time, in seconds, between starting coroutines. If + ``None``, the coroutines will run sequentially. + + loop: the event loop to use. + + Returns: + tuple *(winner_result, winner_index, exceptions)* where + + - *winner_result*: the result of the winning coroutine, or ``None`` + if no coroutines won. + + - *winner_index*: the index of the winning coroutine in + ``coro_fns``, or ``None`` if no coroutines won. If the winning + coroutine may return None on success, *winner_index* can be used + to definitively determine whether any coroutine won. + + - *exceptions*: list of exceptions returned by the coroutines. + ``len(exceptions)`` is equal to the number of coroutines actually + started, and the order is the same as in ``coro_fns``. The winning + coroutine's entry is ``None``. + + enum_coro_fnswinner_resultwinner_indexrunning_tasksrun_one_coroprevious_failedthis_indexcoro_fnthis_failednext_taskfirst_taskdone_count# TODO: when we have aiter() and anext(), allow async iterables in coro_fns.# Wait for the previous task to finish, or for delay seconds# Use asyncio.wait_for() instead of asyncio.wait() here, so# that if we get cancelled at this point, Event.wait() is also# cancelled, otherwise there will be a "Task destroyed but it is# pending" later.# Get the next coroutine to run# Start task that will run the next coroutine# Prepare place to put this coroutine's exceptions if not won# Kickstart the next coroutine# Store winner's results# Cancel all other tasks. We take care to not cancel the current# task as well. If we do so, then since there is no `await` after# here and CancelledError are usually thrown at one, we will# encounter a curious corner case where the current task will end# up as done() == True, cancelled() == False, exception() ==# asyncio.CancelledError. This behavior is specified in# https://bugs.python.org/issue30048# Wait for a growing list of tasks to all finish: poor man's version of# curio's TaskGroup or trio's nursery# If run_one_coro raises an unhandled exception, it's probably a# programming error, and I want to see it.# Make sure no tasks are left running if we leave this functionb'Support for running coroutines in parallel with staggered start times.'u'Support for running coroutines in parallel with staggered start times.'b'staggered_race'u'staggered_race'b'Run coroutines with staggered start times and take the first to finish. + + This method takes an iterable of coroutine functions. The first one is + started immediately. From then on, whenever the immediately preceding one + fails (raises an exception), or when *delay* seconds has passed, the next + coroutine is started. This continues until one of the coroutines complete + successfully, in which case all others are cancelled, or until all + coroutines fail. + + The coroutines provided should be well-behaved in the following way: + + * They should only ``return`` if completed successfully. + + * They should always raise an exception if they did not complete + successfully. In particular, if they handle cancellation, they should + probably reraise, like this:: + + try: + # do work + except asyncio.CancelledError: + # undo partially completed work + raise + + Args: + coro_fns: an iterable of coroutine functions, i.e. callables that + return a coroutine object when called. Use ``functools.partial`` or + lambdas to pass arguments. + + delay: amount of time, in seconds, between starting coroutines. If + ``None``, the coroutines will run sequentially. + + loop: the event loop to use. + + Returns: + tuple *(winner_result, winner_index, exceptions)* where + + - *winner_result*: the result of the winning coroutine, or ``None`` + if no coroutines won. + + - *winner_index*: the index of the winning coroutine in + ``coro_fns``, or ``None`` if no coroutines won. If the winning + coroutine may return None on success, *winner_index* can be used + to definitively determine whether any coroutine won. + + - *exceptions*: list of exceptions returned by the coroutines. + ``len(exceptions)`` is equal to the number of coroutines actually + started, and the order is the same as in ``coro_fns``. The winning + coroutine's entry is ``None``. + + 'u'Run coroutines with staggered start times and take the first to finish. + + This method takes an iterable of coroutine functions. The first one is + started immediately. From then on, whenever the immediately preceding one + fails (raises an exception), or when *delay* seconds has passed, the next + coroutine is started. This continues until one of the coroutines complete + successfully, in which case all others are cancelled, or until all + coroutines fail. + + The coroutines provided should be well-behaved in the following way: + + * They should only ``return`` if completed successfully. + + * They should always raise an exception if they did not complete + successfully. In particular, if they handle cancellation, they should + probably reraise, like this:: + + try: + # do work + except asyncio.CancelledError: + # undo partially completed work + raise + + Args: + coro_fns: an iterable of coroutine functions, i.e. callables that + return a coroutine object when called. Use ``functools.partial`` or + lambdas to pass arguments. + + delay: amount of time, in seconds, between starting coroutines. If + ``None``, the coroutines will run sequentially. + + loop: the event loop to use. + + Returns: + tuple *(winner_result, winner_index, exceptions)* where + + - *winner_result*: the result of the winning coroutine, or ``None`` + if no coroutines won. + + - *winner_index*: the index of the winning coroutine in + ``coro_fns``, or ``None`` if no coroutines won. If the winning + coroutine may return None on success, *winner_index* can be used + to definitively determine whether any coroutine won. + + - *exceptions*: list of exceptions returned by the coroutines. + ``len(exceptions)`` is equal to the number of coroutines actually + started, and the order is the same as in ``coro_fns``. The winning + coroutine's entry is ``None``. + + 'u'asyncio.staggered'u'staggered'Constants/functions for interpreting results of os.stat() and os.lstat(). + +Suggested usage: from stat import * +Return the portion of the file's mode that can be set by + os.chmod(). + 0o7777Return the portion of the file's mode that describes the + file type. + 0o0200000o0600000o0100000o1200000o140000Return True if mode is from a directory.Return True if mode is from a character special device file.Return True if mode is from a block special device file.Return True if mode is from a regular file.Return True if mode is from a FIFO (named pipe).Return True if mode is from a symbolic link.Return True if mode is from a socket.Return True if mode is from a door.Return True if mode is from an event port.Return True if mode is from a whiteout.0o40000o20000o10000o04000o02000o01000o07000o00700o00400o00200o00100o00070o00040o00020o00010x000000010x000000020x000000040x000000080x000000100x000000200x000080000x000100000x000200000x000400000x001000000x00200000_filemode_tableConvert a file's mode to a string of the form '-rwxrwxrwx'.FILE_ATTRIBUTE_ARCHIVEFILE_ATTRIBUTE_COMPRESSEDFILE_ATTRIBUTE_DEVICEFILE_ATTRIBUTE_DIRECTORYFILE_ATTRIBUTE_ENCRYPTEDFILE_ATTRIBUTE_HIDDENFILE_ATTRIBUTE_INTEGRITY_STREAMFILE_ATTRIBUTE_NORMALFILE_ATTRIBUTE_NOT_CONTENT_INDEXEDFILE_ATTRIBUTE_NO_SCRUB_DATAFILE_ATTRIBUTE_OFFLINEFILE_ATTRIBUTE_READONLYFILE_ATTRIBUTE_SPARSE_FILEFILE_ATTRIBUTE_SYSTEMFILE_ATTRIBUTE_TEMPORARYFILE_ATTRIBUTE_VIRTUAL# Indices for stat struct members in the tuple returned by os.stat()# Extract bits from the mode# Constants used as S_IFMT() for various file types# (not all are implemented on all systems)# directory# character device# block device# regular file# fifo (named pipe)# symbolic link# socket file# Fallbacks for uncommon platform-specific constants# Functions to test for each file type# Names for permission bits# set UID bit# set GID bit# file locking enforcement# sticky bit# Unix V7 synonym for S_IRUSR# Unix V7 synonym for S_IWUSR# Unix V7 synonym for S_IXUSR# mask for owner permissions# read by owner# write by owner# execute by owner# mask for group permissions# read by group# write by group# execute by group# mask for others (not in group) permissions# read by others# write by others# execute by others# Names for file flags# do not dump file# file may not be changed# file may only be appended to# directory is opaque when viewed through a union stack# file may not be renamed or deleted# OS X: file is hfs-compressed# OS X: file should not be displayed# file may be archived# file is a snapshot file# Must appear before IFREG and IFDIR as IFSOCK == IFREG | IFDIR# Windows FILE_ATTRIBUTE constants for interpreting os.stat()'s# "st_file_attributes" memberb'Constants/functions for interpreting results of os.stat() and os.lstat(). + +Suggested usage: from stat import * +'u'Constants/functions for interpreting results of os.stat() and os.lstat(). + +Suggested usage: from stat import * +'b'Return the portion of the file's mode that can be set by + os.chmod(). + 'u'Return the portion of the file's mode that can be set by + os.chmod(). + 'b'Return the portion of the file's mode that describes the + file type. + 'u'Return the portion of the file's mode that describes the + file type. + 'b'Return True if mode is from a directory.'u'Return True if mode is from a directory.'b'Return True if mode is from a character special device file.'u'Return True if mode is from a character special device file.'b'Return True if mode is from a block special device file.'u'Return True if mode is from a block special device file.'b'Return True if mode is from a regular file.'u'Return True if mode is from a regular file.'b'Return True if mode is from a FIFO (named pipe).'u'Return True if mode is from a FIFO (named pipe).'b'Return True if mode is from a symbolic link.'u'Return True if mode is from a symbolic link.'b'Return True if mode is from a socket.'u'Return True if mode is from a socket.'b'Return True if mode is from a door.'u'Return True if mode is from a door.'b'Return True if mode is from an event port.'u'Return True if mode is from an event port.'b'Return True if mode is from a whiteout.'u'Return True if mode is from a whiteout.'b'Convert a file's mode to a string of the form '-rwxrwxrwx'.'u'Convert a file's mode to a string of the form '-rwxrwxrwx'.'StreamReaderProtocolopen_connectionopen_unix_connectionstart_unix_server_DEFAULT_LIMITA wrapper for create_connection() returning a (reader, writer) pair. + + The reader returned is a StreamReader instance; the writer is a + StreamWriter instance. + + The arguments are all the usual arguments to create_connection() + except protocol_factory; most common are positional host and port, + with various optional keyword arguments following. + + Additional optional keyword arguments are loop (to set the event loop + instance to use) and limit (to set the buffer limit passed to the + StreamReader). + + (If you want to customize the StreamReader and/or + StreamReaderProtocol classes, just copy the code -- there's + really nothing special here except some convenience.) + client_connected_cbStart a socket server, call back for each client connected. + + The first parameter, `client_connected_cb`, takes two parameters: + client_reader, client_writer. client_reader is a StreamReader + object, while client_writer is a StreamWriter object. This + parameter can either be a plain callback function or a coroutine; + if it is a coroutine, it will be automatically converted into a + Task. + + The rest of the arguments are all the usual arguments to + loop.create_server() except protocol_factory; most common are + positional host and port, with various optional keyword arguments + following. The return value is the same as loop.create_server(). + + Additional optional keyword arguments are loop (to set the event loop + instance to use) and limit (to set the buffer limit passed to the + StreamReader). + + The return value is the same as loop.create_server(), i.e. a + Server object which can be used to stop the service. + Similar to `open_connection` but works with UNIX Domain Sockets.Similar to `start_server` but works with UNIX Domain Sockets.FlowControlMixinReusable flow control logic for StreamWriter.drain(). + + This implements the protocol methods pause_writing(), + resume_writing() and connection_lost(). If the subclass overrides + these it must call the super methods. + + StreamWriter.drain() must wait for _drain_helper() coroutine. + _drain_waiter_connection_lost%r pauses writing%r resumes writing_drain_helperConnection lost_get_close_waiterHelper class to adapt between Protocol and StreamReader. + + (This is a helper class instead of making StreamReader itself a + Protocol subclass, because the StreamReader has other potential + uses, and to prevent the user of the StreamReader to accidentally + call inappropriate methods of the protocol.) + stream_reader_stream_reader_wr_strong_reader_reject_connection_stream_writer_client_connected_cb_over_ssl_stream_readerAn open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.'An open stream was garbage collected prior to ''establishing network connection; ''call "stream.close()" explicitly.'set_transportfeed_dataWraps a Transport. + + This exposes write(), writelines(), [can_]write_eof(), + get_extra_info() and close(). It adds drain() which returns an + optional Future on which you can wait for flow control. It also + adds a transport property which references the Transport + directly. + _complete_futtransport=reader=Flush the write buffer. + + The intended use is to write + + w.write(data) + await w.drain() + Limit cannot be <= 0_limit byteslimit=waiter=pausedWakeup read*() functions waiting for data or EOF.Transport already set_maybe_resume_transportat_eofReturn True if the buffer is empty and 'feed_eof' was called.feed_data after feed_eof_wait_for_dataWait until feed_data() or feed_eof() is called. + + If stream was paused, automatically resume it. + () called while another coroutine is already waiting for incoming data'() called while another coroutine is ''already waiting for incoming data'_wait_for_data after EOFRead chunk of data from the stream until newline (b' +') is found. + + On success, return chunk that ends with newline. If only partial + line can be read due to EOF, return incomplete line without + terminating newline. When EOF was reached while no bytes read, empty + bytes object is returned. + + If limit is reached, ValueError will be raised. In that case, if + newline was found, complete line including newline will be removed + from internal buffer. Else, internal buffer will be cleared. Limit is + compared against part of the line without newline. + + If stream was paused, this function will automatically resume it if + needed. + seplenreaduntilRead data from the stream until ``separator`` is found. + + On success, the data and separator will be removed from the + internal buffer (consumed). Returned data will include the + separator at the end. + + Configured stream limit is used to check result. Limit sets the + maximal length of data that can be returned, not counting the + separator. + + If an EOF occurs and the complete separator is still not found, + an IncompleteReadError exception will be raised, and the internal + buffer will be reset. The IncompleteReadError.partial attribute + may contain the separator partially. + + If the data cannot be read because of over limit, a + LimitOverrunError exception will be raised, and the data + will be left in the internal buffer, so it can be read again. + Separator should be at least one-byte stringisepSeparator is not found, and chunk exceed the limitSeparator is found, but chunk is longer than limitRead up to `n` bytes from the stream. + + If n is not provided, or set to -1, read until EOF and return all read + bytes. If the EOF was received and the internal buffer is empty, return + an empty bytes object. + + If n is zero, return empty bytes object immediately. + + If n is positive, this function try to read `n` bytes, and may return + less or equal bytes than requested, but at least one byte. If EOF was + received before any byte is read, this function returns empty byte + object. + + Returned value is not limited with limit, configured at stream + creation. + + If stream was paused, this function will automatically resume it if + needed. + blocksreadexactlyRead exactly `n` bytes. + + Raise an IncompleteReadError if EOF is reached before `n` bytes can be + read. The IncompleteReadError.partial attribute of the exception will + contain the partial read bytes. + + if n is zero, return empty bytes object. + + Returned value is not limited with limit, configured at stream + creation. + + If stream was paused, this function will automatically resume it if + needed. + readexactly size can not be less than zeroincomplete# 64 KiB# UNIX Domain Sockets are supported on this platform# Wake up the writer if currently paused.# This is a stream created by the `create_server()` function.# Keep a strong reference to the reader until a connection# is established.# Prevent a warning in SSLProtocol.eof_received:# "returning true from eof_received()# has no effect when using ssl"# Prevent reports about unhandled exceptions.# Better than self._closed._log_traceback = False hack# drain() expects that the reader has an exception() method# Wait for protocol.connection_lost() call# Raise connection closing error if any,# ConnectionResetError otherwise# Yield to the event loop so connection_lost() may be# called. Without this, _drain_helper() would return# immediately, and code that calls# write(...); await drain()# in a loop would never call connection_lost(), so it# would not see an error when the socket is closed.# The line length limit is a security feature;# it also doubles as half the buffer limit.# Whether we're done.# A future used by _wait_for_data()# The transport can't be paused.# We'll just have to buffer all data.# Forget the transport so we don't keep trying.# StreamReader uses a future to link the protocol feed_data() method# to a read coroutine. Running two read coroutines at the same time# would have an unexpected behaviour. It would not possible to know# which coroutine would get the next data.# Waiting for data while paused will make deadlock, so prevent it.# This is essential for readexactly(n) for case when n > self._limit.# Consume whole buffer except last bytes, which length is# one less than seplen. Let's check corner cases with# separator='SEPARATOR':# * we have received almost complete separator (without last# byte). i.e buffer='some textSEPARATO'. In this case we# can safely consume len(separator) - 1 bytes.# * last byte of buffer is first byte of separator, i.e.# buffer='abcdefghijklmnopqrS'. We may safely consume# everything except that last byte, but this require to# analyze bytes of buffer that match partial separator.# This is slow and/or require FSM. For this case our# implementation is not optimal, since require rescanning# of data that is known to not belong to separator. In# real world, separator will not be so long to notice# performance problems. Even when reading MIME-encoded# messages :)# `offset` is the number of bytes from the beginning of the buffer# where there is no occurrence of `separator`.# Loop until we find `separator` in the buffer, exceed the buffer size,# or an EOF has happened.# Check if we now have enough data in the buffer for `separator` to# fit.# `separator` is in the buffer. `isep` will be used later# to retrieve the data.# see upper comment for explanation.# Complete message (with full separator) may be present in buffer# even when EOF flag is set. This may happen when the last chunk# adds data which makes separator be found. That's why we check for# EOF *ater* inspecting the buffer.# _wait_for_data() will resume reading if stream was paused.# This used to just loop creating a new waiter hoping to# collect everything in self._buffer, but that would# deadlock if the subprocess sends more than self.limit# bytes. So just call self.read(self._limit) until EOF.# This will work right even if buffer is less than n bytesb'StreamReaderProtocol'u'StreamReaderProtocol'b'open_connection'u'open_connection'b'start_server'u'start_server'b'open_unix_connection'u'open_unix_connection'b'start_unix_server'u'start_unix_server'b'A wrapper for create_connection() returning a (reader, writer) pair. + + The reader returned is a StreamReader instance; the writer is a + StreamWriter instance. + + The arguments are all the usual arguments to create_connection() + except protocol_factory; most common are positional host and port, + with various optional keyword arguments following. + + Additional optional keyword arguments are loop (to set the event loop + instance to use) and limit (to set the buffer limit passed to the + StreamReader). + + (If you want to customize the StreamReader and/or + StreamReaderProtocol classes, just copy the code -- there's + really nothing special here except some convenience.) + 'u'A wrapper for create_connection() returning a (reader, writer) pair. + + The reader returned is a StreamReader instance; the writer is a + StreamWriter instance. + + The arguments are all the usual arguments to create_connection() + except protocol_factory; most common are positional host and port, + with various optional keyword arguments following. + + Additional optional keyword arguments are loop (to set the event loop + instance to use) and limit (to set the buffer limit passed to the + StreamReader). + + (If you want to customize the StreamReader and/or + StreamReaderProtocol classes, just copy the code -- there's + really nothing special here except some convenience.) + 'b'Start a socket server, call back for each client connected. + + The first parameter, `client_connected_cb`, takes two parameters: + client_reader, client_writer. client_reader is a StreamReader + object, while client_writer is a StreamWriter object. This + parameter can either be a plain callback function or a coroutine; + if it is a coroutine, it will be automatically converted into a + Task. + + The rest of the arguments are all the usual arguments to + loop.create_server() except protocol_factory; most common are + positional host and port, with various optional keyword arguments + following. The return value is the same as loop.create_server(). + + Additional optional keyword arguments are loop (to set the event loop + instance to use) and limit (to set the buffer limit passed to the + StreamReader). + + The return value is the same as loop.create_server(), i.e. a + Server object which can be used to stop the service. + 'u'Start a socket server, call back for each client connected. + + The first parameter, `client_connected_cb`, takes two parameters: + client_reader, client_writer. client_reader is a StreamReader + object, while client_writer is a StreamWriter object. This + parameter can either be a plain callback function or a coroutine; + if it is a coroutine, it will be automatically converted into a + Task. + + The rest of the arguments are all the usual arguments to + loop.create_server() except protocol_factory; most common are + positional host and port, with various optional keyword arguments + following. The return value is the same as loop.create_server(). + + Additional optional keyword arguments are loop (to set the event loop + instance to use) and limit (to set the buffer limit passed to the + StreamReader). + + The return value is the same as loop.create_server(), i.e. a + Server object which can be used to stop the service. + 'b'Similar to `open_connection` but works with UNIX Domain Sockets.'u'Similar to `open_connection` but works with UNIX Domain Sockets.'b'Similar to `start_server` but works with UNIX Domain Sockets.'u'Similar to `start_server` but works with UNIX Domain Sockets.'b'Reusable flow control logic for StreamWriter.drain(). + + This implements the protocol methods pause_writing(), + resume_writing() and connection_lost(). If the subclass overrides + these it must call the super methods. + + StreamWriter.drain() must wait for _drain_helper() coroutine. + 'u'Reusable flow control logic for StreamWriter.drain(). + + This implements the protocol methods pause_writing(), + resume_writing() and connection_lost(). If the subclass overrides + these it must call the super methods. + + StreamWriter.drain() must wait for _drain_helper() coroutine. + 'b'%r pauses writing'u'%r pauses writing'b'%r resumes writing'u'%r resumes writing'b'Connection lost'u'Connection lost'b'Helper class to adapt between Protocol and StreamReader. + + (This is a helper class instead of making StreamReader itself a + Protocol subclass, because the StreamReader has other potential + uses, and to prevent the user of the StreamReader to accidentally + call inappropriate methods of the protocol.) + 'u'Helper class to adapt between Protocol and StreamReader. + + (This is a helper class instead of making StreamReader itself a + Protocol subclass, because the StreamReader has other potential + uses, and to prevent the user of the StreamReader to accidentally + call inappropriate methods of the protocol.) + 'b'An open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.'u'An open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.'b'sslcontext'u'sslcontext'b'Wraps a Transport. + + This exposes write(), writelines(), [can_]write_eof(), + get_extra_info() and close(). It adds drain() which returns an + optional Future on which you can wait for flow control. It also + adds a transport property which references the Transport + directly. + 'u'Wraps a Transport. + + This exposes write(), writelines(), [can_]write_eof(), + get_extra_info() and close(). It adds drain() which returns an + optional Future on which you can wait for flow control. It also + adds a transport property which references the Transport + directly. + 'b'transport='u'transport='b'reader='u'reader='b'Flush the write buffer. + + The intended use is to write + + w.write(data) + await w.drain() + 'u'Flush the write buffer. + + The intended use is to write + + w.write(data) + await w.drain() + 'b'Limit cannot be <= 0'u'Limit cannot be <= 0'b' bytes'u' bytes'b'eof'u'eof'b'limit='u'limit='b'waiter='u'waiter='b'paused'u'paused'b'Wakeup read*() functions waiting for data or EOF.'u'Wakeup read*() functions waiting for data or EOF.'b'Transport already set'u'Transport already set'b'Return True if the buffer is empty and 'feed_eof' was called.'u'Return True if the buffer is empty and 'feed_eof' was called.'b'feed_data after feed_eof'u'feed_data after feed_eof'b'Wait until feed_data() or feed_eof() is called. + + If stream was paused, automatically resume it. + 'u'Wait until feed_data() or feed_eof() is called. + + If stream was paused, automatically resume it. + 'b'() called while another coroutine is already waiting for incoming data'u'() called while another coroutine is already waiting for incoming data'b'_wait_for_data after EOF'u'_wait_for_data after EOF'b'Read chunk of data from the stream until newline (b' +') is found. + + On success, return chunk that ends with newline. If only partial + line can be read due to EOF, return incomplete line without + terminating newline. When EOF was reached while no bytes read, empty + bytes object is returned. + + If limit is reached, ValueError will be raised. In that case, if + newline was found, complete line including newline will be removed + from internal buffer. Else, internal buffer will be cleared. Limit is + compared against part of the line without newline. + + If stream was paused, this function will automatically resume it if + needed. + 'u'Read chunk of data from the stream until newline (b' +') is found. + + On success, return chunk that ends with newline. If only partial + line can be read due to EOF, return incomplete line without + terminating newline. When EOF was reached while no bytes read, empty + bytes object is returned. + + If limit is reached, ValueError will be raised. In that case, if + newline was found, complete line including newline will be removed + from internal buffer. Else, internal buffer will be cleared. Limit is + compared against part of the line without newline. + + If stream was paused, this function will automatically resume it if + needed. + 'b'Read data from the stream until ``separator`` is found. + + On success, the data and separator will be removed from the + internal buffer (consumed). Returned data will include the + separator at the end. + + Configured stream limit is used to check result. Limit sets the + maximal length of data that can be returned, not counting the + separator. + + If an EOF occurs and the complete separator is still not found, + an IncompleteReadError exception will be raised, and the internal + buffer will be reset. The IncompleteReadError.partial attribute + may contain the separator partially. + + If the data cannot be read because of over limit, a + LimitOverrunError exception will be raised, and the data + will be left in the internal buffer, so it can be read again. + 'u'Read data from the stream until ``separator`` is found. + + On success, the data and separator will be removed from the + internal buffer (consumed). Returned data will include the + separator at the end. + + Configured stream limit is used to check result. Limit sets the + maximal length of data that can be returned, not counting the + separator. + + If an EOF occurs and the complete separator is still not found, + an IncompleteReadError exception will be raised, and the internal + buffer will be reset. The IncompleteReadError.partial attribute + may contain the separator partially. + + If the data cannot be read because of over limit, a + LimitOverrunError exception will be raised, and the data + will be left in the internal buffer, so it can be read again. + 'b'Separator should be at least one-byte string'u'Separator should be at least one-byte string'b'Separator is not found, and chunk exceed the limit'u'Separator is not found, and chunk exceed the limit'b'readuntil'u'readuntil'b'Separator is found, but chunk is longer than limit'u'Separator is found, but chunk is longer than limit'b'Read up to `n` bytes from the stream. + + If n is not provided, or set to -1, read until EOF and return all read + bytes. If the EOF was received and the internal buffer is empty, return + an empty bytes object. + + If n is zero, return empty bytes object immediately. + + If n is positive, this function try to read `n` bytes, and may return + less or equal bytes than requested, but at least one byte. If EOF was + received before any byte is read, this function returns empty byte + object. + + Returned value is not limited with limit, configured at stream + creation. + + If stream was paused, this function will automatically resume it if + needed. + 'u'Read up to `n` bytes from the stream. + + If n is not provided, or set to -1, read until EOF and return all read + bytes. If the EOF was received and the internal buffer is empty, return + an empty bytes object. + + If n is zero, return empty bytes object immediately. + + If n is positive, this function try to read `n` bytes, and may return + less or equal bytes than requested, but at least one byte. If EOF was + received before any byte is read, this function returns empty byte + object. + + Returned value is not limited with limit, configured at stream + creation. + + If stream was paused, this function will automatically resume it if + needed. + 'b'Read exactly `n` bytes. + + Raise an IncompleteReadError if EOF is reached before `n` bytes can be + read. The IncompleteReadError.partial attribute of the exception will + contain the partial read bytes. + + if n is zero, return empty bytes object. + + Returned value is not limited with limit, configured at stream + creation. + + If stream was paused, this function will automatically resume it if + needed. + 'u'Read exactly `n` bytes. + + Raise an IncompleteReadError if EOF is reached before `n` bytes can be + read. The IncompleteReadError.partial attribute of the exception will + contain the partial read bytes. + + if n is zero, return empty bytes object. + + Returned value is not limited with limit, configured at stream + creation. + + If stream was paused, this function will automatically resume it if + needed. + 'b'readexactly size can not be less than zero'u'readexactly size can not be less than zero'b'readexactly'u'readexactly'u'asyncio.streams'u'streams'A collection of string constants. + +Public module variables: + +whitespace -- a string containing all ASCII whitespace +ascii_lowercase -- a string containing all ASCII lowercase letters +ascii_uppercase -- a string containing all ASCII uppercase letters +ascii_letters -- a string containing all ASCII letters +digits -- a string containing all ASCII decimal digits +hexdigits -- a string containing all ASCII hexadecimal digits +octdigits -- a string containing all ASCII octal digits +punctuation -- a string containing all ASCII punctuation characters +printable -- a string containing all ASCII characters considered printable + +ascii_lowercaseascii_uppercasecapwordsoctdigitsprintableabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefABCDEFcapwords(s [,sep]) -> string + + Split the argument into words using split, capitalize each + word using capitalize, and join the capitalized words using + join. If the optional second argument sep is absent or None, + runs of whitespace characters are replaced by a single space + and leading and trailing whitespace are removed, otherwise + sep is used to split and join the words. + + _ChainMap_sentinel_dict_TemplateMetaclass + %(delim)s(?: + (?P%(delim)s) | # Escape sequence of two delimiters + (?P%(id)s) | # delimiter and a Python identifier + {(?P%(bid)s)} | # delimiter and a braced identifier + (?P) # Other ill-formed delimiter exprs + ) + delimiteridpatternbraceidpatternbidA string class for supporting $-substitutions.(?a:[_a-z][_a-z0-9]*)_invalidInvalid placeholder in string: line %d, col %dUnrecognized named group in patternsafe_substitutevformatused_args_vformatcheck_unused_argsrecursion_depthauto_arg_indexMax string recursion exceededliteral_textcannot switch from manual field specification to automatic field numbering'cannot switch from manual field ''specification to automatic field ''numbering'get_fieldarg_usedconvert_fieldformat_fieldget_valueUnknown conversion specifier {0!s}is_attr# Some strings for ctype-style character classification# Functions which aren't available as string methods.# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".##################################################################### r'[a-z]' matches to non-ASCII letters when used with IGNORECASE, but# without the ASCII flag. We can't add re.ASCII to flags because of# backward compatibility. So we use the ?a local flag and [a-z] pattern.# See https://bugs.python.org/issue31672# Search for $$, $identifier, ${identifier}, and any bare $'s# Helper function for .sub()# Check the most common path first.# the Formatter class# see PEP 3101 for details and purpose of this class# The hard parts are reused from the C implementation. They're exposed as "_"# prefixed methods of str.# The overall parser is implemented in _string.formatter_parser.# The field name parser is implemented in _string.formatter_field_name_split# output the literal text# if there's a field, output it# this is some markup, find the object and do# the formatting# handle arg indexing when empty field_names are given.# disable auto arg incrementing, if it gets# used later on, then an exception will be raised# given the field_name, find the object it references# and the argument it came from# do any conversion on the resulting object# expand the format spec, if needed# format the object and append to the result# returns an iterable that contains tuples of the form:# (literal_text, field_name, format_spec, conversion)# literal_text can be zero length# field_name can be None, in which case there's no# object to format and output# if field_name is not None, it is looked up, formatted# with format_spec and conversion and then used# given a field_name, find the object it references.# field_name: the field being looked up, e.g. "0.name"# or "lookup[3]"# used_args: a set of which args have been used# args, kwargs: as passed in to vformat# loop through the rest of the field_name, doing# getattr or getitem as neededb'A collection of string constants. + +Public module variables: + +whitespace -- a string containing all ASCII whitespace +ascii_lowercase -- a string containing all ASCII lowercase letters +ascii_uppercase -- a string containing all ASCII uppercase letters +ascii_letters -- a string containing all ASCII letters +digits -- a string containing all ASCII decimal digits +hexdigits -- a string containing all ASCII hexadecimal digits +octdigits -- a string containing all ASCII octal digits +punctuation -- a string containing all ASCII punctuation characters +printable -- a string containing all ASCII characters considered printable + +'u'A collection of string constants. + +Public module variables: + +whitespace -- a string containing all ASCII whitespace +ascii_lowercase -- a string containing all ASCII lowercase letters +ascii_uppercase -- a string containing all ASCII uppercase letters +ascii_letters -- a string containing all ASCII letters +digits -- a string containing all ASCII decimal digits +hexdigits -- a string containing all ASCII hexadecimal digits +octdigits -- a string containing all ASCII octal digits +punctuation -- a string containing all ASCII punctuation characters +printable -- a string containing all ASCII characters considered printable + +'b'ascii_letters'u'ascii_letters'b'ascii_lowercase'u'ascii_lowercase'b'ascii_uppercase'u'ascii_uppercase'b'capwords'u'capwords'b'digits'b'hexdigits'u'hexdigits'b'octdigits'u'octdigits'b'printable'u'printable'b'punctuation'u'punctuation'b'whitespace'u'whitespace'b'Template'u'Template'u'abcdefghijklmnopqrstuvwxyz'u'ABCDEFGHIJKLMNOPQRSTUVWXYZ'b'abcdef'u'abcdef'b'ABCDEF'u'ABCDEF'b'capwords(s [,sep]) -> string + + Split the argument into words using split, capitalize each + word using capitalize, and join the capitalized words using + join. If the optional second argument sep is absent or None, + runs of whitespace characters are replaced by a single space + and leading and trailing whitespace are removed, otherwise + sep is used to split and join the words. + + 'u'capwords(s [,sep]) -> string + + Split the argument into words using split, capitalize each + word using capitalize, and join the capitalized words using + join. If the optional second argument sep is absent or None, + runs of whitespace characters are replaced by a single space + and leading and trailing whitespace are removed, otherwise + sep is used to split and join the words. + + 'b' + %(delim)s(?: + (?P%(delim)s) | # Escape sequence of two delimiters + (?P%(id)s) | # delimiter and a Python identifier + {(?P%(bid)s)} | # delimiter and a braced identifier + (?P) # Other ill-formed delimiter exprs + ) + 'u' + %(delim)s(?: + (?P%(delim)s) | # Escape sequence of two delimiters + (?P%(id)s) | # delimiter and a Python identifier + {(?P%(bid)s)} | # delimiter and a braced identifier + (?P) # Other ill-formed delimiter exprs + ) + 'b'delim'u'delim'b'bid'u'bid'b'A string class for supporting $-substitutions.'u'A string class for supporting $-substitutions.'b'(?a:[_a-z][_a-z0-9]*)'u'(?a:[_a-z][_a-z0-9]*)'b'invalid'u'invalid'b'Invalid placeholder in string: line %d, col %d'u'Invalid placeholder in string: line %d, col %d'b'escaped'u'escaped'b'Unrecognized named group in pattern'u'Unrecognized named group in pattern'b'Max string recursion exceeded'u'Max string recursion exceeded'b'cannot switch from manual field specification to automatic field numbering'u'cannot switch from manual field specification to automatic field numbering'b'Unknown conversion specifier {0!s}'u'Unknown conversion specifier {0!s}'b'calcsize'u'calcsize'b'pack_into'u'pack_into'b'unpack'u'unpack'b'unpack_from'u'unpack_from'b'iter_unpack'u'iter_unpack'b'Struct'u'Struct'Subprocesses with accessible I/O streams + +This module allows you to spawn processes, connect to their +input/output/error pipes, and obtain their return codes. + +For a complete description of this module see the Python documentation. + +Main API +======== +run(...): Runs a command, waits for it to complete, then returns a + CompletedProcess instance. +Popen(...): A class for flexibly executing a command in a new process + +Constants +--------- +DEVNULL: Special value that indicates that os.devnull should be used +PIPE: Special value that indicates a pipe should be created +STDOUT: Special value that indicates that stderr should go to stdout + + +Older API +========= +call(...): Runs a command, waits for it to complete, then returns + the return code. +check_call(...): Same as call() but raises CalledProcessError() + if return code is not 0 +check_output(...): Same as check_call() but returns the contents of + stdout instead of a return code +getoutput(...): Runs a command in the shell, waits for it to complete, + then returns the output +getstatusoutput(...): Runs a command in the shell, waits for it to complete, + then returns a (exitcode, output) tuple +check_callgetstatusoutputgetoutputSubprocessErrorTimeoutExpiredCompletedProcess_mswindowsCREATE_NEW_CONSOLECREATE_NEW_PROCESS_GROUPSTD_INPUT_HANDLESTD_OUTPUT_HANDLESTD_ERROR_HANDLESW_HIDESTARTF_USESTDHANDLESSTARTF_USESHOWWINDOWABOVE_NORMAL_PRIORITY_CLASSBELOW_NORMAL_PRIORITY_CLASSHIGH_PRIORITY_CLASSIDLE_PRIORITY_CLASSNORMAL_PRIORITY_CLASSREALTIME_PRIORITY_CLASSCREATE_NO_WINDOWDETACHED_PROCESSCREATE_DEFAULT_ERROR_MODECREATE_BREAKAWAY_FROM_JOBSTARTUPINFORaised when run() is called with check=True and the process + returns a non-zero exit status. + + Attributes: + cmd, returncode, stdout, stderr, output + Command '%s' died with %r.Command '%s' died with unknown signal %d.Command '%s' returned non-zero exit status %d.Alias for output attribute, to match stderrThis exception is raised when the timeout expires while waiting for a + child process. + + Attributes: + cmd, output, stdout, stderr, timeout + Command '%s' timed out after %s secondshStdInputhStdOutputhStdErrorwShowWindowlpAttributeListhandle_listDetachalready closed%s(%d)_PIPE_BUF_PopenSelector_active_internal_poll_deadstateReturn a list of command-line arguments reproducing the current + settings in sys.flags, sys.warnoptions and sys._xoptions.flag_opt_map-I-Ewarnoptsxoptionserror::BytesWarningdefault::BytesWarning-WimporttimeshowalloccountshowrefcountpopenargsRun command with arguments. Wait for command to complete or + timeout, then return the returncode attribute. + + The arguments are the same as for the Popen constructor. Example: + + retcode = call(["ls", "-l"]) + Run command with arguments. Wait for command to complete. If + the exit code was zero then return, otherwise raise + CalledProcessError. The CalledProcessError object will have the + return code in the returncode attribute. + + The arguments are the same as for the call function. Example: + + check_call(["ls", "-l"]) + retcodeRun command with arguments and return its output. + + If the exit code was non-zero it raises a CalledProcessError. The + CalledProcessError object will have the return code in the returncode + attribute and output in the output attribute. + + The arguments are the same as for the Popen constructor. Example: + + >>> check_output(["ls", "-l", "/dev/null"]) + b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' + + The stdout argument is not allowed as it is used internally. + To capture standard error in the result, use stderr=STDOUT. + + >>> check_output(["/bin/sh", "-c", + ... "ls -l non_existent_file ; exit 0"], + ... stderr=STDOUT) + b'ls: non_existent_file: No such file or directory\n' + + There is an additional optional argument, "input", allowing you to + pass a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it too will be used internally. Example: + + >>> check_output(["sed", "-e", "s/foo/bar/"], + ... input=b"when in the course of fooman events\n") + b'when in the course of barman events\n' + + By default, all communication is in bytes, and therefore any "input" + should be bytes, and the return value will be bytes. If in text mode, + any "input" should be a string, and the return value will be a string + decoded according to locale encoding, or by "encoding" if set. Text mode + is triggered by setting any of text, encoding, errors or universal_newlines. + stdout argument not allowed, it will be overridden.A process that has finished running. + + This is returned by run(). + + Attributes: + args: The list or str args passed to run(). + returncode: The exit code of the process, negative for signals. + stdout: The standard output (None if not captured). + stderr: The standard error (None if not captured). + args={!r}returncode={!r}stdout={!r}stderr={!r}check_returncodeRaise CalledProcessError if the exit code is non-zero.Run command with arguments and return a CompletedProcess instance. + + The returned instance will have attributes args, returncode, stdout and + stderr. By default, stdout and stderr are not captured, and those attributes + will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. + + If check is True and the exit code was non-zero, it raises a + CalledProcessError. The CalledProcessError object will have the return code + in the returncode attribute, and output & stderr attributes if those streams + were captured. + + If timeout is given, and the process takes too long, a TimeoutExpired + exception will be raised. + + There is an optional argument "input", allowing you to + pass bytes or a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it will be used internally. + + By default, all communication is in bytes, and therefore any "input" should + be bytes, and the stdout and stderr will be bytes. If in text mode, any + "input" should be a string, and stdout and stderr will be strings decoded + according to locale encoding, or by "encoding" if set. Text mode is + triggered by setting any of text, encoding, errors or universal_newlines. + + The other arguments are the same as for the Popen constructor. + stdin and input arguments may not both be used.stdout and stderr arguments may not be used with capture_output.'stdout and stderr arguments may not be used ''with capture_output.' + Translate a sequence of arguments into a command line + string, using the same rules as the MS C runtime: + + 1) Arguments are delimited by white space, which is either a + space or a tab. + + 2) A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + + 3) A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + + 4) Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + + 5) If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + needquotebs_bufReturn (exitcode, output) of executing cmd in a shell. + + Execute the string 'cmd' in a shell with 'check_output' and + return a 2-tuple (status, output). The locale encoding is used + to decode the output and process newlines. + + A trailing newline is stripped from the output. + The exit status for the command can be interpreted + according to the rules for the function 'wait'. Example: + + >>> import subprocess + >>> subprocess.getstatusoutput('ls /bin/ls') + (0, '/bin/ls') + >>> subprocess.getstatusoutput('cat /bin/junk') + (1, 'cat: /bin/junk: No such file or directory') + >>> subprocess.getstatusoutput('/bin/junk') + (127, 'sh: /bin/junk: not found') + >>> subprocess.getstatusoutput('/bin/kill $$') + (-15, '') + Return output (stdout or stderr) of executing cmd in a shell. + + Like getstatusoutput(), except the exit status is ignored and the return + value is a string containing the command's output. Example: + + >>> import subprocess + >>> subprocess.getoutput('ls /bin/ls') + '/bin/ls' + _use_posix_spawnCheck if posix_spawn() can be used for subprocess. + + subprocess requires a posix_spawn() implementation that properly reports + errors to the parent process, & sets errno on the following failures: + + * Process attribute actions failed. + * File actions failed. + * exec() failed. + + Prefer an implementation which can use vfork() in some cases for best + performance. + _USE_POSIX_SPAWN Execute a child program in a new process. + + For a complete description of the arguments see the Python documentation. + + Arguments: + args: A string, or a sequence of program arguments. + + bufsize: supplied as the buffering argument to the open() function when + creating the stdin/stdout/stderr pipe file objects + + executable: A replacement program to execute. + + stdin, stdout and stderr: These specify the executed programs' standard + input, standard output and standard error file handles, respectively. + + preexec_fn: (POSIX only) An object to be called in the child process + just before the child is executed. + + close_fds: Controls closing or inheriting of file descriptors. + + shell: If true, the command will be executed through the shell. + + cwd: Sets the current directory before the child is executed. + + env: Defines the environment variables for the new process. + + text: If true, decode stdin, stdout and stderr using the given encoding + (if set) or the system default otherwise. + + universal_newlines: Alias of text, provided for backwards compatibility. + + startupinfo and creationflags (Windows only) + + restore_signals (POSIX only) + + start_new_session (POSIX only) + + pass_fds (POSIX only) + + encoding and errors: Text mode encoding and error handling to use for + file objects stdin, stdout and stderr. + + Attributes: + stdin, stdout, stderr, pid, returncode + _child_createdpreexec_fnclose_fdsstartupinfocreationflagsrestore_signalsstart_new_sessionpass_fdsCreate new Popen instance._waitpid_lock_communication_startedbufsize must be an integerpreexec_fn is not supported on Windows platforms"preexec_fn is not supported on Windows ""platforms"pass_fds overriding close_fds.startupinfo is only supported on Windows platforms"startupinfo is only supported on Windows "creationflags is only supported on Windows platforms"creationflags is only supported on Windows "Cannot disambiguate when both text and universal_newlines are supplied but different. Pass one or the other.'Cannot disambiguate when both text ''and universal_newlines are supplied but ''different. Pass one or the other.'_get_handlesp2creadp2cwritec2preadc2pwriteerrreaderrwritetext_mode0.25_sigint_wait_secs_closed_child_pipe_fds_execute_childto_close_devnull_translate_newlinessubprocess %s is still running_get_devnull_stdin_writeInteract with process: Send data to stdin and close it. + Read data from stdout and stderr, until end-of-file is + reached. Wait for process to terminate. + + The optional "input" argument should be data to be sent to the + child process, or None, if no data should be sent to the child. + communicate() returns a tuple (stdout, stderr). + + By default, all communication is in bytes, and therefore any + "input" should be bytes, and the (stdout, stderr) will be bytes. + If in text mode (indicated by self.text_mode), any "input" should + be a string, and (stdout, stderr) will be strings decoded + according to locale encoding, or by "encoding" if set. Text mode + is triggered by setting any of text, encoding, errors or + universal_newlines. + Cannot send input after starting communication_communicate_remaining_timesigint_timeoutCheck if child process has terminated. Set and return returncode + attribute.Convenience for _communicate when computing timeouts.orig_timeoutstdout_seqstderr_seqskip_check_and_raiseConvenience for checking if a timeout has expired.Wait for child process to terminate; returns self.returncode._close_pipe_fdsdevnull_fdConstruct and return tuple with IO objects: + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite + GetStdHandleCreatePipeget_osfhandle_make_inheritableReturn a duplicate of handle, which is inheritable_filter_handle_listFilter out console handles that can't be used + in lpAttributeList["handle_list"] and make sure the list + isn't empty. This also removes duplicate handles.GetFileTypeFILE_TYPE_CHARunused_restore_signalsunused_start_new_sessionExecute program (MS Windows version)pass_fds not supported on Windows.bytes args is not allowed on Windowspath-like args is not allowed when shell is true'path-like args is not allowed when ''shell is true'use_std_handlesattribute_listhave_handle_liststartupinfo.lpAttributeList['handle_list'] overriding close_fds"startupinfo.lpAttributeList['handle_list'] ""overriding close_fds"COMSPECcmd.execomspec{} /c "{}"subprocess.PopenCreateProcesshphtWaitForSingleObjectGetExitCodeProcess_WaitForSingleObject_WAIT_OBJECT_0_GetExitCodeProcessCheck if child process has terminated. Returns returncode + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + Internal implementation of wait() on Windows.timeout_millis_readerthreadfh_stdout_buffstdout_thread_stderr_buffstderr_threadSend a signal to the process.CTRL_C_EVENTCTRL_BREAK_EVENTUnsupported signal: {}Terminates the process.TerminateProcessSTILL_ACTIVE_posix_spawnExecute program using os.posix_spawn().SIGXFZsetsigdeffile_actionsExecute program (POSIX version)orig_executableerrpipe_readerrpipe_writelow_fds_to_closelow_fdenv_listillegal environment variable nameexecutable_listfds_to_keeperrpipe_data50000_handle_exitstatusexception_namehex_errnoerr_msgBad exception data from child: {!r}child_exception_typeerrno_numnoexecchild_exec_never_callederr_filename_WIFSIGNALED_WTERMSIG_WIFEXITED_WEXITSTATUS_WIFSTOPPED_WSTOPSIGAll callers to this function MUST hold self._waitpid_lock.Unknown child exit status!_waitpid_WNOHANG_ECHILDCheck if child process has terminated. Returns returncode + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + _try_waitwait_flagsInternal implementation of wait() on POSIX.0.00050.05.05_fileobj2output_save_inputinput_view_check_timeout(..., skip_check_and_raise=True) failed to raise TimeoutExpired.'_check_timeout(..., skip_check_and_raise=True) ''failed to raise TimeoutExpired.'_input_offsetTerminate the process with SIGTERM + Kill the process with SIGKILL + # subprocess - Subprocesses with accessible I/O streams# For more information about this module, see PEP 324.# Copyright (c) 2003-2005 by Peter Astrand # See http://www.python.org/2.4/license for licensing details.# NOTE: We intentionally exclude list2cmdline as it is# considered an internal implementation detail. issue10838.# Exception classes used by this module.# There's no obvious reason to set this, but allow it anyway so# .stdout is a transparent alias for .output# When select or poll has indicated that the file is writable,# we can write up to _PIPE_BUF bytes without risk of blocking.# POSIX defines PIPE_BUF as >= 512.# On Windows we just need to close `Popen._handle` when we no longer need# it, so that the kernel can free it. `Popen._handle` gets closed# implicitly when the `Popen` instance is finalized (see `Handle.__del__`,# which is calling `CloseHandle` as requested in [1]), so there is nothing# for `_cleanup` to do.# [1] https://docs.microsoft.com/en-us/windows/desktop/ProcThread/# creating-processes# This lists holds Popen instances for which the underlying process had not# exited at the time its __del__ method got called: those processes are# wait()ed for synchronously from _cleanup() when a new Popen object is# created, to avoid zombie processes.# This can happen if two threads create a new Popen instance.# It's harmless that it was already removed, so ignore.# XXX This function is only used by multiprocessing and the test suite,# but it's here so that it can be imported when Python is compiled without# threads.# 'inspect': 'i',# 'interactive': 'i',# -O is handled in _optim_args_from_interpreter_flags()# -W options# -X options# Including KeyboardInterrupt, wait handled that.# We don't call p.wait() again as p.__exit__ does that for us.# Explicitly passing input=None was previously equivalent to passing an# empty string. That is maintained here for backwards compatibility.# Windows accumulates the output in a single blocking# read() call run on child threads, with the timeout# being done in a join() on those threads. communicate()# _after_ kill() is required to collect that and add it# to the exception.# POSIX _communicate already populated the output so# far into the TimeoutExpired exception.# Including KeyboardInterrupt, communicate handled that.# We don't call process.wait() as .__exit__ does that for us.# See# http://msdn.microsoft.com/en-us/library/17w5ykft.aspx# or search http://msdn.microsoft.com for# "Parsing C++ Command-Line Arguments"# Add a space to separate this argument from the others# Don't know if we need to double yet.# Double backslashes.# Normal char# Add remaining backslashes, if any.# Various tools for executing commands and looking at their output and status.# os.posix_spawn() is not available# posix_spawn() is a syscall on macOS and properly reports errors# Check libc name and runtime libc version# parse 'glibc 2.28' as ('glibc', (2, 28))# reject unknown format# glibc 2.24 has a new Linux posix_spawn implementation using vfork# which properly reports errors to the parent process.# Note: Don't use the implementation in earlier glibc because it doesn't# use vfork (even if glibc 2.26 added a pipe to properly report errors# to the parent process).# By default, assume that posix_spawn() does not properly report errors.# Set here since __del__ checks it# Held while anything is calling waitpid before returncode has been# updated to prevent clobbering returncode if wait() or poll() are# called from multiple threads at once. After acquiring the lock,# code must re-check self.returncode to see if another thread just# finished a waitpid() call.# Restore default# POSIX# Validate the combinations of text and universal_newlines# Input and output objects. The general principle is like# this:# Parent Child# ------ -----# p2cwrite ---stdin---> p2cread# c2pread <--stdout--- c2pwrite# errread <--stderr--- errwrite# On POSIX, the child objects are file descriptors. On# Windows, these are Windows file handles. The parent objects# are file descriptors on both platforms. The parent objects# are -1 when not using PIPEs. The child objects are -1# when not redirecting.# We wrap OS handles *before* launching the child, otherwise a# quickly terminating child could make our fds unwrappable# (see #8458).# How long to resume waiting on a child after the first ^C.# There is no right value for this. The purpose is to be polite# yet remain good for interactive users trying to exit a tool.# 1/xkcd221.getRandomNumber()# Use the default buffer size for the underlying binary streams# since they don't support line buffering.# Cleanup if the child failed starting.# Ignore EBADF or other errors.# universal_newlines as retained as an alias of text_mode for API# compatibility. bpo-31756# Flushing a BufferedWriter may raise an error# https://bugs.python.org/issue25942# In the case of a KeyboardInterrupt we assume the SIGINT# was also already sent to our child processes. We can't# block indefinitely as that is not user friendly.# If we have not already waited a brief amount of time in# an interrupted .wait() or .communicate() call, do so here# for consistency.# Note that this has been done.# resume the KeyboardInterrupt# Wait for the process to terminate, to avoid zombies.# We didn't get to successfully create a child process.# Not reading subprocess exit status creates a zombie process which# is only destroyed at the parent python process exit# In case the child hasn't been waited on, check if it's done.# Child is still running, keep us alive until we can wait on it.# communicate() must ignore broken pipe errors.# bpo-19612, bpo-30418: On Windows, stdin.write() fails# with EINVAL if the child process exited or if the child# process is still running but closed the pipe.# Optimization: If we are not worried about timeouts, we haven't# started communicating, and we have one or zero pipes, using select()# or threads is unnecessary.# See the detailed comment in .wait().# nothing else should wait.# The first keyboard interrupt waits briefly for the child to# exit under the common assumption that it also received the ^C# generated SIGINT and will exit rapidly.# self._devnull is not always defined.# Prevent a double close of these handles/fds from __init__ on error.# Windows methods# Assuming file-like object# An handle with it's lowest two bits set might be a special console# handle that if passed in lpAttributeList["handle_list"], will# cause it to fail.# Process startup details# bpo-34044: Copy STARTUPINFO since it is modified above,# so the caller can reuse it multiple times.# If we were given an handle_list or need to create one# When using the handle_list we always request to inherit# handles but the only handles that will be inherited are# the ones in the handle_list# Start the process# no special security# Child is launched. Close the parent's copy of those pipe# handles that only the child should have open. You need# to make sure that no handles to the write end of the# output pipe are maintained in this process or else the# pipe will not close when the child process exits and the# ReadFile will hang.# Retain the process handle, but close the thread handle# API note: Returns immediately if timeout_millis == 0.# Start reader threads feeding into a list hanging off of this# object, unless they've already been started.# Wait for the reader threads, or time out. If we time out, the# threads remain reading and the fds left open in case the user# calls communicate again.# Collect the output from and close both pipes, now that we know# both have been read successfully.# All data exchanged. Translate lists into strings.# Don't signal a process that we know has already died.# Don't terminate a process that we know has already died.# ERROR_ACCESS_DENIED (winerror 5) is received when the# process already died.# POSIX methods# child's stdout is not set, use parent's stdout# See _Py_RestoreSignals() in Python/pylifecycle.c# On Android the default shell is at '/system/bin/sh'.# For transferring possible exec failure from child to parent.# Data format: "exception name:hex errno:description"# Pickle is not used; it is complex and involves memory allocation.# errpipe_write must not be in the standard io 0, 1, or 2 fd range.# We must avoid complex work that could involve# malloc or free in the child process to avoid# potential deadlocks, thus we do all this here.# and pass it to fork_exec()# Use execv instead of execve.# This matches the behavior of os._execvpe().# be sure the FD is closed no matter what# Wait for exec to fail or succeed; possibly raising an# exception (limited in size)# The encoding here should match the encoding# written in by the subprocess implementations# like _posixsubprocess# The error must be from chdir(cwd).# This method is called (indirectly) by __del__, so it cannot# refer to anything outside of its local scope.# Should never happen# Something else is busy calling waitpid. Don't allow two# at once. We know nothing yet.# Another thread waited.# This happens if SIGCLD is set to be ignored or# waiting for child processes has otherwise been# disabled for our process. This child is dead, we# can't get the status.# http://bugs.python.org/issue15756# This happens if SIGCLD is set to be ignored or waiting# for child processes has otherwise been disabled for our# process. This child is dead, we can't get the status.# Enter a busy loop if we have a timeout. This busy loop was# cribbed from Lib/threading.py in Thread.wait() at r71065.# 500 us -> initial delay of 1 ms# Check the pid and loop as waitpid has been known to# return 0 even without WNOHANG in odd situations.# http://bugs.python.org/issue14396.# Flush stdio buffer. This might block, if the user has# been writing to .stdin in an uncontrolled fashion.# communicate() must ignore BrokenPipeError.# Only create this mapping if we haven't already.# Impossible :)# XXX Rewrite these to use non-blocking I/O on the file# objects; they are no longer using C stdio!# Translate newlines, if requested.# This also turns bytes into strings.# This method is called from the _communicate_with_*() methods# so that if we time out while communicating, we can continue# sending input if we retry.# Skip signalling a process that we know has already died.b'Subprocesses with accessible I/O streams + +This module allows you to spawn processes, connect to their +input/output/error pipes, and obtain their return codes. + +For a complete description of this module see the Python documentation. + +Main API +======== +run(...): Runs a command, waits for it to complete, then returns a + CompletedProcess instance. +Popen(...): A class for flexibly executing a command in a new process + +Constants +--------- +DEVNULL: Special value that indicates that os.devnull should be used +PIPE: Special value that indicates a pipe should be created +STDOUT: Special value that indicates that stderr should go to stdout + + +Older API +========= +call(...): Runs a command, waits for it to complete, then returns + the return code. +check_call(...): Same as call() but raises CalledProcessError() + if return code is not 0 +check_output(...): Same as check_call() but returns the contents of + stdout instead of a return code +getoutput(...): Runs a command in the shell, waits for it to complete, + then returns the output +getstatusoutput(...): Runs a command in the shell, waits for it to complete, + then returns a (exitcode, output) tuple +'u'Subprocesses with accessible I/O streams + +This module allows you to spawn processes, connect to their +input/output/error pipes, and obtain their return codes. + +For a complete description of this module see the Python documentation. + +Main API +======== +run(...): Runs a command, waits for it to complete, then returns a + CompletedProcess instance. +Popen(...): A class for flexibly executing a command in a new process + +Constants +--------- +DEVNULL: Special value that indicates that os.devnull should be used +PIPE: Special value that indicates a pipe should be created +STDOUT: Special value that indicates that stderr should go to stdout + + +Older API +========= +call(...): Runs a command, waits for it to complete, then returns + the return code. +check_call(...): Same as call() but raises CalledProcessError() + if return code is not 0 +check_output(...): Same as check_call() but returns the contents of + stdout instead of a return code +getoutput(...): Runs a command in the shell, waits for it to complete, + then returns the output +getstatusoutput(...): Runs a command in the shell, waits for it to complete, + then returns a (exitcode, output) tuple +'b'PIPE'u'PIPE'b'STDOUT'u'STDOUT'b'check_call'u'check_call'b'getstatusoutput'u'getstatusoutput'b'getoutput'u'getoutput'b'check_output'u'check_output'b'CalledProcessError'u'CalledProcessError'b'DEVNULL'u'DEVNULL'b'SubprocessError'u'SubprocessError'b'TimeoutExpired'u'TimeoutExpired'b'CompletedProcess'u'CompletedProcess'b'CREATE_NEW_CONSOLE'u'CREATE_NEW_CONSOLE'b'CREATE_NEW_PROCESS_GROUP'u'CREATE_NEW_PROCESS_GROUP'b'STD_INPUT_HANDLE'u'STD_INPUT_HANDLE'b'STD_OUTPUT_HANDLE'u'STD_OUTPUT_HANDLE'b'STD_ERROR_HANDLE'u'STD_ERROR_HANDLE'b'SW_HIDE'u'SW_HIDE'b'STARTF_USESTDHANDLES'u'STARTF_USESTDHANDLES'b'STARTF_USESHOWWINDOW'u'STARTF_USESHOWWINDOW'b'STARTUPINFO'u'STARTUPINFO'b'ABOVE_NORMAL_PRIORITY_CLASS'u'ABOVE_NORMAL_PRIORITY_CLASS'b'BELOW_NORMAL_PRIORITY_CLASS'u'BELOW_NORMAL_PRIORITY_CLASS'b'HIGH_PRIORITY_CLASS'u'HIGH_PRIORITY_CLASS'b'IDLE_PRIORITY_CLASS'u'IDLE_PRIORITY_CLASS'b'NORMAL_PRIORITY_CLASS'u'NORMAL_PRIORITY_CLASS'b'REALTIME_PRIORITY_CLASS'u'REALTIME_PRIORITY_CLASS'b'CREATE_NO_WINDOW'u'CREATE_NO_WINDOW'b'DETACHED_PROCESS'u'DETACHED_PROCESS'b'CREATE_DEFAULT_ERROR_MODE'u'CREATE_DEFAULT_ERROR_MODE'b'CREATE_BREAKAWAY_FROM_JOB'u'CREATE_BREAKAWAY_FROM_JOB'b'Raised when run() is called with check=True and the process + returns a non-zero exit status. + + Attributes: + cmd, returncode, stdout, stderr, output + 'u'Raised when run() is called with check=True and the process + returns a non-zero exit status. + + Attributes: + cmd, returncode, stdout, stderr, output + 'b'Command '%s' died with %r.'u'Command '%s' died with %r.'b'Command '%s' died with unknown signal %d.'u'Command '%s' died with unknown signal %d.'b'Command '%s' returned non-zero exit status %d.'u'Command '%s' returned non-zero exit status %d.'b'Alias for output attribute, to match stderr'u'Alias for output attribute, to match stderr'b'This exception is raised when the timeout expires while waiting for a + child process. + + Attributes: + cmd, output, stdout, stderr, timeout + 'u'This exception is raised when the timeout expires while waiting for a + child process. + + Attributes: + cmd, output, stdout, stderr, timeout + 'b'Command '%s' timed out after %s seconds'u'Command '%s' timed out after %s seconds'b'handle_list'u'handle_list'b'already closed'u'already closed'b'%s(%d)'u'%s(%d)'b'PIPE_BUF'u'PIPE_BUF'b'Return a list of command-line arguments reproducing the current + settings in sys.flags, sys.warnoptions and sys._xoptions.'u'Return a list of command-line arguments reproducing the current + settings in sys.flags, sys.warnoptions and sys._xoptions.'b'dont_write_bytecode'u'dont_write_bytecode'b'no_site'u'no_site'b'bytes_warning'u'bytes_warning'b'-I'u'-I'b'-E'u'-E'b'_xoptions'u'_xoptions'b'error::BytesWarning'u'error::BytesWarning'b'default::BytesWarning'u'default::BytesWarning'b'-W'u'-W'b'faulthandler'b'tracemalloc'u'tracemalloc'b'importtime'u'importtime'b'showalloccount'u'showalloccount'b'showrefcount'u'showrefcount'b'Run command with arguments. Wait for command to complete or + timeout, then return the returncode attribute. + + The arguments are the same as for the Popen constructor. Example: + + retcode = call(["ls", "-l"]) + 'u'Run command with arguments. Wait for command to complete or + timeout, then return the returncode attribute. + + The arguments are the same as for the Popen constructor. Example: + + retcode = call(["ls", "-l"]) + 'b'Run command with arguments. Wait for command to complete. If + the exit code was zero then return, otherwise raise + CalledProcessError. The CalledProcessError object will have the + return code in the returncode attribute. + + The arguments are the same as for the call function. Example: + + check_call(["ls", "-l"]) + 'u'Run command with arguments. Wait for command to complete. If + the exit code was zero then return, otherwise raise + CalledProcessError. The CalledProcessError object will have the + return code in the returncode attribute. + + The arguments are the same as for the call function. Example: + + check_call(["ls", "-l"]) + 'b'Run command with arguments and return its output. + + If the exit code was non-zero it raises a CalledProcessError. The + CalledProcessError object will have the return code in the returncode + attribute and output in the output attribute. + + The arguments are the same as for the Popen constructor. Example: + + >>> check_output(["ls", "-l", "/dev/null"]) + b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' + + The stdout argument is not allowed as it is used internally. + To capture standard error in the result, use stderr=STDOUT. + + >>> check_output(["/bin/sh", "-c", + ... "ls -l non_existent_file ; exit 0"], + ... stderr=STDOUT) + b'ls: non_existent_file: No such file or directory\n' + + There is an additional optional argument, "input", allowing you to + pass a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it too will be used internally. Example: + + >>> check_output(["sed", "-e", "s/foo/bar/"], + ... input=b"when in the course of fooman events\n") + b'when in the course of barman events\n' + + By default, all communication is in bytes, and therefore any "input" + should be bytes, and the return value will be bytes. If in text mode, + any "input" should be a string, and the return value will be a string + decoded according to locale encoding, or by "encoding" if set. Text mode + is triggered by setting any of text, encoding, errors or universal_newlines. + 'u'Run command with arguments and return its output. + + If the exit code was non-zero it raises a CalledProcessError. The + CalledProcessError object will have the return code in the returncode + attribute and output in the output attribute. + + The arguments are the same as for the Popen constructor. Example: + + >>> check_output(["ls", "-l", "/dev/null"]) + b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' + + The stdout argument is not allowed as it is used internally. + To capture standard error in the result, use stderr=STDOUT. + + >>> check_output(["/bin/sh", "-c", + ... "ls -l non_existent_file ; exit 0"], + ... stderr=STDOUT) + b'ls: non_existent_file: No such file or directory\n' + + There is an additional optional argument, "input", allowing you to + pass a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it too will be used internally. Example: + + >>> check_output(["sed", "-e", "s/foo/bar/"], + ... input=b"when in the course of fooman events\n") + b'when in the course of barman events\n' + + By default, all communication is in bytes, and therefore any "input" + should be bytes, and the return value will be bytes. If in text mode, + any "input" should be a string, and the return value will be a string + decoded according to locale encoding, or by "encoding" if set. Text mode + is triggered by setting any of text, encoding, errors or universal_newlines. + 'b'stdout argument not allowed, it will be overridden.'u'stdout argument not allowed, it will be overridden.'b'universal_newlines'u'universal_newlines'b'A process that has finished running. + + This is returned by run(). + + Attributes: + args: The list or str args passed to run(). + returncode: The exit code of the process, negative for signals. + stdout: The standard output (None if not captured). + stderr: The standard error (None if not captured). + 'u'A process that has finished running. + + This is returned by run(). + + Attributes: + args: The list or str args passed to run(). + returncode: The exit code of the process, negative for signals. + stdout: The standard output (None if not captured). + stderr: The standard error (None if not captured). + 'b'args={!r}'u'args={!r}'b'returncode={!r}'u'returncode={!r}'b'stdout={!r}'u'stdout={!r}'b'stderr={!r}'u'stderr={!r}'b'Raise CalledProcessError if the exit code is non-zero.'u'Raise CalledProcessError if the exit code is non-zero.'b'Run command with arguments and return a CompletedProcess instance. + + The returned instance will have attributes args, returncode, stdout and + stderr. By default, stdout and stderr are not captured, and those attributes + will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. + + If check is True and the exit code was non-zero, it raises a + CalledProcessError. The CalledProcessError object will have the return code + in the returncode attribute, and output & stderr attributes if those streams + were captured. + + If timeout is given, and the process takes too long, a TimeoutExpired + exception will be raised. + + There is an optional argument "input", allowing you to + pass bytes or a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it will be used internally. + + By default, all communication is in bytes, and therefore any "input" should + be bytes, and the stdout and stderr will be bytes. If in text mode, any + "input" should be a string, and stdout and stderr will be strings decoded + according to locale encoding, or by "encoding" if set. Text mode is + triggered by setting any of text, encoding, errors or universal_newlines. + + The other arguments are the same as for the Popen constructor. + 'u'Run command with arguments and return a CompletedProcess instance. + + The returned instance will have attributes args, returncode, stdout and + stderr. By default, stdout and stderr are not captured, and those attributes + will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. + + If check is True and the exit code was non-zero, it raises a + CalledProcessError. The CalledProcessError object will have the return code + in the returncode attribute, and output & stderr attributes if those streams + were captured. + + If timeout is given, and the process takes too long, a TimeoutExpired + exception will be raised. + + There is an optional argument "input", allowing you to + pass bytes or a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it will be used internally. + + By default, all communication is in bytes, and therefore any "input" should + be bytes, and the stdout and stderr will be bytes. If in text mode, any + "input" should be a string, and stdout and stderr will be strings decoded + according to locale encoding, or by "encoding" if set. Text mode is + triggered by setting any of text, encoding, errors or universal_newlines. + + The other arguments are the same as for the Popen constructor. + 'b'stdin and input arguments may not both be used.'u'stdin and input arguments may not both be used.'b'stdout and stderr arguments may not be used with capture_output.'u'stdout and stderr arguments may not be used with capture_output.'b' + Translate a sequence of arguments into a command line + string, using the same rules as the MS C runtime: + + 1) Arguments are delimited by white space, which is either a + space or a tab. + + 2) A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + + 3) A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + + 4) Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + + 5) If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + 'u' + Translate a sequence of arguments into a command line + string, using the same rules as the MS C runtime: + + 1) Arguments are delimited by white space, which is either a + space or a tab. + + 2) A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + + 3) A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + + 4) Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + + 5) If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + 'b'Return (exitcode, output) of executing cmd in a shell. + + Execute the string 'cmd' in a shell with 'check_output' and + return a 2-tuple (status, output). The locale encoding is used + to decode the output and process newlines. + + A trailing newline is stripped from the output. + The exit status for the command can be interpreted + according to the rules for the function 'wait'. Example: + + >>> import subprocess + >>> subprocess.getstatusoutput('ls /bin/ls') + (0, '/bin/ls') + >>> subprocess.getstatusoutput('cat /bin/junk') + (1, 'cat: /bin/junk: No such file or directory') + >>> subprocess.getstatusoutput('/bin/junk') + (127, 'sh: /bin/junk: not found') + >>> subprocess.getstatusoutput('/bin/kill $$') + (-15, '') + 'u'Return (exitcode, output) of executing cmd in a shell. + + Execute the string 'cmd' in a shell with 'check_output' and + return a 2-tuple (status, output). The locale encoding is used + to decode the output and process newlines. + + A trailing newline is stripped from the output. + The exit status for the command can be interpreted + according to the rules for the function 'wait'. Example: + + >>> import subprocess + >>> subprocess.getstatusoutput('ls /bin/ls') + (0, '/bin/ls') + >>> subprocess.getstatusoutput('cat /bin/junk') + (1, 'cat: /bin/junk: No such file or directory') + >>> subprocess.getstatusoutput('/bin/junk') + (127, 'sh: /bin/junk: not found') + >>> subprocess.getstatusoutput('/bin/kill $$') + (-15, '') + 'b'Return output (stdout or stderr) of executing cmd in a shell. + + Like getstatusoutput(), except the exit status is ignored and the return + value is a string containing the command's output. Example: + + >>> import subprocess + >>> subprocess.getoutput('ls /bin/ls') + '/bin/ls' + 'u'Return output (stdout or stderr) of executing cmd in a shell. + + Like getstatusoutput(), except the exit status is ignored and the return + value is a string containing the command's output. Example: + + >>> import subprocess + >>> subprocess.getoutput('ls /bin/ls') + '/bin/ls' + 'b'Check if posix_spawn() can be used for subprocess. + + subprocess requires a posix_spawn() implementation that properly reports + errors to the parent process, & sets errno on the following failures: + + * Process attribute actions failed. + * File actions failed. + * exec() failed. + + Prefer an implementation which can use vfork() in some cases for best + performance. + 'u'Check if posix_spawn() can be used for subprocess. + + subprocess requires a posix_spawn() implementation that properly reports + errors to the parent process, & sets errno on the following failures: + + * Process attribute actions failed. + * File actions failed. + * exec() failed. + + Prefer an implementation which can use vfork() in some cases for best + performance. + 'b'posix_spawn'u'posix_spawn'b' Execute a child program in a new process. + + For a complete description of the arguments see the Python documentation. + + Arguments: + args: A string, or a sequence of program arguments. + + bufsize: supplied as the buffering argument to the open() function when + creating the stdin/stdout/stderr pipe file objects + + executable: A replacement program to execute. + + stdin, stdout and stderr: These specify the executed programs' standard + input, standard output and standard error file handles, respectively. + + preexec_fn: (POSIX only) An object to be called in the child process + just before the child is executed. + + close_fds: Controls closing or inheriting of file descriptors. + + shell: If true, the command will be executed through the shell. + + cwd: Sets the current directory before the child is executed. + + env: Defines the environment variables for the new process. + + text: If true, decode stdin, stdout and stderr using the given encoding + (if set) or the system default otherwise. + + universal_newlines: Alias of text, provided for backwards compatibility. + + startupinfo and creationflags (Windows only) + + restore_signals (POSIX only) + + start_new_session (POSIX only) + + pass_fds (POSIX only) + + encoding and errors: Text mode encoding and error handling to use for + file objects stdin, stdout and stderr. + + Attributes: + stdin, stdout, stderr, pid, returncode + 'u' Execute a child program in a new process. + + For a complete description of the arguments see the Python documentation. + + Arguments: + args: A string, or a sequence of program arguments. + + bufsize: supplied as the buffering argument to the open() function when + creating the stdin/stdout/stderr pipe file objects + + executable: A replacement program to execute. + + stdin, stdout and stderr: These specify the executed programs' standard + input, standard output and standard error file handles, respectively. + + preexec_fn: (POSIX only) An object to be called in the child process + just before the child is executed. + + close_fds: Controls closing or inheriting of file descriptors. + + shell: If true, the command will be executed through the shell. + + cwd: Sets the current directory before the child is executed. + + env: Defines the environment variables for the new process. + + text: If true, decode stdin, stdout and stderr using the given encoding + (if set) or the system default otherwise. + + universal_newlines: Alias of text, provided for backwards compatibility. + + startupinfo and creationflags (Windows only) + + restore_signals (POSIX only) + + start_new_session (POSIX only) + + pass_fds (POSIX only) + + encoding and errors: Text mode encoding and error handling to use for + file objects stdin, stdout and stderr. + + Attributes: + stdin, stdout, stderr, pid, returncode + 'b'Create new Popen instance.'u'Create new Popen instance.'b'bufsize must be an integer'u'bufsize must be an integer'b'preexec_fn is not supported on Windows platforms'u'preexec_fn is not supported on Windows platforms'b'pass_fds overriding close_fds.'u'pass_fds overriding close_fds.'b'startupinfo is only supported on Windows platforms'u'startupinfo is only supported on Windows platforms'b'creationflags is only supported on Windows platforms'u'creationflags is only supported on Windows platforms'b'Cannot disambiguate when both text and universal_newlines are supplied but different. Pass one or the other.'u'Cannot disambiguate when both text and universal_newlines are supplied but different. Pass one or the other.'b'_devnull'u'_devnull'b'subprocess %s is still running'u'subprocess %s is still running'b'Interact with process: Send data to stdin and close it. + Read data from stdout and stderr, until end-of-file is + reached. Wait for process to terminate. + + The optional "input" argument should be data to be sent to the + child process, or None, if no data should be sent to the child. + communicate() returns a tuple (stdout, stderr). + + By default, all communication is in bytes, and therefore any + "input" should be bytes, and the (stdout, stderr) will be bytes. + If in text mode (indicated by self.text_mode), any "input" should + be a string, and (stdout, stderr) will be strings decoded + according to locale encoding, or by "encoding" if set. Text mode + is triggered by setting any of text, encoding, errors or + universal_newlines. + 'u'Interact with process: Send data to stdin and close it. + Read data from stdout and stderr, until end-of-file is + reached. Wait for process to terminate. + + The optional "input" argument should be data to be sent to the + child process, or None, if no data should be sent to the child. + communicate() returns a tuple (stdout, stderr). + + By default, all communication is in bytes, and therefore any + "input" should be bytes, and the (stdout, stderr) will be bytes. + If in text mode (indicated by self.text_mode), any "input" should + be a string, and (stdout, stderr) will be strings decoded + according to locale encoding, or by "encoding" if set. Text mode + is triggered by setting any of text, encoding, errors or + universal_newlines. + 'b'Cannot send input after starting communication'u'Cannot send input after starting communication'b'Check if child process has terminated. Set and return returncode + attribute.'u'Check if child process has terminated. Set and return returncode + attribute.'b'Convenience for _communicate when computing timeouts.'u'Convenience for _communicate when computing timeouts.'b'Convenience for checking if a timeout has expired.'u'Convenience for checking if a timeout has expired.'b'Wait for child process to terminate; returns self.returncode.'u'Wait for child process to terminate; returns self.returncode.'b'Construct and return tuple with IO objects: + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite + 'u'Construct and return tuple with IO objects: + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite + 'b'Return a duplicate of handle, which is inheritable'u'Return a duplicate of handle, which is inheritable'b'Filter out console handles that can't be used + in lpAttributeList["handle_list"] and make sure the list + isn't empty. This also removes duplicate handles.'u'Filter out console handles that can't be used + in lpAttributeList["handle_list"] and make sure the list + isn't empty. This also removes duplicate handles.'b'Execute program (MS Windows version)'u'Execute program (MS Windows version)'b'pass_fds not supported on Windows.'u'pass_fds not supported on Windows.'b'bytes args is not allowed on Windows'u'bytes args is not allowed on Windows'b'path-like args is not allowed when shell is true'u'path-like args is not allowed when shell is true'b'startupinfo.lpAttributeList['handle_list'] overriding close_fds'u'startupinfo.lpAttributeList['handle_list'] overriding close_fds'b'COMSPEC'u'COMSPEC'b'cmd.exe'u'cmd.exe'b'{} /c "{}"'u'{} /c "{}"'b'subprocess.Popen'u'subprocess.Popen'b'Check if child process has terminated. Returns returncode + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + 'u'Check if child process has terminated. Returns returncode + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + 'b'Internal implementation of wait() on Windows.'u'Internal implementation of wait() on Windows.'b'_stdout_buff'u'_stdout_buff'b'_stderr_buff'u'_stderr_buff'b'Send a signal to the process.'u'Send a signal to the process.'b'Unsupported signal: {}'u'Unsupported signal: {}'b'Terminates the process.'u'Terminates the process.'b'Execute program using os.posix_spawn().'u'Execute program using os.posix_spawn().'b'SIGPIPE'u'SIGPIPE'b'SIGXFZ'u'SIGXFZ'b'SIGXFSZ'u'SIGXFSZ'b'setsigdef'u'setsigdef'b'file_actions'u'file_actions'b'Execute program (POSIX version)'u'Execute program (POSIX version)'b'illegal environment variable name'u'illegal environment variable name'b'Bad exception data from child: {!r}'u'Bad exception data from child: {!r}'b'noexec'u'noexec'b'All callers to this function MUST hold self._waitpid_lock.'u'All callers to this function MUST hold self._waitpid_lock.'b'Unknown child exit status!'u'Unknown child exit status!'b'Check if child process has terminated. Returns returncode + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + 'u'Check if child process has terminated. Returns returncode + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + 'b'Internal implementation of wait() on POSIX.'u'Internal implementation of wait() on POSIX.'b'_check_timeout(..., skip_check_and_raise=True) failed to raise TimeoutExpired.'u'_check_timeout(..., skip_check_and_raise=True) failed to raise TimeoutExpired.'b'Terminate the process with SIGTERM + 'u'Terminate the process with SIGTERM + 'b'Kill the process with SIGKILL + 'u'Kill the process with SIGKILL + 'create_subprocess_execcreate_subprocess_shellSubprocessStreamProtocolLike StreamReaderProtocol, but for a subprocess._pipe_fds_stdin_closedstdout_transportstderr_transportstdin_transport_maybe_close_transportWait until the process exit and return the process return code._feed_stdin%r communicate: feed stdin (%s bytes)%r communicate: stdin got %r%r communicate: close stdin_read_stream%r communicate: read %s%r communicate: close %sThe loop argument is deprecated since Python 3.8 and scheduled for removal in Python 3.10."The loop argument is deprecated since Python 3.8 "# communicate() ignores BrokenPipeError and ConnectionResetErrorb'create_subprocess_exec'u'create_subprocess_exec'b'create_subprocess_shell'u'create_subprocess_shell'b'Like StreamReaderProtocol, but for a subprocess.'u'Like StreamReaderProtocol, but for a subprocess.'b'Wait until the process exit and return the process return code.'u'Wait until the process exit and return the process return code.'b'%r communicate: feed stdin (%s bytes)'u'%r communicate: feed stdin (%s bytes)'b'%r communicate: stdin got %r'u'%r communicate: stdin got %r'b'%r communicate: close stdin'u'%r communicate: close stdin'b'%r communicate: read %s'u'%r communicate: read %s'b'%r communicate: close %s'u'%r communicate: close %s'b'The loop argument is deprecated since Python 3.8 and scheduled for removal in Python 3.10.'u'The loop argument is deprecated since Python 3.8 and scheduled for removal in Python 3.10.'u'asyncio.subprocess'_call_if_existsA simple test suite that doesn't provide class or module shared fixtures. + _removed_tests<%s tests=%s>cases{} is not callableTestCases and TestSuites must be instantiated before passing them to addTest()"TestCases and TestSuites must be instantiated ""before passing them to addTest()"tests must be an iterable of tests, not a stringStop holding a reference to the TestCase at index.Run the tests without collecting errors in a TestResultA test suite is a composite test consisting of a number of TestCases. + + For use, create an instance of TestSuite, then add test case instances. + When all tests have been added, the suite can be passed to a test + runner, such as TextTestRunner. It will run the individual test cases + in the order in which they were added, aggregating the results. When + subclassing, do not forget to call the base class constructor. + topLevel_isnotsuite_tearDownPreviousClass_handleModuleFixture_handleClassSetUp_handleModuleTearDown_DebugResultpreviousClasscurrentClass_createClassOrModuleLevelException_get_previous_modulepreviousModulecurrentModulesetUpModuleerrorName_addClassOrModuleLevelException_ErrorHoldertearDownModule + Placeholder for a TestCase inside a result. As far as a TestResult + is concerned, this looks exactly like a unit test. Used to insert + arbitrary errors into a test suite run. + A crude way to tell apart testcases and suites with duck-typingUsed by the TestSuite to hold previous class when running in debug.# sanity checks# support for suite implementations that have overridden self._tests# Some unittest tests add non TestCase/TestSuite objects to# the suite.################################# test may actually be a function# so its class will be a builtin-type# Inspired by the ErrorHolder from Twisted:# http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py# attribute used by TestResult._exc_info_to_string# could call result.addError(...) - but this test-like object# shouldn't be run anywayb'A simple test suite that doesn't provide class or module shared fixtures. + 'u'A simple test suite that doesn't provide class or module shared fixtures. + 'b'<%s tests=%s>'u'<%s tests=%s>'b'{} is not callable'u'{} is not callable'b'TestCases and TestSuites must be instantiated before passing them to addTest()'u'TestCases and TestSuites must be instantiated before passing them to addTest()'b'tests must be an iterable of tests, not a string'u'tests must be an iterable of tests, not a string'b'Stop holding a reference to the TestCase at index.'u'Stop holding a reference to the TestCase at index.'b'countTestCases'u'countTestCases'b'Run the tests without collecting errors in a TestResult'u'Run the tests without collecting errors in a TestResult'b'A test suite is a composite test consisting of a number of TestCases. + + For use, create an instance of TestSuite, then add test case instances. + When all tests have been added, the suite can be passed to a test + runner, such as TextTestRunner. It will run the individual test cases + in the order in which they were added, aggregating the results. When + subclassing, do not forget to call the base class constructor. + 'u'A test suite is a composite test consisting of a number of TestCases. + + For use, create an instance of TestSuite, then add test case instances. + When all tests have been added, the suite can be passed to a test + runner, such as TextTestRunner. It will run the individual test cases + in the order in which they were added, aggregating the results. When + subclassing, do not forget to call the base class constructor. + 'b'_testRunEntered'u'_testRunEntered'b'_classSetupFailed'u'_classSetupFailed'b'_moduleSetUpFailed'u'_moduleSetUpFailed'b'_previousTestClass'u'_previousTestClass'b'setUpClass'u'setUpClass'b'_setupStdout'u'_setupStdout'b'_restoreStdout'u'_restoreStdout'b'setUpModule'u'setUpModule'b'tearDownModule'u'tearDownModule'b'tearDownClass'u'tearDownClass'b' + Placeholder for a TestCase inside a result. As far as a TestResult + is concerned, this looks exactly like a unit test. Used to insert + arbitrary errors into a test suite run. + 'u' + Placeholder for a TestCase inside a result. As far as a TestResult + is concerned, this looks exactly like a unit test. Used to insert + arbitrary errors into a test suite run. + 'b''u''b'A crude way to tell apart testcases and suites with duck-typing'u'A crude way to tell apart testcases and suites with duck-typing'b'Used by the TestSuite to hold previous class when running in debug.'u'Used by the TestSuite to hold previous class when running in debug.'u'unittest.suite'u'suite'Access to Python's configuration information.get_config_h_filenameget_config_varsget_makefile_filenameget_path_namesget_pathsget_platformget_python_versionget_scheme_namesparse_config_h_ALWAYS_STR{installed_base}/lib/python{py_version_short}{platbase}/lib/python{py_version_short}platstdlib{base}/lib/python{py_version_short}/site-packagespurelib{platbase}/lib/python{py_version_short}/site-packagesplatlib{installed_base}/include/python{py_version_short}{abiflags}{installed_platbase}/include/python{py_version_short}{abiflags}platinclude{base}/binscripts{base}posix_prefix{installed_base}/lib/python{base}/lib/python{installed_base}/include/pythonposix_home{installed_base}/Lib{base}/Lib{base}/Lib/site-packages{installed_base}/Include{base}/Scripts{userbase}/Python{py_version_nodot}{userbase}/Python{py_version_nodot}/site-packages{userbase}/Python{py_version_nodot}/Include{userbase}/Python{py_version_nodot}/Scripts{userbase}nt_user{userbase}/lib/python{py_version_short}{userbase}/lib/python{py_version_short}/site-packages{userbase}/include/python{py_version_short}{userbase}/binposix_user{userbase}/lib/python{userbase}/lib/python/site-packages{userbase}/includeosx_framework_user_INSTALL_SCHEMES_SCHEME_KEYS_PY_VERSION_PY_VERSION_SHORT%d%d_PY_VERSION_SHORT_NO_DOT_PREFIX_BASE_PREFIX_EXEC_PREFIX_BASE_EXEC_PREFIX_CONFIG_VARS_USER_BASE_safe_realpath_PROJECT_BASE\pcbuild\win32\pcbuild\amd64_PYTHON_PROJECT_BASE_is_python_source_dirSetupSetup.local_home_sys_home_fix_pcbuildPCbuildcheck_home_PYTHON_BUILD{srcdir}/Include{projectbase}/._subst_varslocal_vars_extend_dicttarget_dictother_dicttarget_keys_expand_vars_get_default_scheme_getuserbasePYTHONUSERBASEenv_basejoinuserAPPDATAPythonLibrary.local_parse_makefileParse a Makefile-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + ([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)_variable_rx\$\(([A-Za-z][A-Za-z0-9_]*)\)_findvar1_rx\${([A-Za-z][A-Za-z0-9_]*)}_findvar2_rxnotdone$$tmpvvariablesrenamed_variablesm1PY_Return the path of the Makefile.Makefileconfig-%s%sconfig_dir_name_multiarch_get_sysconfigdata_name_PYTHON_SYSCONFIGDATA_NAME_sysconfigdata_{abi}_{platform}_{multiarch}abimultiarch_generate_posix_varsGenerate the Python module containing build-time variables.invalid Python installation: unable to open %sconfig_hbuild_time_varsbuild/lib.%s-%spybuilddirgettotalrefcount-pydebugdestfile# system configuration generated and used by the sysconfig module +'# system configuration generated and used by'' the sysconfig module\n'build_time_vars = pybuilddir.txt_init_posixInitialize the module as appropriate for POSIX systems._temp_init_non_posixInitialize the module as appropriate for NTLIBDESTBINLIBDESTINCLUDEPYEXT_SUFFIXEXEBINDIRParse a config.h-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + #define ([A-Z][A-Za-z0-9_]+) (.*) +define_rx/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/ +undef_rxReturn the path of pyconfig.h.PCinc_dirpyconfig.hReturn a tuple containing the schemes names.Return a tuple containing the paths names.expandReturn a mapping containing an install scheme. + + ``scheme`` is the install scheme name. If not provided, it will + return the default scheme for the current platform. + Return a path corresponding to the scheme. + + ``scheme`` is the install scheme name. + With no arguments, return a dictionary of all configuration + variables relevant for the current platform. + + On Unix, this means every variable defined in Python's installed Makefile; + On Windows it's a much smaller set. + + With arguments, return a list of values that result from looking up + each argument in the configuration variable dictionary. + py_versionpy_version_shortpy_version_nodotinstalled_baseinstalled_platbaseplatbaseprojectbaseSOuserbasesrcdir_osx_supportvalsReturn the value of a single variable using the dictionary returned by + 'get_config_vars()'. + + Equivalent to get_config_vars().get(name) + SO is deprecated, use EXT_SUFFIXReturn a string that identifies the current platform. + + This is used mainly to distinguish platform-specific build directories and + platform-specific built distributions. Typically includes the OS name and + version and the architecture (as supplied by 'os.uname()'), although the + exact information included depends on the OS; on Linux, the kernel version + isn't particularly important. + + Examples of returned values: + linux-i586 + linux-alpha (?) + solaris-2.6-sun4u + + Windows will return one of: + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) + win32 (all others - specifically, sys.platform is returned) + + For other non-POSIX platforms, currently just returns 'sys.platform'. + + amd64win-amd64(arm)win-arm32(arm64)win-arm64_PYTHON_HOST_PLATFORM%s-%ssunossolaris%d.%sbitness.%s%s-%s.%s[\d.]+rel_re%s-%s-%s_print_dict %s = "%s"Display all information sysconfig detains.--generate-posix-varsPlatform: "%s"Python version: "%s"Current installation scheme: "%s"PathsVariables# Keys for get_config_var() that are never converted to Python integers.# NOTE: When modifying "purelib" scheme, update site._get_path() too.# FIXME don't rely on sys.version here, its format is an implementation detail# of CPython, use sys.version_info or sys.hexversion# sys.executable can be empty if argv[0] has been changed and Python is# unable to retrieve the real program name# set for cross builds# the default scheme for posix is posix_prefix# NOTE: site.py has copy of this function.# Sync it when modify this function.# Regexes needed for parsing Makefile (and similar syntaxes,# like old-style Setup files).# `$$' is a literal `$' in make# insert literal `$'# do variable interpolation here# Variables with a 'PY_' prefix in the makefile. These need to# be made available without that prefix through sysconfig.# Special care is needed to ensure that variable expansion works, even# if the expansion uses the name without a prefix.# get it on a subsequent round# do it like make: fall back to environment# bogus variable reference (e.g. "prefix=$/opt/python");# just drop it since we can't deal# strip spurious spaces# save the results in the global dictionary# load the installed Makefile:# load the installed pyconfig.h:# On AIX, there are wrong paths to the linker scripts in the Makefile# -- these paths are relative to the Python source, but when installed# the scripts are in another directory.# There's a chicken-and-egg situation on OS X with regards to the# _sysconfigdata module after the changes introduced by #15298:# get_config_vars() is called by get_platform() as part of the# `make pybuilddir.txt` target -- which is a precursor to the# _sysconfigdata.py module being constructed. Unfortunately,# get_config_vars() eventually calls _init_posix(), which attempts# to import _sysconfigdata, which we won't have built yet. In order# for _init_posix() to work, if we're on Darwin, just mock up the# _sysconfigdata module manually and populate it with the build vars.# This is more than sufficient for ensuring the subsequent call to# get_platform() succeeds.# Create file used for sys.path fixup -- see Modules/getpath.c# _sysconfigdata is generated at build time, see _generate_posix_vars()# set basic install directories# public APIs# Normalized versions of prefix and exec_prefix are handy to have;# in fact, these are the standard versions used most places in the# Distutils.# sys.abiflags may not be defined on all platforms.# For backward compatibility, see issue19555# Setting 'userbase' is done below the call to the# init function to enable using 'get_config_var' in# the init-function.# Always convert srcdir to an absolute path# If srcdir is a relative path (typically '.' or '..')# then it should be interpreted relative to the directory# containing Makefile.# srcdir is not meaningful since the installation is# spread about the filesystem. We choose the# directory containing the Makefile since we know it# exists.# OS X platforms require special customization to handle# multi-architecture, multi-os-version installers# XXX what about the architecture? NT is Intel or Alpha# Set for cross builds explicitly# Try to distinguish various flavours of Unix# Convert the OS name to lowercase, remove '/' characters, and translate# spaces (for "Power Macintosh")# At least on Linux/Intel, 'machine' is the processor --# i386, etc.# XXX what about Alpha, SPARC, etc?# SunOS 5 == Solaris 2# We can't use "platform.architecture()[0]" because a# bootstrap problem. We use a dict to get an error# if some suspicious happens.# fall through to standard osname-release-machine representationb'Access to Python's configuration information.'u'Access to Python's configuration information.'b'get_config_h_filename'u'get_config_h_filename'b'get_config_var'u'get_config_var'b'get_config_vars'u'get_config_vars'b'get_makefile_filename'u'get_makefile_filename'b'get_path'u'get_path'b'get_path_names'u'get_path_names'b'get_paths'u'get_paths'b'get_platform'u'get_platform'b'get_python_version'u'get_python_version'b'get_scheme_names'u'get_scheme_names'b'parse_config_h'u'parse_config_h'b'{installed_base}/lib/python{py_version_short}'u'{installed_base}/lib/python{py_version_short}'b'{platbase}/lib/python{py_version_short}'u'{platbase}/lib/python{py_version_short}'b'platstdlib'u'platstdlib'b'{base}/lib/python{py_version_short}/site-packages'u'{base}/lib/python{py_version_short}/site-packages'b'purelib'u'purelib'b'{platbase}/lib/python{py_version_short}/site-packages'u'{platbase}/lib/python{py_version_short}/site-packages'b'platlib'u'platlib'b'{installed_base}/include/python{py_version_short}{abiflags}'u'{installed_base}/include/python{py_version_short}{abiflags}'b'{installed_platbase}/include/python{py_version_short}{abiflags}'u'{installed_platbase}/include/python{py_version_short}{abiflags}'b'platinclude'u'platinclude'b'{base}/bin'u'{base}/bin'b'scripts'u'scripts'b'{base}'u'{base}'b'posix_prefix'u'posix_prefix'b'{installed_base}/lib/python'u'{installed_base}/lib/python'b'{base}/lib/python'u'{base}/lib/python'b'{installed_base}/include/python'u'{installed_base}/include/python'b'posix_home'u'posix_home'b'{installed_base}/Lib'u'{installed_base}/Lib'b'{base}/Lib'u'{base}/Lib'b'{base}/Lib/site-packages'u'{base}/Lib/site-packages'b'{installed_base}/Include'u'{installed_base}/Include'b'{base}/Scripts'u'{base}/Scripts'b'{userbase}/Python{py_version_nodot}'u'{userbase}/Python{py_version_nodot}'b'{userbase}/Python{py_version_nodot}/site-packages'u'{userbase}/Python{py_version_nodot}/site-packages'b'{userbase}/Python{py_version_nodot}/Include'u'{userbase}/Python{py_version_nodot}/Include'b'{userbase}/Python{py_version_nodot}/Scripts'u'{userbase}/Python{py_version_nodot}/Scripts'b'{userbase}'u'{userbase}'b'nt_user'u'nt_user'b'{userbase}/lib/python{py_version_short}'u'{userbase}/lib/python{py_version_short}'b'{userbase}/lib/python{py_version_short}/site-packages'u'{userbase}/lib/python{py_version_short}/site-packages'b'{userbase}/include/python{py_version_short}'u'{userbase}/include/python{py_version_short}'b'{userbase}/bin'u'{userbase}/bin'b'posix_user'u'posix_user'b'{userbase}/lib/python'u'{userbase}/lib/python'b'{userbase}/lib/python/site-packages'u'{userbase}/lib/python/site-packages'b'{userbase}/include'u'{userbase}/include'b'osx_framework_user'u'osx_framework_user'b'%d%d'u'%d%d'b'\pcbuild\win32'u'\pcbuild\win32'b'\pcbuild\amd64'u'\pcbuild\amd64'b'_PYTHON_PROJECT_BASE'u'_PYTHON_PROJECT_BASE'b'Setup'u'Setup'b'Setup.local'u'Setup.local'b'_home'u'_home'b'PCbuild'u'PCbuild'b'{srcdir}/Include'u'{srcdir}/Include'b'{projectbase}/.'u'{projectbase}/.'b'PYTHONUSERBASE'u'PYTHONUSERBASE'b'APPDATA'u'APPDATA'b'Python'u'Python'b'Library'u'Library'b'.local'u'.local'b'Parse a Makefile-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + 'u'Parse a Makefile-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + 'b'([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)'u'([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)'b'\$\(([A-Za-z][A-Za-z0-9_]*)\)'u'\$\(([A-Za-z][A-Za-z0-9_]*)\)'b'\${([A-Za-z][A-Za-z0-9_]*)}'u'\${([A-Za-z][A-Za-z0-9_]*)}'b'$$'u'$$'b'PY_'u'PY_'b'Return the path of the Makefile.'u'Return the path of the Makefile.'b'Makefile'u'Makefile'b'abiflags'u'abiflags'b'config-%s%s'u'config-%s%s'b'_multiarch'u'_multiarch'b'_PYTHON_SYSCONFIGDATA_NAME'u'_PYTHON_SYSCONFIGDATA_NAME'b'_sysconfigdata_{abi}_{platform}_{multiarch}'u'_sysconfigdata_{abi}_{platform}_{multiarch}'b'Generate the Python module containing build-time variables.'u'Generate the Python module containing build-time variables.'b'invalid Python installation: unable to open %s'u'invalid Python installation: unable to open %s'b'strerror'u'strerror'b'build/lib.%s-%s'u'build/lib.%s-%s'b'gettotalrefcount'u'gettotalrefcount'b'-pydebug'u'-pydebug'b'# system configuration generated and used by the sysconfig module +'u'# system configuration generated and used by the sysconfig module +'b'build_time_vars = 'u'build_time_vars = 'b'pybuilddir.txt'u'pybuilddir.txt'b'Initialize the module as appropriate for POSIX systems.'u'Initialize the module as appropriate for POSIX systems.'b'build_time_vars'u'build_time_vars'b'Initialize the module as appropriate for NT'u'Initialize the module as appropriate for NT'b'LIBDEST'u'LIBDEST'b'BINLIBDEST'u'BINLIBDEST'b'INCLUDEPY'u'INCLUDEPY'b'EXT_SUFFIX'u'EXT_SUFFIX'b'EXE'u'EXE'b'BINDIR'u'BINDIR'b'Parse a config.h-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + 'u'Parse a config.h-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + 'b'#define ([A-Z][A-Za-z0-9_]+) (.*) +'u'#define ([A-Z][A-Za-z0-9_]+) (.*) +'b'/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/ +'u'/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/ +'b'Return the path of pyconfig.h.'u'Return the path of pyconfig.h.'b'PC'u'PC'b'pyconfig.h'u'pyconfig.h'b'Return a tuple containing the schemes names.'u'Return a tuple containing the schemes names.'b'Return a tuple containing the paths names.'u'Return a tuple containing the paths names.'b'Return a mapping containing an install scheme. + + ``scheme`` is the install scheme name. If not provided, it will + return the default scheme for the current platform. + 'u'Return a mapping containing an install scheme. + + ``scheme`` is the install scheme name. If not provided, it will + return the default scheme for the current platform. + 'b'Return a path corresponding to the scheme. + + ``scheme`` is the install scheme name. + 'u'Return a path corresponding to the scheme. + + ``scheme`` is the install scheme name. + 'b'With no arguments, return a dictionary of all configuration + variables relevant for the current platform. + + On Unix, this means every variable defined in Python's installed Makefile; + On Windows it's a much smaller set. + + With arguments, return a list of values that result from looking up + each argument in the configuration variable dictionary. + 'u'With no arguments, return a dictionary of all configuration + variables relevant for the current platform. + + On Unix, this means every variable defined in Python's installed Makefile; + On Windows it's a much smaller set. + + With arguments, return a list of values that result from looking up + each argument in the configuration variable dictionary. + 'b'prefix'u'prefix'b'exec_prefix'u'exec_prefix'b'py_version'u'py_version'b'py_version_short'u'py_version_short'b'py_version_nodot'u'py_version_nodot'b'installed_base'u'installed_base'b'installed_platbase'u'installed_platbase'b'platbase'u'platbase'b'projectbase'u'projectbase'b'SO'u'SO'b'userbase'u'userbase'b'srcdir'u'srcdir'b'Return the value of a single variable using the dictionary returned by + 'get_config_vars()'. + + Equivalent to get_config_vars().get(name) + 'u'Return the value of a single variable using the dictionary returned by + 'get_config_vars()'. + + Equivalent to get_config_vars().get(name) + 'b'SO is deprecated, use EXT_SUFFIX'u'SO is deprecated, use EXT_SUFFIX'b'Return a string that identifies the current platform. + + This is used mainly to distinguish platform-specific build directories and + platform-specific built distributions. Typically includes the OS name and + version and the architecture (as supplied by 'os.uname()'), although the + exact information included depends on the OS; on Linux, the kernel version + isn't particularly important. + + Examples of returned values: + linux-i586 + linux-alpha (?) + solaris-2.6-sun4u + + Windows will return one of: + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) + win32 (all others - specifically, sys.platform is returned) + + For other non-POSIX platforms, currently just returns 'sys.platform'. + + 'u'Return a string that identifies the current platform. + + This is used mainly to distinguish platform-specific build directories and + platform-specific built distributions. Typically includes the OS name and + version and the architecture (as supplied by 'os.uname()'), although the + exact information included depends on the OS; on Linux, the kernel version + isn't particularly important. + + Examples of returned values: + linux-i586 + linux-alpha (?) + solaris-2.6-sun4u + + Windows will return one of: + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) + win32 (all others - specifically, sys.platform is returned) + + For other non-POSIX platforms, currently just returns 'sys.platform'. + + 'b'amd64'u'amd64'b'win-amd64'u'win-amd64'b'(arm)'u'(arm)'b'win-arm32'u'win-arm32'b'(arm64)'u'(arm64)'b'win-arm64'u'win-arm64'b'_PYTHON_HOST_PLATFORM'u'_PYTHON_HOST_PLATFORM'b'%s-%s'u'%s-%s'b'sunos'u'sunos'b'solaris'u'solaris'b'%d.%s'u'%d.%s'b'.%s'u'.%s'b'%s-%s.%s'u'%s-%s.%s'b'[\d.]+'u'[\d.]+'b'%s-%s-%s'u'%s-%s-%s'b' %s = "%s"'u' %s = "%s"'b'Display all information sysconfig detains.'u'Display all information sysconfig detains.'b'--generate-posix-vars'u'--generate-posix-vars'b'Platform: "%s"'u'Platform: "%s"'b'Python version: "%s"'u'Python version: "%s"'b'Current installation scheme: "%s"'u'Current installation scheme: "%s"'b'Paths'u'Paths'b'Variables'u'Variables'u'sysconfig'Provide access to Python's configuration information. The specific +configuration variables available depend heavily on the platform and +configuration. The values may be retrieved using +get_config_var(name), and the list of variables is available via +get_config_vars().keys(). Additional convenience functions are also +available. + +Written by: Fred L. Drake, Jr. +Email: +get_host_platformPREFIXEXEC_PREFIXBASE_PREFIXBASE_EXEC_PREFIXproject_base_python_buildbuild_flagsReturn a string containing the major and minor Python version, + leaving off the patchlevel. Sample return values could be '1.5' + or '2.2'. + get_python_incplat_specificReturn the directory containing installed Python header files. + + If 'plat_specific' is false (the default), this is the path to the + non-platform-specific header files, i.e. Python.h and so on; + otherwise, this is the path to platform-specific header files + (namely pyconfig.h). + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + Includeincdirpython_dirI don't know where Python installs its C header files on platform '%s'"I don't know where Python installs its C header files ""on platform '%s'"get_python_libstandard_libReturn the directory containing the Python library (standard or + site additions). + + If 'plat_specific' is true, return the directory containing + platform-specific modules, i.e. any module from a non-pure-Python + module distribution; otherwise, return the platform-shared library + directory. If 'standard_lib' is true, return the directory + containing standard Python library modules; otherwise, return the + directory for site-specific modules. + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + libpythonLibI don't know where Python installs its library on platform '%s'"I don't know where Python installs its library "Do any platform-specific customization of a CCompiler instance. + + Mainly needed on Unix, so we can plug in the information that + varies across Unices and is stored in Python's Makefile. + CUSTOMIZED_OSX_COMPILERCCSHAREDSHLIB_SUFFIXARARFLAGScxxccsharedldsharedshlib_suffixar_flagsnewccCPPcpp -Earchivercc_cmdpreprocessorcompiler_cxxlinker_solinker_exeReturn full pathname of installed pyconfig.h file.Return full pathname of installed Makefile from the Python build.config-{}{}config_fileparse_makefiledistutils.text_fileTextFilestrip_commentsskip_blanksjoin_linesexpand_makefile_varsExpand Makefile-style variables -- "${foo}" or "$(foo)" -- in + 'string' according to 'vars' (a dictionary mapping variable names to + values). Variables not present in 'vars' are silently expanded to the + empty string. The variable values in 'vars' should not contain further + variable expansions; if 'vars' is the output of 'parse_makefile()', + you're fine. Returns a variable-expanded version of 's'. + beg_init_ntWith no arguments, return a dictionary of all configuration + variables relevant for the current platform. Generally this includes + everything needed to build extensions and install both pure modules and + extensions. On Unix, this means every variable defined in Python's + installed Makefile; on Windows it's a much smaller set. + + With arguments, return a list of values that result from looking up + each argument in the configuration variable dictionary. + _init_Return the value of a single variable using the dictionary + returned by 'get_config_vars()'. Equivalent to + get_config_vars().get(name) + # These are needed in a couple of spots, so just compute them once.# Path to the base directory of the project. On Windows the binary may# live in project/PCbuild/win32 or project/PCbuild/amd64.# python_build: (Boolean) if true, we're either building Python or# building an extension with an un-installed Python, so we use# different (hard-wired) directories.# Calculate the build qualifier flags if they are defined. Adding the flags# to the include and lib directories only makes sense for an installation, not# an in-source build.# It's not a configure-based build, so the sys module doesn't have# this attribute, which is fine.# Assume the executable is in the build directory. The# pyconfig.h file should be in the same directory. Since# the build directory may not be the source directory, we# must use "srcdir" from the makefile to find the "Include"# Include both the include and PC dir to ensure we can find# pyconfig.h# Perform first-time customization of compiler-related# config vars on OS X now that we know we need a compiler.# This is primarily to support Pythons from binary# installers. The kind and paths to build tools on# the user system may vary significantly from the system# that Python itself was built on. Also the user OS# version and build tools may not support the same set# of CPU architectures for universal builds.# Use get_config_var() to ensure _config_vars is initialized.# On OS X, if CC is overridden, use that as the default# command for LDSHARED as well# not always# bogus variable reference; just drop it since we can't deal# This algorithm does multiple expansion, so if vars['foo'] contains# "${bar}", it will expand ${foo} to ${bar}, and then expand# ${bar}... and so forth. This is fine as long as 'vars' comes from# 'parse_makefile()', which takes care of such expansions eagerly,# according to make's variable expansion semantics.# _sysconfigdata is generated at build time, see the sysconfig module# XXX hmmm.. a normal install puts include files here# Convert srcdir into an absolute path if it appears necessary.# Normally it is relative to the build directory. However, during# testing, for example, we might be running a non-installed python# from a different directory.# srcdir is relative and we are not in the same directory# as the executable. Assume executable is in the build# directory and make srcdir absolute.b'Provide access to Python's configuration information. The specific +configuration variables available depend heavily on the platform and +configuration. The values may be retrieved using +get_config_var(name), and the list of variables is available via +get_config_vars().keys(). Additional convenience functions are also +available. + +Written by: Fred L. Drake, Jr. +Email: +'u'Provide access to Python's configuration information. The specific +configuration variables available depend heavily on the platform and +configuration. The values may be retrieved using +get_config_var(name), and the list of variables is available via +get_config_vars().keys(). Additional convenience functions are also +available. + +Written by: Fred L. Drake, Jr. +Email: +'b'Return a string containing the major and minor Python version, + leaving off the patchlevel. Sample return values could be '1.5' + or '2.2'. + 'u'Return a string containing the major and minor Python version, + leaving off the patchlevel. Sample return values could be '1.5' + or '2.2'. + 'b'Return the directory containing installed Python header files. + + If 'plat_specific' is false (the default), this is the path to the + non-platform-specific header files, i.e. Python.h and so on; + otherwise, this is the path to platform-specific header files + (namely pyconfig.h). + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + 'u'Return the directory containing installed Python header files. + + If 'plat_specific' is false (the default), this is the path to the + non-platform-specific header files, i.e. Python.h and so on; + otherwise, this is the path to platform-specific header files + (namely pyconfig.h). + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + 'b'Include'u'Include'b'I don't know where Python installs its C header files on platform '%s''u'I don't know where Python installs its C header files on platform '%s''b'Return the directory containing the Python library (standard or + site additions). + + If 'plat_specific' is true, return the directory containing + platform-specific modules, i.e. any module from a non-pure-Python + module distribution; otherwise, return the platform-shared library + directory. If 'standard_lib' is true, return the directory + containing standard Python library modules; otherwise, return the + directory for site-specific modules. + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + 'u'Return the directory containing the Python library (standard or + site additions). + + If 'plat_specific' is true, return the directory containing + platform-specific modules, i.e. any module from a non-pure-Python + module distribution; otherwise, return the platform-shared library + directory. If 'standard_lib' is true, return the directory + containing standard Python library modules; otherwise, return the + directory for site-specific modules. + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + 'b'Lib'u'Lib'b'I don't know where Python installs its library on platform '%s''u'I don't know where Python installs its library on platform '%s''b'Do any platform-specific customization of a CCompiler instance. + + Mainly needed on Unix, so we can plug in the information that + varies across Unices and is stored in Python's Makefile. + 'u'Do any platform-specific customization of a CCompiler instance. + + Mainly needed on Unix, so we can plug in the information that + varies across Unices and is stored in Python's Makefile. + 'b'CUSTOMIZED_OSX_COMPILER'u'CUSTOMIZED_OSX_COMPILER'b'CCSHARED'u'CCSHARED'b'SHLIB_SUFFIX'u'SHLIB_SUFFIX'b'AR'u'AR'b'ARFLAGS'u'ARFLAGS'b'CPP'u'CPP'b' -E'u' -E'b'Return full pathname of installed pyconfig.h file.'u'Return full pathname of installed pyconfig.h file.'b'Return full pathname of installed Makefile from the Python build.'u'Return full pathname of installed Makefile from the Python build.'b'config-{}{}'u'config-{}{}'b'Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in + 'string' according to 'vars' (a dictionary mapping variable names to + values). Variables not present in 'vars' are silently expanded to the + empty string. The variable values in 'vars' should not contain further + variable expansions; if 'vars' is the output of 'parse_makefile()', + you're fine. Returns a variable-expanded version of 's'. + 'u'Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in + 'string' according to 'vars' (a dictionary mapping variable names to + values). Variables not present in 'vars' are silently expanded to the + empty string. The variable values in 'vars' should not contain further + variable expansions; if 'vars' is the output of 'parse_makefile()', + you're fine. Returns a variable-expanded version of 's'. + 'b'With no arguments, return a dictionary of all configuration + variables relevant for the current platform. Generally this includes + everything needed to build extensions and install both pure modules and + extensions. On Unix, this means every variable defined in Python's + installed Makefile; on Windows it's a much smaller set. + + With arguments, return a list of values that result from looking up + each argument in the configuration variable dictionary. + 'u'With no arguments, return a dictionary of all configuration + variables relevant for the current platform. Generally this includes + everything needed to build extensions and install both pure modules and + extensions. On Unix, this means every variable defined in Python's + installed Makefile; on Windows it's a much smaller set. + + With arguments, return a list of values that result from looking up + each argument in the configuration variable dictionary. + 'b'_init_'u'_init_'b'Return the value of a single variable using the dictionary + returned by 'get_config_vars()'. Equivalent to + get_config_vars().get(name) + 'u'Return the value of a single variable using the dictionary + returned by 'get_config_vars()'. Equivalent to + get_config_vars().get(name) + 'u'distutils.sysconfig'Read from and write to tar format archives. +0.9.0Lars Gustäbel (lars@gustaebel.de)Gustavo Niemeyer, Niels Gustäbel, Richard Townsend.bltn_opensymlink_exceptionTarFileTarInfois_tarfileCompressionErrorStreamErrorExtractErrorHeaderErrorUSTAR_FORMATGNU_FORMATPAX_FORMATDEFAULT_FORMATNULBLOCKSIZERECORDSIZEustar GNU_MAGICustar00POSIX_MAGICLENGTH_NAMELENGTH_LINKLENGTH_PREFIXREGTYPEAREGTYPELNKTYPESYMTYPECHRTYPEBLKTYPEDIRTYPEFIFOTYPECONTTYPEGNUTYPE_LONGNAMEGNUTYPE_LONGLINKGNUTYPE_SPARSEXHDTYPEXGLTYPESOLARIS_XHDTYPESUPPORTED_TYPESREGULAR_TYPESGNU_TYPESlinkpathPAX_FIELDSPAX_NAME_FIELDSatimePAX_NUMBER_FIELDSstnConvert a string to a null-terminated bytes object. + ntsConvert a null-terminated bytes object to a string. + ntiConvert a number field to a python number. + InvalidHeaderErrorinvalid headeritnConvert a python number to a number field. + %0*ooverflow in number fieldcalc_chksumsCalculate the checksum for a member's header by summing up all + characters except for the chksum field which is treated as if + it was filled with spaces. According to the GNU tar sources, + some tars (Sun and NeXT) calculate chksum with signed char, + which will be different if there are chars in the buffer with + the high bit set. So we calculate two checksums, unsigned and + signed. + 148B8x356Bunsigned_chksum148b8x356bsigned_chksumCopy length bytes from fileobj src to fileobj dst. + If length is None, copy the entire content. + unexpected end of data_safe_printBase exception.General exception for extract errors.Exception for unreadable tar archives.Exception for unavailable compression methods.Exception for unsupported operations on stream-like TarFiles.Base exception for header errors.EmptyHeaderErrorException for empty headers.TruncatedHeaderErrorException for truncated headers.EOFHeaderErrorException for end of file headers.Exception for invalid headers.SubsequentHeaderErrorException for missing and invalid extended headers._LowLevelFileLow-level file object. Supports reading and writing. + It is used instead of a regular file object for streaming + access. + O_BINARY_StreamClass that serves as an adapter between TarFile and + a stream-like object. The stream-like object only + needs to have a read() or write() method and is accessed + blockwise. Use of gzip or bzip2 compression is possible. + A stream-like object could be for example: sys.stdin, + sys.stdout, a socket, a tape device etc. + + _Stream is intended to be used only internally. + comptypeConstruct a _Stream object. + _extfileobj_StreamProxygetcomptypezlib module is not available_init_read_gz_init_write_gzbz2 module is not availabledbufcmplzma module is not availableunknown compression type %rInitialize for writing with gzip compression. + __write‹ÿWrite string s to the stream. + Write string s to the stream if a whole new block + is ready to be written. + Close the _Stream object. No operation should be + done on it afterwards. + 0xffffFFFFInitialize for reading a gzip compressed fileobj. + __readnot a gzip fileunsupported compression methodxlenReturn the stream's file pointer position. + Set the stream's file pointer to pos. Negative seeking + is forbidden. + seeking backwards is not allowedReturn the next size number of bytes from the stream.Return size bytes from the stream. + invalid compressed dataReturn size bytes from stream. If internal buffer is empty, + read another block from the stream. + Small proxy class that enables transparent compression + detection for the Stream interface (mode 'r|*'). + ‹BZh1AY&SY]€ý7zXZ_FileInFileA thin wrapper around an existing file object that + provides a part of its data as an individual file + object. + blockinfomap_indexlastposrealposReturn the current file position. + Seek to a position in the file. + Invalid argumentRead data from the file. + ExFileObjectoffset_datasparseInformational class which holds the details about an + archive member given by a tar header block. + TarInfo objects are returned by TarFile.getmember(), + TarFile.getmembers() and TarFile.gettarinfo() and are + usually created internally. + Name of the archive member.Permission bits.User ID of the user who originally stored this member.Group ID of the user who originally stored this member.Size in bytes.Time of last modification.Header checksum.chksumFile type. type is usually one of these constants: REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'File type. type is usually one of these constants: ''REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, ''CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'Name of the target file name, which is only present in TarInfo objects of type LNKTYPE and SYMTYPE.'Name of the target file name, which is only present ''in TarInfo objects of type LNKTYPE and SYMTYPE.'User name.Group name.Device major number.devmajorDevice minor number.devminorThe tar header starts here.The file's data starts here.A dictionary containing key-value pairs of an associated pax extended header.'A dictionary containing key-value pairs of an ''associated pax extended header.'pax_headersSparse member information._sparse_structs_link_targetConstruct a TarInfo object. name is the optional name + of the member. + 4200o644In pax headers, "name" is called "path".In pax headers, "linkname" is called "linkpath".get_infoReturn the TarInfo's attributes as a dictionary. + tobufReturn a tar header as a string of 512 byte blocks. + create_ustar_headercreate_gnu_headercreate_pax_headerinvalid formatReturn the object as a ustar header block. + linkname is too long_posix_split_name_create_headerReturn the object as a GNU header block sequence. + _create_gnu_long_headerReturn the object as a ustar header block. If it cannot be + represented this way, prepend a pax extended header sequence + with supplement information. + hname_create_pax_generic_headercreate_pax_global_headerReturn the object as a pax global header block sequence. + Split a name longer than 100 chars into a prefix + and a name part. + name is too longReturn a header block. info is a dictionary with file + information, format must be one of the *_FORMAT constants. + %ds364%06o357_create_payloadReturn the string payload filled with zero bytes + up to the next 512 byte border. + Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence + for name. + ././@LongLinkReturn a POSIX.1-2008 extended or global header sequence + that contains a list of keyword, value pairs. The values + must be strings. + 21 hdrcharset=BINARY +././@PaxHeaderfrombufConstruct a TarInfo object from a 512 byte bytes object. + empty headertruncated headerend of file headerbad checksum265297329337345386structs482isextended483495origsizefromtarfileReturn the next TarInfo object from TarFile object + tarfile. + _proc_memberChoose the right processing method depending on + the type and call it. + _proc_gnulong_proc_sparse_proc_pax_proc_builtinProcess a builtin type or an unknown type which + will be treated as a regular file. + isreg_block_apply_pax_infoProcess the blocks that hold a GNU longname + or longlink member. + missing or bad subsequent headerProcess a GNU sparse header plus extra headers. + Process an extended or global header as described in + POSIX.1-2008. + \d+ hdrcharset=([^\n]+)\nhdrcharset(\d+) ([^=]+)=_decode_pax_fieldGNU.sparse.map_proc_gnusparse_01GNU.sparse.size_proc_gnusparse_00GNU.sparse.majorGNU.sparse.minor_proc_gnusparse_10Process a GNU tar extended sparse header, version 0.0. + offsets\d+ GNU.sparse.offset=(\d+)\n\d+ GNU.sparse.numbytes=(\d+)\nProcess a GNU tar extended sparse header, version 0.1. + Process a GNU tar extended sparse header, version 1.0. + Replace fields with supplemental information from a previous + pax extended or global header. + GNU.sparse.nameGNU.sparse.realsizefallback_encodingfallback_errorsDecode a single field from a pax record. + Round up a byte count by BLOCKSIZE and return it, + e.g. _block(834) => 1024. + Return True if the Tarinfo object is a regular file.Return True if it is a directory.issymReturn True if it is a symbolic link.islnkReturn True if it is a hard link.ischrReturn True if it is a character device.isblkReturn True if it is a block device.isfifoReturn True if it is a FIFO.issparseisdevReturn True if it is one of character device, block device or FIFO.The TarFile Class provides an interface to tar archives. + dereferenceignore_zeroserrorlevelfileobjectcopybufsizeOpen an (uncompressed) tar archive `name'. `mode' is either 'r' to + read from an existing archive, 'a' to append data to an existing + file or 'w' to create a new file overwriting an existing one. `mode' + defaults to 'r'. + If `fileobj' is given, it is used for reading or writing data. If it + can be determined, `mode' is overridden by `fileobj's mode. + `fileobj' is not closed, when TarFile is closed. + r+bmodesmode must be 'r', 'a', 'w' or 'x'_loadedinodesfirstmemberOpen a tar archive for reading, writing or appending. Return + an appropriate TarFile class. + + mode: + 'r' or 'r:*' open for reading with transparent compression + 'r:' open for reading exclusively uncompressed + 'r:gz' open for reading with gzip compression + 'r:bz2' open for reading with bzip2 compression + 'r:xz' open for reading with lzma compression + 'a' or 'a:' open for appending, creating the file if necessary + 'w' or 'w:' open for writing without compression + 'w:gz' open for writing with gzip compression + 'w:bz2' open for writing with bzip2 compression + 'w:xz' open for writing with lzma compression + + 'x' or 'x:' create a tarfile exclusively without compression, raise + an exception if the file is already created + 'x:gz' create a gzip compressed tarfile, raise an exception + if the file is already created + 'x:bz2' create a bzip2 compressed tarfile, raise an exception + if the file is already created + 'x:xz' create an lzma compressed tarfile, raise an exception + if the file is already created + + 'r|*' open a stream of tar blocks with transparent compression + 'r|' open an uncompressed stream of tar blocks for reading + 'r|gz' open a gzip compressed stream of tar blocks + 'r|bz2' open a bzip2 compressed stream of tar blocks + 'r|xz' open an lzma compressed stream of tar blocks + 'w|' open an uncompressed stream for writing + 'w|gz' open a gzip compressed stream for writing + 'w|bz2' open a bzip2 compressed stream for writing + 'w|xz' open an lzma compressed stream for writing + nothing to openr:*not_compressedOPEN_METHtaropensaved_posfile could not be opened successfullymode must be 'r' or 'w'undiscernible modeOpen uncompressed tar archive name for reading or writing. + gzopenOpen gzip compressed tar archive name for reading or writing. + Appending is not allowed. + mode must be 'r', 'w' or 'x'gzip module is not availablebz2openOpen bzip2 compressed tar archive name for reading or writing. + Appending is not allowed. + not a bzip2 filexzopenOpen lzma compressed tar archive name for reading or writing. + Appending is not allowed. + not an lzma fileClose the TarFile. In write-mode, two finishing zero blocks are + appended to the archive. + getmemberReturn a TarInfo object for member `name'. If `name' can not be + found in the archive, KeyError is raised. If a member occurs more + than once in the archive, its last occurrence is assumed to be the + most up-to-date version. + _getmemberfilename %r not foundReturn the members of the archive as a list of TarInfo objects. The + list has the same order as the members in the archive. + _checkgetnamesReturn the members of the archive as a list of their names. It has + the same order as the list returned by getmembers(). + gettarinfoarcnameCreate a TarInfo object from the result of os.stat or equivalent + on an existing file. The file is either named by `name', or + specified as a file object `fileobj' with a file descriptor. If + given, `arcname' specifies an alternative name for the file in the + archive, otherwise, the name is taken from the 'name' attribute of + 'fileobj', or the 'name' argument. The name should be a text + string. + awxdrvstatresstmdPrint a table of contents to sys.stdout. If `verbose' is False, only + the names of the members are printed. If it is True, an `ls -l'-like + output is produced. `members' is optional and must be a subset of the + list returned by getmembers(). + %10s%d,%d%10d%d-%02d-%02d %02d:%02d:%02d-> link to Add the file `name' to the archive. `name' may be any type of file + (directory, fifo, symbolic link, etc.). If given, `arcname' + specifies an alternative name for the file in the archive. + Directories are added recursively by default. This can be avoided by + setting `recursive' to False. `filter' is a function + that expects a TarInfo object argument and returns the changed + TarInfo object, if it returns None the TarInfo object will be + excluded from the archive. + _dbgtarfile: Skipped %rtarfile: Unsupported type %rtarfile: Excluded %raddfileAdd the TarInfo object `tarinfo' to the archive. If `fileobj' is + given, it should be a binary file, and tarinfo.size bytes are read + from it and added to the archive. You can create TarInfo objects + directly, or by using gettarinfo(). + numeric_ownerExtract all members from the archive to the current working + directory and set owner, modification time and permissions on + directories afterwards. `path' specifies a different directory + to extract to. `members' is optional and must be a subset of the + list returned by getmembers(). If `numeric_owner` is True, only + the numbers for user/group names are used and not the names. + directories0o700set_attrstarfile: %sExtract a member from the archive to the current working directory, + using its full name. Its file information is extracted as accurately + as possible. `member' may be a filename or a TarInfo object. You can + specify a different directory using `path'. File attributes (owner, + mtime, mode) are set unless `set_attrs' is False. If `numeric_owner` + is True, only the numbers for user/group names are used and not + the names. + _extract_membertarfile: %s %rextractfileExtract a member from the archive as a file object. `member' may be + a filename or a TarInfo object. If `member' is a regular file or a + link, an io.BufferedReader object is returned. Otherwise, None is + returned. + cannot extract (sym)link as file object_find_link_targettargetpathExtract the TarInfo object tarinfo to a physical + file called targetpath. + upperdirsmakedirmakefifomakelinkmakeunknownMake a directory called targetpath. + Make a file called targetpath. + Make a file from a TarInfo object with an unknown type + at targetpath. + tarfile: Unknown file type %r, extracted as regular file."tarfile: Unknown file type %r, ""extracted as regular file."Make a fifo called targetpath. + fifo not supported by systemMake a character or block device called targetpath. + special devices not supported by systemMake a (symbolic) link called targetpath. If it cannot be created + (platform limitation), we try to make a copy of the referenced file + instead of a link. + unable to resolve link inside archiveSet owner of targetpath according to tarinfo. If numeric_owner + is True, use .gid/.uid instead of .gname/.uname. If numeric_owner + is False, fall back to .gid/.uid when the search based on name + fails. + could not change ownerSet file permissions of targetpath according to tarinfo. + could not change modeSet modification time of targetpath according to tarinfo. + could not change modification timeReturn the next member of the archive as a TarInfo object, when + TarFile is opened for reading. Return None if there is no more + available. + ra0x%X: %sempty fileFind an archive member by name from bottom to top. + If tarinfo is given, it is used as the starting point. + Read through the entire archive file and look for readable + members. + Check if TarFile is still open, and if the operation's mode + corresponds to TarFile's mode. + %s is closedbad operation for mode %rFind the target member of a symlink or hardlink member in the + archive. + linkname %r not foundProvide an iterator object. + Write debugging output to sys.stderr. + Return True if name points to a tar archive that we + are able to handle, else return False. + A simple command-line interface for tarfile module.--listShow listing of a tarfile--extractExtract tarfile into target dir--createCreate tarfile from sourcesTest if a tarfile is valid{!r} is a tar archive.{!r} is not a tar archive. +tf{!r} file is extracted.{!r} file is extracted into {!r} directory.'{!r} file is extracted ''into {!r} directory.'tar_name.tbz.tb2compressionsw:tar_modetar_files{!r} file created.#-------------------------------------------------------------------# tarfile.py# Copyright (C) 2002 Lars Gustaebel # Permission is hereby granted, free of charge, to any person# obtaining a copy of this software and associated documentation# files (the "Software"), to deal in the Software without# restriction, including without limitation the rights to use,# copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the# Software is furnished to do so, subject to the following# conditions:# The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR# OTHER DEALINGS IN THE SOFTWARE.#---------# os.symlink on Windows prior to 6.0 raises NotImplementedError# OSError (winerror=1314) will be raised if the caller does not hold the# SeCreateSymbolicLinkPrivilege privilege# from tarfile import *#---------------------------------------------------------# tar constants# the null character# length of processing blocks# length of records# magic gnu tar string# magic posix tar string# maximum length of a filename# maximum length of a linkname# maximum length of the prefix field# link (inside tarfile)# character special device# block special device# fifo special device# contiguous file# GNU tar longname# GNU tar longlink# GNU tar sparse file# POSIX.1-2001 extended header# POSIX.1-2001 global header# Solaris extended header# POSIX.1-1988 (ustar) format# GNU tar format# POSIX.1-2001 (pax) format# tarfile constants# File types that tarfile supports:# File types that will be treated as a regular file.# File types that are part of the GNU tar format.# Fields from a pax header that override a TarInfo attribute.# Fields from a pax header that are affected by hdrcharset.# Fields in a pax header that are numbers, all other fields# are treated as strings.# initialization# Some useful functions# There are two possible encodings for a number field, see# itn() below.# POSIX 1003.1-1988 requires numbers to be encoded as a string of# octal digits followed by a null-byte, this allows values up to# (8**(digits-1))-1. GNU tar allows storing numbers greater than# that if necessary. A leading 0o200 or 0o377 byte indicate this# particular encoding, the following digits-1 bytes are a big-endian# base-256 representation. This allows values up to (256**(digits-1))-1.# A 0o200 byte indicates a positive number, a 0o377 byte a negative# number.#---------------------------# internal stream interface# Enable transparent compression detection for the# stream interface# Honor "directory components removed" from RFC1952# RFC1952 says we must use ISO-8859-1 for the FNAME field.# taken from gzip.GzipFile with some alterations# Skip underlying buffer to avoid unaligned double buffering.# class _Stream# class StreamProxy#------------------------# Extraction file object# Construct a map with data and zero blocks.#class _FileInFile#class ExFileObject#------------------# Exported Classes# member name# file permissions# user id# group id# file size# modification time# header checksum# member type# link name# user name# group name# device major number# device minor number# the tar header starts here# the file's data starts here# sparse member information# pax header information# Test string fields for values that exceed the field length or cannot# be represented in ASCII encoding.# The pax header has priority.# Try to encode the string as ASCII.# Test number fields for values that exceed the field limit or values# that like to be stored as float.# The pax header has priority. Avoid overflow.# Create a pax extended header if necessary.# checksum field# create extended header + name blocks.# Check if one of the fields contains surrogate characters and thereby# forces hdrcharset=BINARY, see _proc_pax() for more information.# Put the hdrcharset field at the beginning of the header.# Try to restore the original byte representation of `value'.# Needless to say, that the encoding must match the string.# ' ' + '=' + '\n'# We use a hardcoded "././@PaxHeader" name like star does# instead of the one that POSIX recommends.# Create pax header + record blocks.# Old V7 tar format represents a directory as a regular# file with a trailing slash.# The old GNU sparse format occupies some of the unused# space in the buffer for up to 4 sparse structures.# Save them for later processing in _proc_sparse().# Remove redundant slashes from directories.# Reconstruct a ustar longname.#--------------------------------------------------------------------------# The following are methods that are called depending on the type of a# member. The entry point is _proc_member() which can be overridden in a# subclass to add custom _proc_*() methods. A _proc_*() method MUST# implement the following# operations:# 1. Set self.offset_data to the position where the data blocks begin,# if there is data that follows.# 2. Set tarfile.offset to the position where the next member's header will# begin.# 3. Return self or another valid TarInfo object.# Skip the following data blocks.# Patch the TarInfo object with saved global# header information.# Fetch the next header and process it.# Patch the TarInfo object from the next header with# the longname information.# We already collected some sparse structures in frombuf().# Collect sparse structures from extended header blocks.# Read the header information.# A pax header stores supplemental information for either# the following file (extended) or all following files# (global).# Check if the pax header contains a hdrcharset field. This tells us# the encoding of the path, linkpath, uname and gname fields. Normally,# these fields are UTF-8 encoded but since POSIX.1-2008 tar# implementations are allowed to store them as raw binary strings if# the translation to UTF-8 fails.# For the time being, we don't care about anything other than "BINARY".# The only other value that is currently allowed by the standard is# "ISO-IR 10646 2000 UTF-8" in other words UTF-8.# Parse pax header information. A record looks like that:# "%d %s=%s\n" % (length, keyword, value). length is the size# of the complete record including the length field itself and# the newline. keyword and value are both UTF-8 encoded strings.# Normally, we could just use "utf-8" as the encoding and "strict"# as the error handler, but we better not take the risk. For# example, GNU tar <= 1.23 is known to store filenames it cannot# translate to UTF-8 as raw strings (unfortunately without a# hdrcharset=BINARY header).# We first try the strict standard encoding, and if that fails we# fall back on the user's encoding and error handler.# Fetch the next header.# Process GNU sparse information.# GNU extended sparse format version 0.1.# GNU extended sparse format version 0.0.# GNU extended sparse format version 1.0.# Patch the TarInfo object with the extended header info.# If the extended header replaces the size field,# we need to recalculate the offset where the next# header starts.# class TarInfo# May be set from 0 (no msgs) to 3 (all msgs)# If true, add content of linked file to the# tar file, else the link.# If true, skips empty or invalid blocks and# continues processing.# If 0, fatal errors only appear in debug# messages (if debug >= 0). If > 0, errors# are passed to the caller as exceptions.# The format to use when creating an archive.# Encoding for 8-bit character strings.# Error handler for unicode conversion.# The default TarInfo class to use.# The file-object for extractfile().# Create nonexistent files in append mode.# Init attributes.# Init datastructures.# list of members as TarInfo objects# flag if all members have been read# current position in the archive file# dictionary caching the inodes of# archive members already added# Move to the end of the archive,# before the first empty block.# Below are the classmethods which act as alternate constructors to the# TarFile class. The open() method is the only one that is needed for# public use; it is the "super"-constructor and is able to select an# adequate "sub"-constructor for a particular compression using the mapping# from OPEN_METH.# This concept allows one to subclass TarFile without losing the comfort of# the super-constructor. A sub-constructor is registered and made available# by adding it to the mapping in OPEN_METH.# Find out which *open() is appropriate for opening the file.# Select the *open() function according to# given compression.# All *open() methods are registered here.# uncompressed tar# gzip compressed tar# bzip2 compressed tar# lzma compressed tar# The public methods which TarFile provides:# fill up the end with zero-blocks# (like option -b20 for tar does)# if we want to obtain a list of# all members, we first have to# scan the whole archive.# When fileobj is given, replace name by# fileobj's real name.# Building the name of the member in the archive.# Backward slashes are converted to forward slashes,# Absolute paths are turned to relative paths.# Now, fill the TarInfo object with# information specific for the file.# Not needed# Use os.stat or os.lstat, depending on if symlinks shall be resolved.# Is it a hardlink to an already# archived file?# The inode is added only if its valid.# For win32 it is always 0.# Fill the TarInfo object with all# information we can get.# Skip if somebody tries to archive the archive...# Create a TarInfo object from the file.# Change or exclude the TarInfo object.# Append the tar header and data to the archive.# If there's data to follow, append it.# Extract directories with a safe mode.# Do not set_attrs directories, as we will do that further down# Reverse sort directories.# Set correct owner, mtime and filemode on directories.# Prepare the link target for makelink().# Members with unknown types are treated as regular files.# A small but ugly workaround for the case that someone tries# to extract a (sym)link as a file-object from a non-seekable# stream of tar blocks.# A (sym)link's file object is its target's file object.# If there's no data associated with the member (directory, chrdev,# blkdev, etc.), return None instead of a file object.# Fetch the TarInfo object for the given name# and build the destination pathname, replacing# forward slashes to platform specific separators.# Create all upper directories.# Create directories that are not part of the archive with# default permissions.# Below are the different file methods. They are called via# _extract_member() when extract() is called. They can be replaced in a# subclass to implement other functionality.# Use a safe mode for the directory, the real mode is set# later in _extract_member().# For systems that support symbolic and hard links.# Avoid FileExistsError on following os.symlink.# See extract().# We have to be root to do so.# Advance the file pointer.# Read the next block.# Little helper methods:# Ensure that all members have been loaded.# Limit the member search list up to tarinfo.# Always search the entire archive.# Search the archive before the link, because a hard link is# just a reference to an already archived file.# Yield items using TarFile's next() method.# When all members have been read, set TarFile as _loaded.# Fix for SF #1100429: Under rare circumstances it can# happen that getmembers() is called during iteration,# which will have already exhausted the next() method.# An exception occurred. We must not call close() because# it would try to write end-of-archive blocks and padding.#--------------------# exported functions# gz# xz# bz2b'Read from and write to tar format archives. +'u'Read from and write to tar format archives. +'b'0.9.0'u'0.9.0'b'Lars Gustäbel (lars@gustaebel.de)'u'Lars Gustäbel (lars@gustaebel.de)'b'Gustavo Niemeyer, Niels Gustäbel, Richard Townsend.'u'Gustavo Niemeyer, Niels Gustäbel, Richard Townsend.'b'TarFile'u'TarFile'b'TarInfo'u'TarInfo'b'is_tarfile'u'is_tarfile'b'TarError'u'TarError'b'ReadError'u'ReadError'b'CompressionError'u'CompressionError'b'StreamError'u'StreamError'b'ExtractError'u'ExtractError'b'HeaderError'u'HeaderError'b'ENCODING'u'ENCODING'b'USTAR_FORMAT'u'USTAR_FORMAT'b'GNU_FORMAT'u'GNU_FORMAT'b'PAX_FORMAT'u'PAX_FORMAT'b'DEFAULT_FORMAT'u'DEFAULT_FORMAT'b'ustar 'b'ustar00'b'linkpath'u'linkpath'b'uid'u'uid'b'gid'u'gid'b'gname'u'gname'b'atime'u'atime'b'ctime'u'ctime'b'Convert a string to a null-terminated bytes object. + 'u'Convert a string to a null-terminated bytes object. + 'b'Convert a null-terminated bytes object to a string. + 'u'Convert a null-terminated bytes object to a string. + 'b'Convert a number field to a python number. + 'u'Convert a number field to a python number. + 'b'invalid header'u'invalid header'b'Convert a python number to a number field. + 'u'Convert a python number to a number field. + 'b'%0*o'u'%0*o'b'overflow in number field'u'overflow in number field'b'Calculate the checksum for a member's header by summing up all + characters except for the chksum field which is treated as if + it was filled with spaces. According to the GNU tar sources, + some tars (Sun and NeXT) calculate chksum with signed char, + which will be different if there are chars in the buffer with + the high bit set. So we calculate two checksums, unsigned and + signed. + 'u'Calculate the checksum for a member's header by summing up all + characters except for the chksum field which is treated as if + it was filled with spaces. According to the GNU tar sources, + some tars (Sun and NeXT) calculate chksum with signed char, + which will be different if there are chars in the buffer with + the high bit set. So we calculate two checksums, unsigned and + signed. + 'b'148B8x356B'u'148B8x356B'b'148b8x356b'u'148b8x356b'b'Copy length bytes from fileobj src to fileobj dst. + If length is None, copy the entire content. + 'u'Copy length bytes from fileobj src to fileobj dst. + If length is None, copy the entire content. + 'b'unexpected end of data'u'unexpected end of data'b'Base exception.'u'Base exception.'b'General exception for extract errors.'u'General exception for extract errors.'b'Exception for unreadable tar archives.'u'Exception for unreadable tar archives.'b'Exception for unavailable compression methods.'u'Exception for unavailable compression methods.'b'Exception for unsupported operations on stream-like TarFiles.'u'Exception for unsupported operations on stream-like TarFiles.'b'Base exception for header errors.'u'Base exception for header errors.'b'Exception for empty headers.'u'Exception for empty headers.'b'Exception for truncated headers.'u'Exception for truncated headers.'b'Exception for end of file headers.'u'Exception for end of file headers.'b'Exception for invalid headers.'u'Exception for invalid headers.'b'Exception for missing and invalid extended headers.'u'Exception for missing and invalid extended headers.'b'Low-level file object. Supports reading and writing. + It is used instead of a regular file object for streaming + access. + 'u'Low-level file object. Supports reading and writing. + It is used instead of a regular file object for streaming + access. + 'b'O_BINARY'u'O_BINARY'b'Class that serves as an adapter between TarFile and + a stream-like object. The stream-like object only + needs to have a read() or write() method and is accessed + blockwise. Use of gzip or bzip2 compression is possible. + A stream-like object could be for example: sys.stdin, + sys.stdout, a socket, a tape device etc. + + _Stream is intended to be used only internally. + 'u'Class that serves as an adapter between TarFile and + a stream-like object. The stream-like object only + needs to have a read() or write() method and is accessed + blockwise. Use of gzip or bzip2 compression is possible. + A stream-like object could be for example: sys.stdin, + sys.stdout, a socket, a tape device etc. + + _Stream is intended to be used only internally. + 'b'Construct a _Stream object. + 'u'Construct a _Stream object. + 'b'zlib module is not available'u'zlib module is not available'b'bz2 module is not available'u'bz2 module is not available'b'lzma module is not available'u'lzma module is not available'b'unknown compression type %r'u'unknown compression type %r'b'Initialize for writing with gzip compression. + 'u'Initialize for writing with gzip compression. + 'b'‹'b'ÿ'b'Write string s to the stream. + 'u'Write string s to the stream. + 'b'Write string s to the stream if a whole new block + is ready to be written. + 'u'Write string s to the stream if a whole new block + is ready to be written. + 'b'Close the _Stream object. No operation should be + done on it afterwards. + 'u'Close the _Stream object. No operation should be + done on it afterwards. + 'b'Initialize for reading a gzip compressed fileobj. + 'u'Initialize for reading a gzip compressed fileobj. + 'b'not a gzip file'u'not a gzip file'b'unsupported compression method'u'unsupported compression method'b'Return the stream's file pointer position. + 'u'Return the stream's file pointer position. + 'b'Set the stream's file pointer to pos. Negative seeking + is forbidden. + 'u'Set the stream's file pointer to pos. Negative seeking + is forbidden. + 'b'seeking backwards is not allowed'u'seeking backwards is not allowed'b'Return the next size number of bytes from the stream.'u'Return the next size number of bytes from the stream.'b'Return size bytes from the stream. + 'u'Return size bytes from the stream. + 'b'invalid compressed data'u'invalid compressed data'b'Return size bytes from stream. If internal buffer is empty, + read another block from the stream. + 'u'Return size bytes from stream. If internal buffer is empty, + read another block from the stream. + 'b'Small proxy class that enables transparent compression + detection for the Stream interface (mode 'r|*'). + 'u'Small proxy class that enables transparent compression + detection for the Stream interface (mode 'r|*'). + 'b'‹'b'BZh'b'1AY&SY'b']€'b'ý7zXZ'b'A thin wrapper around an existing file object that + provides a part of its data as an individual file + object. + 'u'A thin wrapper around an existing file object that + provides a part of its data as an individual file + object. + 'b'Return the current file position. + 'u'Return the current file position. + 'b'Seek to a position in the file. + 'u'Seek to a position in the file. + 'b'Invalid argument'u'Invalid argument'b'Read data from the file. + 'u'Read data from the file. + 'b'Informational class which holds the details about an + archive member given by a tar header block. + TarInfo objects are returned by TarFile.getmember(), + TarFile.getmembers() and TarFile.gettarinfo() and are + usually created internally. + 'u'Informational class which holds the details about an + archive member given by a tar header block. + TarInfo objects are returned by TarFile.getmember(), + TarFile.getmembers() and TarFile.gettarinfo() and are + usually created internally. + 'b'Name of the archive member.'u'Name of the archive member.'b'Permission bits.'u'Permission bits.'b'User ID of the user who originally stored this member.'u'User ID of the user who originally stored this member.'b'Group ID of the user who originally stored this member.'u'Group ID of the user who originally stored this member.'b'Size in bytes.'u'Size in bytes.'b'Time of last modification.'u'Time of last modification.'b'Header checksum.'u'Header checksum.'b'File type. type is usually one of these constants: REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'u'File type. type is usually one of these constants: REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'b'Name of the target file name, which is only present in TarInfo objects of type LNKTYPE and SYMTYPE.'u'Name of the target file name, which is only present in TarInfo objects of type LNKTYPE and SYMTYPE.'b'User name.'u'User name.'b'Group name.'u'Group name.'b'Device major number.'u'Device major number.'b'Device minor number.'u'Device minor number.'b'The tar header starts here.'u'The tar header starts here.'b'The file's data starts here.'u'The file's data starts here.'b'A dictionary containing key-value pairs of an associated pax extended header.'u'A dictionary containing key-value pairs of an associated pax extended header.'b'Sparse member information.'u'Sparse member information.'b'Construct a TarInfo object. name is the optional name + of the member. + 'u'Construct a TarInfo object. name is the optional name + of the member. + 'b'In pax headers, "name" is called "path".'u'In pax headers, "name" is called "path".'b'In pax headers, "linkname" is called "linkpath".'u'In pax headers, "linkname" is called "linkpath".'b'Return the TarInfo's attributes as a dictionary. + 'u'Return the TarInfo's attributes as a dictionary. + 'b'chksum'u'chksum'b'linkname'u'linkname'b'devmajor'u'devmajor'b'devminor'u'devminor'b'Return a tar header as a string of 512 byte blocks. + 'u'Return a tar header as a string of 512 byte blocks. + 'b'invalid format'u'invalid format'b'Return the object as a ustar header block. + 'u'Return the object as a ustar header block. + 'b'magic'u'magic'b'linkname is too long'u'linkname is too long'b'Return the object as a GNU header block sequence. + 'u'Return the object as a GNU header block sequence. + 'b'Return the object as a ustar header block. If it cannot be + represented this way, prepend a pax extended header sequence + with supplement information. + 'u'Return the object as a ustar header block. If it cannot be + represented this way, prepend a pax extended header sequence + with supplement information. + 'b'Return the object as a pax global header block sequence. + 'u'Return the object as a pax global header block sequence. + 'b'Split a name longer than 100 chars into a prefix + and a name part. + 'u'Split a name longer than 100 chars into a prefix + and a name part. + 'b'name is too long'u'name is too long'b'Return a header block. info is a dictionary with file + information, format must be one of the *_FORMAT constants. + 'u'Return a header block. info is a dictionary with file + information, format must be one of the *_FORMAT constants. + 'b' 'b'%ds'u'%ds'b'%06o'u'%06o'b'Return the string payload filled with zero bytes + up to the next 512 byte border. + 'u'Return the string payload filled with zero bytes + up to the next 512 byte border. + 'b'Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence + for name. + 'u'Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence + for name. + 'b'././@LongLink'u'././@LongLink'b'Return a POSIX.1-2008 extended or global header sequence + that contains a list of keyword, value pairs. The values + must be strings. + 'u'Return a POSIX.1-2008 extended or global header sequence + that contains a list of keyword, value pairs. The values + must be strings. + 'b'21 hdrcharset=BINARY +'b'././@PaxHeader'u'././@PaxHeader'b'Construct a TarInfo object from a 512 byte bytes object. + 'u'Construct a TarInfo object from a 512 byte bytes object. + 'b'empty header'u'empty header'b'truncated header'u'truncated header'b'end of file header'u'end of file header'b'bad checksum'u'bad checksum'b'Return the next TarInfo object from TarFile object + tarfile. + 'u'Return the next TarInfo object from TarFile object + tarfile. + 'b'Choose the right processing method depending on + the type and call it. + 'u'Choose the right processing method depending on + the type and call it. + 'b'Process a builtin type or an unknown type which + will be treated as a regular file. + 'u'Process a builtin type or an unknown type which + will be treated as a regular file. + 'b'Process the blocks that hold a GNU longname + or longlink member. + 'u'Process the blocks that hold a GNU longname + or longlink member. + 'b'missing or bad subsequent header'u'missing or bad subsequent header'b'Process a GNU sparse header plus extra headers. + 'u'Process a GNU sparse header plus extra headers. + 'b'Process an extended or global header as described in + POSIX.1-2008. + 'u'Process an extended or global header as described in + POSIX.1-2008. + 'b'\d+ hdrcharset=([^\n]+)\n'b'hdrcharset'u'hdrcharset'b'(\d+) ([^=]+)='b'GNU.sparse.map'u'GNU.sparse.map'b'GNU.sparse.size'u'GNU.sparse.size'b'GNU.sparse.major'u'GNU.sparse.major'b'GNU.sparse.minor'u'GNU.sparse.minor'b'Process a GNU tar extended sparse header, version 0.0. + 'u'Process a GNU tar extended sparse header, version 0.0. + 'b'\d+ GNU.sparse.offset=(\d+)\n'b'\d+ GNU.sparse.numbytes=(\d+)\n'b'Process a GNU tar extended sparse header, version 0.1. + 'u'Process a GNU tar extended sparse header, version 0.1. + 'b'Process a GNU tar extended sparse header, version 1.0. + 'u'Process a GNU tar extended sparse header, version 1.0. + 'b'Replace fields with supplemental information from a previous + pax extended or global header. + 'u'Replace fields with supplemental information from a previous + pax extended or global header. + 'b'GNU.sparse.name'u'GNU.sparse.name'b'GNU.sparse.realsize'u'GNU.sparse.realsize'b'Decode a single field from a pax record. + 'u'Decode a single field from a pax record. + 'b'Round up a byte count by BLOCKSIZE and return it, + e.g. _block(834) => 1024. + 'u'Round up a byte count by BLOCKSIZE and return it, + e.g. _block(834) => 1024. + 'b'Return True if the Tarinfo object is a regular file.'u'Return True if the Tarinfo object is a regular file.'b'Return True if it is a directory.'u'Return True if it is a directory.'b'Return True if it is a symbolic link.'u'Return True if it is a symbolic link.'b'Return True if it is a hard link.'u'Return True if it is a hard link.'b'Return True if it is a character device.'u'Return True if it is a character device.'b'Return True if it is a block device.'u'Return True if it is a block device.'b'Return True if it is a FIFO.'u'Return True if it is a FIFO.'b'Return True if it is one of character device, block device or FIFO.'u'Return True if it is one of character device, block device or FIFO.'b'The TarFile Class provides an interface to tar archives. + 'u'The TarFile Class provides an interface to tar archives. + 'b'Open an (uncompressed) tar archive `name'. `mode' is either 'r' to + read from an existing archive, 'a' to append data to an existing + file or 'w' to create a new file overwriting an existing one. `mode' + defaults to 'r'. + If `fileobj' is given, it is used for reading or writing data. If it + can be determined, `mode' is overridden by `fileobj's mode. + `fileobj' is not closed, when TarFile is closed. + 'u'Open an (uncompressed) tar archive `name'. `mode' is either 'r' to + read from an existing archive, 'a' to append data to an existing + file or 'w' to create a new file overwriting an existing one. `mode' + defaults to 'r'. + If `fileobj' is given, it is used for reading or writing data. If it + can be determined, `mode' is overridden by `fileobj's mode. + `fileobj' is not closed, when TarFile is closed. + 'b'r+b'u'r+b'b'mode must be 'r', 'a', 'w' or 'x''u'mode must be 'r', 'a', 'w' or 'x''b'Open a tar archive for reading, writing or appending. Return + an appropriate TarFile class. + + mode: + 'r' or 'r:*' open for reading with transparent compression + 'r:' open for reading exclusively uncompressed + 'r:gz' open for reading with gzip compression + 'r:bz2' open for reading with bzip2 compression + 'r:xz' open for reading with lzma compression + 'a' or 'a:' open for appending, creating the file if necessary + 'w' or 'w:' open for writing without compression + 'w:gz' open for writing with gzip compression + 'w:bz2' open for writing with bzip2 compression + 'w:xz' open for writing with lzma compression + + 'x' or 'x:' create a tarfile exclusively without compression, raise + an exception if the file is already created + 'x:gz' create a gzip compressed tarfile, raise an exception + if the file is already created + 'x:bz2' create a bzip2 compressed tarfile, raise an exception + if the file is already created + 'x:xz' create an lzma compressed tarfile, raise an exception + if the file is already created + + 'r|*' open a stream of tar blocks with transparent compression + 'r|' open an uncompressed stream of tar blocks for reading + 'r|gz' open a gzip compressed stream of tar blocks + 'r|bz2' open a bzip2 compressed stream of tar blocks + 'r|xz' open an lzma compressed stream of tar blocks + 'w|' open an uncompressed stream for writing + 'w|gz' open a gzip compressed stream for writing + 'w|bz2' open a bzip2 compressed stream for writing + 'w|xz' open an lzma compressed stream for writing + 'u'Open a tar archive for reading, writing or appending. Return + an appropriate TarFile class. + + mode: + 'r' or 'r:*' open for reading with transparent compression + 'r:' open for reading exclusively uncompressed + 'r:gz' open for reading with gzip compression + 'r:bz2' open for reading with bzip2 compression + 'r:xz' open for reading with lzma compression + 'a' or 'a:' open for appending, creating the file if necessary + 'w' or 'w:' open for writing without compression + 'w:gz' open for writing with gzip compression + 'w:bz2' open for writing with bzip2 compression + 'w:xz' open for writing with lzma compression + + 'x' or 'x:' create a tarfile exclusively without compression, raise + an exception if the file is already created + 'x:gz' create a gzip compressed tarfile, raise an exception + if the file is already created + 'x:bz2' create a bzip2 compressed tarfile, raise an exception + if the file is already created + 'x:xz' create an lzma compressed tarfile, raise an exception + if the file is already created + + 'r|*' open a stream of tar blocks with transparent compression + 'r|' open an uncompressed stream of tar blocks for reading + 'r|gz' open a gzip compressed stream of tar blocks + 'r|bz2' open a bzip2 compressed stream of tar blocks + 'r|xz' open an lzma compressed stream of tar blocks + 'w|' open an uncompressed stream for writing + 'w|gz' open a gzip compressed stream for writing + 'w|bz2' open a bzip2 compressed stream for writing + 'w|xz' open an lzma compressed stream for writing + 'b'nothing to open'u'nothing to open'b'r:*'u'r:*'b'taropen'u'taropen'b'file could not be opened successfully'u'file could not be opened successfully'b'mode must be 'r' or 'w''u'mode must be 'r' or 'w''b'undiscernible mode'u'undiscernible mode'b'Open uncompressed tar archive name for reading or writing. + 'u'Open uncompressed tar archive name for reading or writing. + 'b'Open gzip compressed tar archive name for reading or writing. + Appending is not allowed. + 'u'Open gzip compressed tar archive name for reading or writing. + Appending is not allowed. + 'b'mode must be 'r', 'w' or 'x''u'mode must be 'r', 'w' or 'x''b'gzip module is not available'u'gzip module is not available'b'Open bzip2 compressed tar archive name for reading or writing. + Appending is not allowed. + 'u'Open bzip2 compressed tar archive name for reading or writing. + Appending is not allowed. + 'b'not a bzip2 file'u'not a bzip2 file'b'Open lzma compressed tar archive name for reading or writing. + Appending is not allowed. + 'u'Open lzma compressed tar archive name for reading or writing. + Appending is not allowed. + 'b'not an lzma file'u'not an lzma file'b'gzopen'u'gzopen'b'bz2open'u'bz2open'b'xzopen'u'xzopen'b'Close the TarFile. In write-mode, two finishing zero blocks are + appended to the archive. + 'u'Close the TarFile. In write-mode, two finishing zero blocks are + appended to the archive. + 'b'Return a TarInfo object for member `name'. If `name' can not be + found in the archive, KeyError is raised. If a member occurs more + than once in the archive, its last occurrence is assumed to be the + most up-to-date version. + 'u'Return a TarInfo object for member `name'. If `name' can not be + found in the archive, KeyError is raised. If a member occurs more + than once in the archive, its last occurrence is assumed to be the + most up-to-date version. + 'b'filename %r not found'u'filename %r not found'b'Return the members of the archive as a list of TarInfo objects. The + list has the same order as the members in the archive. + 'u'Return the members of the archive as a list of TarInfo objects. The + list has the same order as the members in the archive. + 'b'Return the members of the archive as a list of their names. It has + the same order as the list returned by getmembers(). + 'u'Return the members of the archive as a list of their names. It has + the same order as the list returned by getmembers(). + 'b'Create a TarInfo object from the result of os.stat or equivalent + on an existing file. The file is either named by `name', or + specified as a file object `fileobj' with a file descriptor. If + given, `arcname' specifies an alternative name for the file in the + archive, otherwise, the name is taken from the 'name' attribute of + 'fileobj', or the 'name' argument. The name should be a text + string. + 'u'Create a TarInfo object from the result of os.stat or equivalent + on an existing file. The file is either named by `name', or + specified as a file object `fileobj' with a file descriptor. If + given, `arcname' specifies an alternative name for the file in the + archive, otherwise, the name is taken from the 'name' attribute of + 'fileobj', or the 'name' argument. The name should be a text + string. + 'b'awx'u'awx'b'major'u'major'b'minor'u'minor'b'Print a table of contents to sys.stdout. If `verbose' is False, only + the names of the members are printed. If it is True, an `ls -l'-like + output is produced. `members' is optional and must be a subset of the + list returned by getmembers(). + 'u'Print a table of contents to sys.stdout. If `verbose' is False, only + the names of the members are printed. If it is True, an `ls -l'-like + output is produced. `members' is optional and must be a subset of the + list returned by getmembers(). + 'b'%10s'u'%10s'b'%d,%d'u'%d,%d'b'%10d'u'%10d'b'%d-%02d-%02d %02d:%02d:%02d'u'%d-%02d-%02d %02d:%02d:%02d'b'-> 'u'-> 'b'link to 'u'link to 'b'Add the file `name' to the archive. `name' may be any type of file + (directory, fifo, symbolic link, etc.). If given, `arcname' + specifies an alternative name for the file in the archive. + Directories are added recursively by default. This can be avoided by + setting `recursive' to False. `filter' is a function + that expects a TarInfo object argument and returns the changed + TarInfo object, if it returns None the TarInfo object will be + excluded from the archive. + 'u'Add the file `name' to the archive. `name' may be any type of file + (directory, fifo, symbolic link, etc.). If given, `arcname' + specifies an alternative name for the file in the archive. + Directories are added recursively by default. This can be avoided by + setting `recursive' to False. `filter' is a function + that expects a TarInfo object argument and returns the changed + TarInfo object, if it returns None the TarInfo object will be + excluded from the archive. + 'b'tarfile: Skipped %r'u'tarfile: Skipped %r'b'tarfile: Unsupported type %r'u'tarfile: Unsupported type %r'b'tarfile: Excluded %r'u'tarfile: Excluded %r'b'Add the TarInfo object `tarinfo' to the archive. If `fileobj' is + given, it should be a binary file, and tarinfo.size bytes are read + from it and added to the archive. You can create TarInfo objects + directly, or by using gettarinfo(). + 'u'Add the TarInfo object `tarinfo' to the archive. If `fileobj' is + given, it should be a binary file, and tarinfo.size bytes are read + from it and added to the archive. You can create TarInfo objects + directly, or by using gettarinfo(). + 'b'Extract all members from the archive to the current working + directory and set owner, modification time and permissions on + directories afterwards. `path' specifies a different directory + to extract to. `members' is optional and must be a subset of the + list returned by getmembers(). If `numeric_owner` is True, only + the numbers for user/group names are used and not the names. + 'u'Extract all members from the archive to the current working + directory and set owner, modification time and permissions on + directories afterwards. `path' specifies a different directory + to extract to. `members' is optional and must be a subset of the + list returned by getmembers(). If `numeric_owner` is True, only + the numbers for user/group names are used and not the names. + 'b'tarfile: %s'u'tarfile: %s'b'Extract a member from the archive to the current working directory, + using its full name. Its file information is extracted as accurately + as possible. `member' may be a filename or a TarInfo object. You can + specify a different directory using `path'. File attributes (owner, + mtime, mode) are set unless `set_attrs' is False. If `numeric_owner` + is True, only the numbers for user/group names are used and not + the names. + 'u'Extract a member from the archive to the current working directory, + using its full name. Its file information is extracted as accurately + as possible. `member' may be a filename or a TarInfo object. You can + specify a different directory using `path'. File attributes (owner, + mtime, mode) are set unless `set_attrs' is False. If `numeric_owner` + is True, only the numbers for user/group names are used and not + the names. + 'b'tarfile: %s %r'u'tarfile: %s %r'b'Extract a member from the archive as a file object. `member' may be + a filename or a TarInfo object. If `member' is a regular file or a + link, an io.BufferedReader object is returned. Otherwise, None is + returned. + 'u'Extract a member from the archive as a file object. `member' may be + a filename or a TarInfo object. If `member' is a regular file or a + link, an io.BufferedReader object is returned. Otherwise, None is + returned. + 'b'cannot extract (sym)link as file object'u'cannot extract (sym)link as file object'b'Extract the TarInfo object tarinfo to a physical + file called targetpath. + 'u'Extract the TarInfo object tarinfo to a physical + file called targetpath. + 'b'Make a directory called targetpath. + 'u'Make a directory called targetpath. + 'b'Make a file called targetpath. + 'u'Make a file called targetpath. + 'b'Make a file from a TarInfo object with an unknown type + at targetpath. + 'u'Make a file from a TarInfo object with an unknown type + at targetpath. + 'b'tarfile: Unknown file type %r, extracted as regular file.'u'tarfile: Unknown file type %r, extracted as regular file.'b'Make a fifo called targetpath. + 'u'Make a fifo called targetpath. + 'b'fifo not supported by system'u'fifo not supported by system'b'Make a character or block device called targetpath. + 'u'Make a character or block device called targetpath. + 'b'makedev'u'makedev'b'special devices not supported by system'u'special devices not supported by system'b'Make a (symbolic) link called targetpath. If it cannot be created + (platform limitation), we try to make a copy of the referenced file + instead of a link. + 'u'Make a (symbolic) link called targetpath. If it cannot be created + (platform limitation), we try to make a copy of the referenced file + instead of a link. + 'b'unable to resolve link inside archive'u'unable to resolve link inside archive'b'Set owner of targetpath according to tarinfo. If numeric_owner + is True, use .gid/.uid instead of .gname/.uname. If numeric_owner + is False, fall back to .gid/.uid when the search based on name + fails. + 'u'Set owner of targetpath according to tarinfo. If numeric_owner + is True, use .gid/.uid instead of .gname/.uname. If numeric_owner + is False, fall back to .gid/.uid when the search based on name + fails. + 'b'geteuid'u'geteuid'b'could not change owner'u'could not change owner'b'Set file permissions of targetpath according to tarinfo. + 'u'Set file permissions of targetpath according to tarinfo. + 'b'could not change mode'u'could not change mode'b'Set modification time of targetpath according to tarinfo. + 'u'Set modification time of targetpath according to tarinfo. + 'b'could not change modification time'u'could not change modification time'b'Return the next member of the archive as a TarInfo object, when + TarFile is opened for reading. Return None if there is no more + available. + 'u'Return the next member of the archive as a TarInfo object, when + TarFile is opened for reading. Return None if there is no more + available. + 'b'ra'u'ra'b'0x%X: %s'u'0x%X: %s'b'empty file'u'empty file'b'Find an archive member by name from bottom to top. + If tarinfo is given, it is used as the starting point. + 'u'Find an archive member by name from bottom to top. + If tarinfo is given, it is used as the starting point. + 'b'Read through the entire archive file and look for readable + members. + 'u'Read through the entire archive file and look for readable + members. + 'b'Check if TarFile is still open, and if the operation's mode + corresponds to TarFile's mode. + 'u'Check if TarFile is still open, and if the operation's mode + corresponds to TarFile's mode. + 'b'%s is closed'u'%s is closed'b'bad operation for mode %r'u'bad operation for mode %r'b'Find the target member of a symlink or hardlink member in the + archive. + 'u'Find the target member of a symlink or hardlink member in the + archive. + 'b'linkname %r not found'u'linkname %r not found'b'Provide an iterator object. + 'u'Provide an iterator object. + 'b'Write debugging output to sys.stderr. + 'u'Write debugging output to sys.stderr. + 'b'Return True if name points to a tar archive that we + are able to handle, else return False. + 'u'Return True if name points to a tar archive that we + are able to handle, else return False. + 'b'A simple command-line interface for tarfile module.'u'A simple command-line interface for tarfile module.'b'--list'u'--list'b''u''b'Show listing of a tarfile'u'Show listing of a tarfile'b'--extract'u'--extract'b''u''b'Extract tarfile into target dir'u'Extract tarfile into target dir'b'--create'u'--create'b''u''b''u''b'Create tarfile from sources'u'Create tarfile from sources'b'Test if a tarfile is valid'u'Test if a tarfile is valid'b'{!r} is a tar archive.'u'{!r} is a tar archive.'b'{!r} is not a tar archive. +'u'{!r} is not a tar archive. +'b'{!r} file is extracted.'u'{!r} file is extracted.'b'{!r} file is extracted into {!r} directory.'u'{!r} file is extracted into {!r} directory.'b'.tbz'u'.tbz'b'.tb2'u'.tb2'b'w:'u'w:'b'{!r} file created.'u'{!r} file created.'u'tarfile'Support for tasks, coroutines and the scheduler.shieldrun_coroutine_threadsafebase_tasks_task_name_counterReturn a currently executed task.Return a set of all tasks for the loop.A coroutine wrapped in a Future.Return the currently running task in an event loop or None. + + By default the current task for the current event loop is returned. + + None is returned when called not in the context of a Task. + Task.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead"Task.current_task() is deprecated since Python 3.7, ""use asyncio.current_task() instead"Return a set of all tasks for an event loop. + + By default all tasks for the current event loop are returned. + Task.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() instead"Task.all_tasks() is deprecated since Python 3.7, ""use asyncio.all_tasks() instead"a coroutine was expected, got Task-__stepTask was destroyed but it is pending!Task does not support set_result operationTask does not support set_exception operationReturn the list of stack frames for this task's coroutine. + + If the coroutine is not done, this returns the stack where it is + suspended. If the coroutine has completed successfully or was + cancelled, this returns an empty list. If the coroutine was + terminated by an exception, this returns the list of traceback + frames. + + The frames are always ordered from oldest to newest. + + The optional limit gives the maximum number of frames to + return; by default all available frames are returned. Its + meaning differs depending on whether a stack or a traceback is + returned: the newest frames of a stack are returned, but the + oldest frames of a traceback are returned. (This matches the + behavior of the traceback module.) + + For reasons beyond our control, only one stack frame is + returned for a suspended coroutine. + Print the stack or traceback for this task's coroutine. + + This produces output similar to that of the traceback module, + for the frames retrieved by get_stack(). The limit argument + is passed to get_stack(). The file argument is an I/O stream + to which the output is written; by default output is written + to sys.stderr. + Request that this task cancel itself. + + This arranges for a CancelledError to be thrown into the + wrapped coroutine on the next cycle through the event loop. + The coroutine then has a chance to clean up or even deny + the request using try/except/finally. + + Unlike Future.cancel, this does not guarantee that the + task will be cancelled: the exception might be caught and + acted upon, delaying cancellation of the task or preventing + cancellation completely. The task may also return a value or + raise a different exception. + + Immediately after this method is called, Task.cancelled() will + not return True (unless the task was already cancelled). A + task will be marked as cancelled when the wrapped coroutine + terminates with a CancelledError exception (even if cancel() + was not called). + _step(): already done: Task got Future ' got Future ' attached to a different loopTask cannot await on itself: __wakeupyield was used instead of yield from in task 'yield was used instead of yield from ''in task ' with yield was used instead of yield from for generator in task 'yield was used instead of yield from for ''generator in task 'Task got bad yield: _PyTask_CTaskSchedule the execution of a coroutine object in a spawn task. + + Return a Task object. + Wait for the Futures and coroutines given by fs to complete. + + The fs iterable must not be empty. + + Coroutines will be wrapped in Tasks. + + Returns two sets of Future: (done, pending). + + Usage: + + done, pending = await asyncio.wait(fs) + + Note: This does not raise TimeoutError! Futures that aren't done + when the timeout occurs are returned in the second set. + expect a list of futures, not Set of coroutines/Futures is empty.Invalid return_when value: _release_waiterWait for the single Future or coroutine to complete, with timeout. + + Coroutine will be wrapped in Task. + + Returns result of the Future or coroutine. When a timeout occurs, + it cancels the task and raises TimeoutError. To avoid the task + cancellation, wrap it in shield(). + + If the wait is cancelled, the task is also cancelled. + + This function is a coroutine. + _cancel_and_waittimeout_handleInternal helper for wait(). + + The fs argument must be a collection of Futures. + Set of Futures is empty.counter_on_completionCancel the *fut* future or task and wait until it completes.Return an iterator whose values are coroutines. + + When waiting for the yielded coroutines you'll get the results (or + exceptions!) of the original Futures (or coroutines), in the order + in which and as soon as they complete. + + This differs from PEP 3148; the proper way to use this is: + + for f in as_completed(fs): + result = await f # The 'await' may raise. + # Use result. + + If a timeout is specified, the 'await' will raise + TimeoutError when the timeout occurs before all Futures are done. + + Note: The futures 'f' are not necessarily members of fs. + expect an iterable of futures, not _on_timeout_wait_for_one__sleep0Skip one event loop run cycle. + + This is a private helper for 'asyncio.sleep()', used + when the 'delay' is set to 0. It uses a bare 'yield' + expression (which Task.__step knows how to handle) + instead of creating a Future object. + Coroutine that completes after a given time (in seconds).coro_or_futureWrap a coroutine or an awaitable in a future. + + If the argument is a Future, it is returned directly. + The future belongs to a different loop than the one specified as the loop argument'The future belongs to a different loop than ''the one specified as the loop argument'_wrap_awaitableAn asyncio.Future, a coroutine or an awaitable is required'An asyncio.Future, a coroutine or an awaitable is ''required'Helper for asyncio.ensure_future(). + + Wraps awaitable (an object with __await__) into a coroutine + that will later be wrapped in a Task by ensure_future(). + _GatheringFutureHelper for gather(). + + This overrides cancel() to cancel all the children and act more + like Task.cancel(), which doesn't immediately mark itself as + cancelled. + _cancel_requestedcoros_or_futuresReturn a future aggregating results from the given coroutines/futures. + + Coroutines will be wrapped in a future and scheduled in the event + loop. They will not necessarily be scheduled in the same order as + passed in. + + All futures must share the same event loop. If all the tasks are + done successfully, the returned future's result is the list of + results (in the order of the original sequence, not necessarily + the order of results arrival). If *return_exceptions* is True, + exceptions in the tasks are treated the same as successful + results, and gathered in the result list; otherwise, the first + raised exception will be immediately propagated to the returned + future. + + Cancellation: if the outer Future is cancelled, all children (that + have not completed yet) are also cancelled. If any child is + cancelled, this is treated as if it raised CancelledError -- + the outer Future is *not* cancelled in this case. (This is to + prevent the cancellation of one child to cause other children to + be cancelled.) + + If *return_exceptions* is False, cancelling gather() after it + has been marked done won't cancel any submitted awaitables. + For instance, gather can be marked done after propagating an + exception to the caller, therefore, calling ``gather.cancel()`` + after catching an exception (raised by one of the awaitables) from + gather won't cancel any other awaitables. + _done_callbacknfinishednfutsarg_to_futWait for a future, shielding it from cancellation. + + The statement + + res = await shield(something()) + + is exactly equivalent to the statement + + res = await something() + + *except* that if the coroutine containing it is cancelled, the + task running in something() is not cancelled. From the POV of + something(), the cancellation did not happen. But its caller is + still cancelled, so the yield-from expression still raises + CancelledError. Note: If something() is cancelled by other means + this will still cancel shield(). + + If you want to completely ignore cancellation (not recommended) + you can combine shield() with a try/except clause, as follows: + + try: + res = await shield(something()) + except CancelledError: + res = None + _inner_done_callback_outer_done_callbackSubmit a coroutine object to a given event loop. + + Return a concurrent.futures.Future to access the result. + A coroutine object is requiredRegister a new task in asyncio as executed by loop.Cannot enter into task while another task " while another ""task " is being executed.Leaving task does not match the current task " does not match ""the current task "Unregister a task._py_register_task_py_unregister_task_py_enter_task_py_leave_task_c_register_task_c_unregister_task_c_enter_task_c_leave_task# Helper to generate new task names# This uses itertools.count() instead of a "+= 1" operation because the latter# is not thread safe. See bpo-11866 for a longer explanation.# Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another# thread while we do so. Therefore we cast it to list prior to filtering. The list# cast itself requires iteration, so we repeat it several times ignoring# RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for# Different from "all_task()" by returning *all* Tasks, including# the completed ones. Used to implement deprecated "Tasks.all_task()"# method.# Inherit Python Task implementation# from a Python Future implementation.# An important invariant maintained while a Task not done:# - Either _fut_waiter is None, and _step() is scheduled;# - or _fut_waiter is some Future, and _step() is *not* scheduled.# The only transition from the latter to the former is through# _wakeup(). When _fut_waiter is not None, one of its callbacks# must be _wakeup().# If False, don't log a message if the task is destroyed whereas its# status is still pending# raise after Future.__init__(), attrs are required for __del__# prevent logging for pending task in __del__# Leave self._fut_waiter; it may be a Task that# catches and ignores the cancellation so we may have# to cancel it again later.# It must be the case that self.__step is already scheduled.# Call either coro.throw(exc) or coro.send(None).# We use the `send` method directly, because coroutines# don't have `__iter__` and `__next__` methods.# Task is cancelled right before coro stops.# I.e., Future.cancel(self).# Yielded Future must come from Future.__iter__().# Bare yield relinquishes control for one event loop iteration.# Yielding a generator is just wrong.# Yielding something else is an error.# This may also be a cancellation.# Don't pass the value of `future.result()` explicitly,# as `Future.__iter__` and `Future.__await__` don't need it.# If we call `_step(value, None)` instead of `_step()`,# Python eval loop would use `.send(value)` method call,# instead of `__next__()`, which is slower for futures# that return non-generator iterators from their `__iter__`.# _CTask is needed for tests.# wait() and as_completed() similar to those in PEP 3148.# wait until the future completes or the timeout# We must ensure that the task is not running# after wait_for() returns.# See https://bugs.python.org/issue32751# We cannot wait on *fut* directly to make# sure _cancel_and_wait itself is reliably cancellable.# This is *not* a @coroutine! It is just an iterator (yielding Futures).# Import here to avoid circular import problem.# Queue a dummy value for _wait_for_one().# Can't do todo.remove(f) in the loop.# _on_timeout() was here first.# Dummy value from _on_timeout().# May raise f.exception().# If any child tasks were actually cancelled, we should# propagate the cancellation request regardless of# *return_exceptions* argument. See issue 32684.# Mark exception retrieved.# Check if 'fut' is cancelled first, as# 'fut.exception()' will *raise* a CancelledError# instead of returning it.# All futures are done; create a list of results# and set it to the 'outer' future.# If gather is being cancelled we must propagate the# cancellation regardless of *return_exceptions* argument.# See issue 32684.# 'arg' was not a Future, therefore, 'fut' is a new# Future created specifically for 'arg'. Since the caller# can't control it, disable the "destroy pending task"# warning.# There's a duplicate Future object in coros_or_futures.# Shortcut.# Mark inner's result as retrieved.# WeakSet containing all alive tasks.# Dictionary containing tasks that are currently active in# all running event loops. {EventLoop: Task}b'Support for tasks, coroutines and the scheduler.'u'Support for tasks, coroutines and the scheduler.'b'Task'u'Task'b'create_task'u'create_task'b'wait_for'u'wait_for'b'sleep'u'sleep'b'gather'u'gather'b'shield'u'shield'b'ensure_future'u'ensure_future'b'run_coroutine_threadsafe'u'run_coroutine_threadsafe'b'current_task'u'current_task'b'all_tasks'u'all_tasks'b'_register_task'u'_register_task'b'_unregister_task'u'_unregister_task'b'_enter_task'u'_enter_task'b'_leave_task'u'_leave_task'b'Return a currently executed task.'u'Return a currently executed task.'b'Return a set of all tasks for the loop.'u'Return a set of all tasks for the loop.'b'A coroutine wrapped in a Future.'b'Return the currently running task in an event loop or None. + + By default the current task for the current event loop is returned. + + None is returned when called not in the context of a Task. + 'u'Return the currently running task in an event loop or None. + + By default the current task for the current event loop is returned. + + None is returned when called not in the context of a Task. + 'b'Task.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead'u'Task.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead'b'Return a set of all tasks for an event loop. + + By default all tasks for the current event loop are returned. + 'u'Return a set of all tasks for an event loop. + + By default all tasks for the current event loop are returned. + 'b'Task.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() instead'u'Task.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() instead'b'a coroutine was expected, got 'u'a coroutine was expected, got 'b'Task-'u'Task-'b'Task was destroyed but it is pending!'u'Task was destroyed but it is pending!'b'Task does not support set_result operation'u'Task does not support set_result operation'b'Task does not support set_exception operation'u'Task does not support set_exception operation'b'Return the list of stack frames for this task's coroutine. + + If the coroutine is not done, this returns the stack where it is + suspended. If the coroutine has completed successfully or was + cancelled, this returns an empty list. If the coroutine was + terminated by an exception, this returns the list of traceback + frames. + + The frames are always ordered from oldest to newest. + + The optional limit gives the maximum number of frames to + return; by default all available frames are returned. Its + meaning differs depending on whether a stack or a traceback is + returned: the newest frames of a stack are returned, but the + oldest frames of a traceback are returned. (This matches the + behavior of the traceback module.) + + For reasons beyond our control, only one stack frame is + returned for a suspended coroutine. + 'u'Return the list of stack frames for this task's coroutine. + + If the coroutine is not done, this returns the stack where it is + suspended. If the coroutine has completed successfully or was + cancelled, this returns an empty list. If the coroutine was + terminated by an exception, this returns the list of traceback + frames. + + The frames are always ordered from oldest to newest. + + The optional limit gives the maximum number of frames to + return; by default all available frames are returned. Its + meaning differs depending on whether a stack or a traceback is + returned: the newest frames of a stack are returned, but the + oldest frames of a traceback are returned. (This matches the + behavior of the traceback module.) + + For reasons beyond our control, only one stack frame is + returned for a suspended coroutine. + 'b'Print the stack or traceback for this task's coroutine. + + This produces output similar to that of the traceback module, + for the frames retrieved by get_stack(). The limit argument + is passed to get_stack(). The file argument is an I/O stream + to which the output is written; by default output is written + to sys.stderr. + 'u'Print the stack or traceback for this task's coroutine. + + This produces output similar to that of the traceback module, + for the frames retrieved by get_stack(). The limit argument + is passed to get_stack(). The file argument is an I/O stream + to which the output is written; by default output is written + to sys.stderr. + 'b'Request that this task cancel itself. + + This arranges for a CancelledError to be thrown into the + wrapped coroutine on the next cycle through the event loop. + The coroutine then has a chance to clean up or even deny + the request using try/except/finally. + + Unlike Future.cancel, this does not guarantee that the + task will be cancelled: the exception might be caught and + acted upon, delaying cancellation of the task or preventing + cancellation completely. The task may also return a value or + raise a different exception. + + Immediately after this method is called, Task.cancelled() will + not return True (unless the task was already cancelled). A + task will be marked as cancelled when the wrapped coroutine + terminates with a CancelledError exception (even if cancel() + was not called). + 'u'Request that this task cancel itself. + + This arranges for a CancelledError to be thrown into the + wrapped coroutine on the next cycle through the event loop. + The coroutine then has a chance to clean up or even deny + the request using try/except/finally. + + Unlike Future.cancel, this does not guarantee that the + task will be cancelled: the exception might be caught and + acted upon, delaying cancellation of the task or preventing + cancellation completely. The task may also return a value or + raise a different exception. + + Immediately after this method is called, Task.cancelled() will + not return True (unless the task was already cancelled). A + task will be marked as cancelled when the wrapped coroutine + terminates with a CancelledError exception (even if cancel() + was not called). + 'b'_step(): already done: 'u'_step(): already done: 'b'Task 'u'Task 'b' got Future 'u' got Future 'b' attached to a different loop'u' attached to a different loop'b'Task cannot await on itself: 'u'Task cannot await on itself: 'b'yield was used instead of yield from in task 'u'yield was used instead of yield from in task 'b' with 'u' with 'b'yield was used instead of yield from for generator in task 'u'yield was used instead of yield from for generator in task 'b'Task got bad yield: 'u'Task got bad yield: 'b'Schedule the execution of a coroutine object in a spawn task. + + Return a Task object. + 'u'Schedule the execution of a coroutine object in a spawn task. + + Return a Task object. + 'b'Wait for the Futures and coroutines given by fs to complete. + + The fs iterable must not be empty. + + Coroutines will be wrapped in Tasks. + + Returns two sets of Future: (done, pending). + + Usage: + + done, pending = await asyncio.wait(fs) + + Note: This does not raise TimeoutError! Futures that aren't done + when the timeout occurs are returned in the second set. + 'u'Wait for the Futures and coroutines given by fs to complete. + + The fs iterable must not be empty. + + Coroutines will be wrapped in Tasks. + + Returns two sets of Future: (done, pending). + + Usage: + + done, pending = await asyncio.wait(fs) + + Note: This does not raise TimeoutError! Futures that aren't done + when the timeout occurs are returned in the second set. + 'b'expect a list of futures, not 'u'expect a list of futures, not 'b'Set of coroutines/Futures is empty.'u'Set of coroutines/Futures is empty.'b'Invalid return_when value: 'u'Invalid return_when value: 'b'Wait for the single Future or coroutine to complete, with timeout. + + Coroutine will be wrapped in Task. + + Returns result of the Future or coroutine. When a timeout occurs, + it cancels the task and raises TimeoutError. To avoid the task + cancellation, wrap it in shield(). + + If the wait is cancelled, the task is also cancelled. + + This function is a coroutine. + 'u'Wait for the single Future or coroutine to complete, with timeout. + + Coroutine will be wrapped in Task. + + Returns result of the Future or coroutine. When a timeout occurs, + it cancels the task and raises TimeoutError. To avoid the task + cancellation, wrap it in shield(). + + If the wait is cancelled, the task is also cancelled. + + This function is a coroutine. + 'b'Internal helper for wait(). + + The fs argument must be a collection of Futures. + 'u'Internal helper for wait(). + + The fs argument must be a collection of Futures. + 'b'Set of Futures is empty.'u'Set of Futures is empty.'b'Cancel the *fut* future or task and wait until it completes.'u'Cancel the *fut* future or task and wait until it completes.'b'Return an iterator whose values are coroutines. + + When waiting for the yielded coroutines you'll get the results (or + exceptions!) of the original Futures (or coroutines), in the order + in which and as soon as they complete. + + This differs from PEP 3148; the proper way to use this is: + + for f in as_completed(fs): + result = await f # The 'await' may raise. + # Use result. + + If a timeout is specified, the 'await' will raise + TimeoutError when the timeout occurs before all Futures are done. + + Note: The futures 'f' are not necessarily members of fs. + 'u'Return an iterator whose values are coroutines. + + When waiting for the yielded coroutines you'll get the results (or + exceptions!) of the original Futures (or coroutines), in the order + in which and as soon as they complete. + + This differs from PEP 3148; the proper way to use this is: + + for f in as_completed(fs): + result = await f # The 'await' may raise. + # Use result. + + If a timeout is specified, the 'await' will raise + TimeoutError when the timeout occurs before all Futures are done. + + Note: The futures 'f' are not necessarily members of fs. + 'b'expect an iterable of futures, not 'u'expect an iterable of futures, not 'b'Skip one event loop run cycle. + + This is a private helper for 'asyncio.sleep()', used + when the 'delay' is set to 0. It uses a bare 'yield' + expression (which Task.__step knows how to handle) + instead of creating a Future object. + 'u'Skip one event loop run cycle. + + This is a private helper for 'asyncio.sleep()', used + when the 'delay' is set to 0. It uses a bare 'yield' + expression (which Task.__step knows how to handle) + instead of creating a Future object. + 'b'Coroutine that completes after a given time (in seconds).'u'Coroutine that completes after a given time (in seconds).'b'Wrap a coroutine or an awaitable in a future. + + If the argument is a Future, it is returned directly. + 'u'Wrap a coroutine or an awaitable in a future. + + If the argument is a Future, it is returned directly. + 'b'The future belongs to a different loop than the one specified as the loop argument'u'The future belongs to a different loop than the one specified as the loop argument'b'An asyncio.Future, a coroutine or an awaitable is required'u'An asyncio.Future, a coroutine or an awaitable is required'b'Helper for asyncio.ensure_future(). + + Wraps awaitable (an object with __await__) into a coroutine + that will later be wrapped in a Task by ensure_future(). + 'u'Helper for asyncio.ensure_future(). + + Wraps awaitable (an object with __await__) into a coroutine + that will later be wrapped in a Task by ensure_future(). + 'b'Helper for gather(). + + This overrides cancel() to cancel all the children and act more + like Task.cancel(), which doesn't immediately mark itself as + cancelled. + 'u'Helper for gather(). + + This overrides cancel() to cancel all the children and act more + like Task.cancel(), which doesn't immediately mark itself as + cancelled. + 'b'Return a future aggregating results from the given coroutines/futures. + + Coroutines will be wrapped in a future and scheduled in the event + loop. They will not necessarily be scheduled in the same order as + passed in. + + All futures must share the same event loop. If all the tasks are + done successfully, the returned future's result is the list of + results (in the order of the original sequence, not necessarily + the order of results arrival). If *return_exceptions* is True, + exceptions in the tasks are treated the same as successful + results, and gathered in the result list; otherwise, the first + raised exception will be immediately propagated to the returned + future. + + Cancellation: if the outer Future is cancelled, all children (that + have not completed yet) are also cancelled. If any child is + cancelled, this is treated as if it raised CancelledError -- + the outer Future is *not* cancelled in this case. (This is to + prevent the cancellation of one child to cause other children to + be cancelled.) + + If *return_exceptions* is False, cancelling gather() after it + has been marked done won't cancel any submitted awaitables. + For instance, gather can be marked done after propagating an + exception to the caller, therefore, calling ``gather.cancel()`` + after catching an exception (raised by one of the awaitables) from + gather won't cancel any other awaitables. + 'u'Return a future aggregating results from the given coroutines/futures. + + Coroutines will be wrapped in a future and scheduled in the event + loop. They will not necessarily be scheduled in the same order as + passed in. + + All futures must share the same event loop. If all the tasks are + done successfully, the returned future's result is the list of + results (in the order of the original sequence, not necessarily + the order of results arrival). If *return_exceptions* is True, + exceptions in the tasks are treated the same as successful + results, and gathered in the result list; otherwise, the first + raised exception will be immediately propagated to the returned + future. + + Cancellation: if the outer Future is cancelled, all children (that + have not completed yet) are also cancelled. If any child is + cancelled, this is treated as if it raised CancelledError -- + the outer Future is *not* cancelled in this case. (This is to + prevent the cancellation of one child to cause other children to + be cancelled.) + + If *return_exceptions* is False, cancelling gather() after it + has been marked done won't cancel any submitted awaitables. + For instance, gather can be marked done after propagating an + exception to the caller, therefore, calling ``gather.cancel()`` + after catching an exception (raised by one of the awaitables) from + gather won't cancel any other awaitables. + 'b'Wait for a future, shielding it from cancellation. + + The statement + + res = await shield(something()) + + is exactly equivalent to the statement + + res = await something() + + *except* that if the coroutine containing it is cancelled, the + task running in something() is not cancelled. From the POV of + something(), the cancellation did not happen. But its caller is + still cancelled, so the yield-from expression still raises + CancelledError. Note: If something() is cancelled by other means + this will still cancel shield(). + + If you want to completely ignore cancellation (not recommended) + you can combine shield() with a try/except clause, as follows: + + try: + res = await shield(something()) + except CancelledError: + res = None + 'u'Wait for a future, shielding it from cancellation. + + The statement + + res = await shield(something()) + + is exactly equivalent to the statement + + res = await something() + + *except* that if the coroutine containing it is cancelled, the + task running in something() is not cancelled. From the POV of + something(), the cancellation did not happen. But its caller is + still cancelled, so the yield-from expression still raises + CancelledError. Note: If something() is cancelled by other means + this will still cancel shield(). + + If you want to completely ignore cancellation (not recommended) + you can combine shield() with a try/except clause, as follows: + + try: + res = await shield(something()) + except CancelledError: + res = None + 'b'Submit a coroutine object to a given event loop. + + Return a concurrent.futures.Future to access the result. + 'u'Submit a coroutine object to a given event loop. + + Return a concurrent.futures.Future to access the result. + 'b'A coroutine object is required'u'A coroutine object is required'b'Register a new task in asyncio as executed by loop.'u'Register a new task in asyncio as executed by loop.'b'Cannot enter into task 'u'Cannot enter into task 'b' while another task 'u' while another task 'b' is being executed.'u' is being executed.'b'Leaving task 'u'Leaving task 'b' does not match the current task 'u' does not match the current task 'b'Unregister a task.'u'Unregister a task.'u'asyncio.tasks'u'tasks'Temporary files. + +This module provides generic, low- and high-level interfaces for +creating temporary files and directories. All of the interfaces +provided by this module can be used without fear of race conditions +except for 'mktemp'. 'mktemp' is subject to race conditions and +should not be used; it is provided for backward compatibility only. + +The default path names are returned as str. If you supply bytes as +input, all return values will be in bytes. Ex: + + >>> tempfile.mkstemp() + (4, '/tmp/tmptpu9nin8') + >>> tempfile.mkdtemp(suffix=b'') + b'/tmp/tmppbi8f0hy' + +This module also provides some data items to the user: + + TMP_MAX - maximum number of names that will be tried before + giving up. + tempdir - If this is set to a string before the first use of + any routine from this module, it will be considered as + another candidate location to store temporary files. +TemporaryFileSpooledTemporaryFilegettempprefixgettempdirgettempprefixbgettempdirb_errno_Random_allocate_lock_text_openflags_bin_openflags_once_lock_infer_return_typeLook at the type of all args and divine their implied return type.return_typeCan't mix bytes and non-bytes in path components."Can't mix bytes and non-bytes in ""path components."_sanitize_paramsCommon parameter processing for most APIs in this module.output_type_RandomNameSequenceAn instance of _RandomNameSequence generates an endless + sequence of unpredictable strings which can safely be incorporated + into file names. Each string is eight characters long. Multiple + threads can safely use the same instance at the same time. + + _RandomNameSequence is an iterator.abcdefghijklmnopqrstuvwxyz0123456789_characterscur_pid_rng_pid_rngchooseletters_candidate_tempdir_listGenerate a list of candidate temporary directories which + _get_default_tempdir will try.envnameTMPDIRTEMPTMP~\AppData\Local\Temp%SYSTEMROOT%\Tempc:\tempc:\tmp\temp\tmp/tmp/var/tmp/usr/tmp_get_default_tempdirCalculate the default directory to use for temporary files. + This routine should be called exactly once. + + We determine whether or not a candidate temp dir is usable by + trying to create and write to a file in that directory. If this + is successful, the test file is deleted. To prevent denial of + service, the name of the test file must be randomized.blatNo usable temporary directory found in %s_name_sequence_get_candidate_namesCommon setup sequence for all user-callable interfaces._mkstemp_innersufCode common to mkstemp, TemporaryFile, and NamedTemporaryFile.tempfile.mkstempNo usable temporary file name foundThe default prefix for temporary directories.The default prefix for temporary directories as bytes.Accessor for tempfile.tempdir.A bytes version of tempfile.gettempdir().User-callable function to create and return a unique temporary + file. The return value is a pair (fd, name) where fd is the + file descriptor returned by os.open, and name is the filename. + + If 'suffix' is not None, the file name will end with that suffix, + otherwise there will be no suffix. + + If 'prefix' is not None, the file name will begin with that prefix, + otherwise a default prefix is used. + + If 'dir' is not None, the file will be created in that directory, + otherwise a default directory is used. + + If 'text' is specified and true, the file is opened in text + mode. Else (the default) the file is opened in binary mode. + + If any of 'suffix', 'prefix' and 'dir' are not None, they must be the + same type. If they are bytes, the returned name will be bytes; str + otherwise. + + The file is readable and writable only by the creating user ID. + If the operating system uses permission bits to indicate whether a + file is executable, the file is executable by no one. The file + descriptor is not inherited by children of this process. + + Caller is responsible for deleting the file when done with it. + User-callable function to create and return a unique temporary + directory. The return value is the pathname of the directory. + + Arguments are as for mkstemp, except that the 'text' argument is + not accepted. + + The directory is readable, writable, and searchable only by the + creating user. + + Caller is responsible for deleting the directory when done with it. + tempfile.mkdtempNo usable temporary directory name foundUser-callable function to return a unique temporary file name. The + file is not created. + + Arguments are similar to mkstemp, except that the 'text' argument is + not accepted, and suffix=None, prefix=None and bytes file names are not + supported. + + THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may + refer to a file that did not exist at some point, but by the time + you get around to creating it, someone else may have beaten you to + the punch. + No usable temporary filename found_TemporaryFileCloserA separate object allowing proper closing of a temporary file's + underlying file object, without adding a __del__ method to the + temporary file.close_calledTemporary file wrapper + + This class provides a wrapper around files opened for + temporary use. In particular, it seeks to automatically + remove the file when it is no longer needed. + _closerfunc_wrapper + Close the temporary file, possibly deleting it. + Create and return a temporary file. + Arguments: + 'prefix', 'suffix', 'dir' -- as for mkstemp. + 'mode' -- the mode argument to io.open (default "w+b"). + 'buffering' -- the buffer size argument to io.open (default -1). + 'encoding' -- the encoding argument to io.open (default None) + 'newline' -- the newline argument to io.open (default None) + 'delete' -- whether the file is deleted on close (default True). + 'errors' -- the errors argument to io.open (default None) + The file is created as mkstemp() would do it. + + Returns an object with a file-like interface; the name of the file + is accessible as its 'name' attribute. The file will be automatically + deleted when it is closed unless the 'delete' argument is set to False. + O_TEMPORARYO_TMPFILE_O_TMPFILE_WORKSCreate and return a temporary file. + Arguments: + 'prefix', 'suffix', 'dir' -- as for mkstemp. + 'mode' -- the mode argument to io.open (default "w+b"). + 'buffering' -- the buffer size argument to io.open (default -1). + 'encoding' -- the encoding argument to io.open (default None) + 'newline' -- the newline argument to io.open (default None) + 'errors' -- the errors argument to io.open (default None) + The file is created as mkstemp() would do it. + + Returns an object with a file-like interface. The file has no + name, and will cease to exist when it is closed. + flags2Temporary file wrapper, specialized to switch from BytesIO + or StringIO to a real file when it exceeds a certain size or + when a fileno is needed. + _rolled_file_max_size_TemporaryFileArgsrolloverCannot enter context with closed filesoftspaceCreate and return a temporary directory. This has the same + behavior as mkdtemp but can be used as a context manager. For + example: + + with TemporaryDirectory() as tmpdir: + ... + + Upon exiting the context, the directory and everything contained + in it are removed. + finalizeImplicitly cleaning up {!r}warn_message_finalizerresetperms<{} {!r}># high level safe interfaces# low level safe interfaces# deprecated unsafe interface# constants# Imports.# This variable _was_ unused for legacy reasons, see issue 10354.# But as of 3.5 we actually use it at runtime so changing it would# have a possibly desirable side effect... But we do not want to support# that as an API. It is undocumented on purpose. Do not depend on this.# Internal routines.# tempfile APIs return a str by default.# First, try the environment.# Failing that, try OS-specific locations.# As a last resort, the current directory.# Try only a few names per directory.# This exception is thrown when a directory with the chosen name# already exists on windows.# no point trying more names in this directory# try again# User visible interfaces.## from warnings import warn as _warn## _warn("mktemp is a potential security risk to your program",## RuntimeWarning, stacklevel=2)# NT provides delete-on-close as a primitive, so we don't need# the wrapper to do anything special. We still use it so that# file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.# Cache the unlinker so we don't get spurious errors at# shutdown when the module-level "os" is None'd out. Note# that this must be referenced as self.unlink, because the# name TemporaryFileWrapper may also get None'd out before# __del__ is called.# Need to ensure the file is deleted on __del__# Attribute lookups are delegated to the underlying file# and cached for non-numeric results# (i.e. methods are cached, closed and friends are not)# Avoid closing the file as long as the wrapper is alive,# see issue #18879.# The underlying __enter__ method returns the wrong object# (self.file) so override it to return the wrapper# Need to trap __exit__ as well to ensure the file gets# deleted when used in a with statement# iter() doesn't use __getattr__ to find the __iter__ method# Don't return iter(self.file), but yield from it to avoid closing# file as long as it's being used as iterator (see issue #23700). We# can't use 'yield from' here because iter(file) returns the file# object itself, which has a close method, and thus the file would get# closed when the generator is finalized, due to PEP380 semantics.# Setting O_TEMPORARY in the flags causes the OS to delete# the file when it is closed. This is only supported by Windows.# On non-POSIX and Cygwin systems, assume that we cannot unlink a file# while it is open.# Is the O_TMPFILE flag available and does it work?# The flag is set to False if os.open(dir, os.O_TMPFILE) raises an# IsADirectoryError exception# Linux kernel older than 3.11 ignores the O_TMPFILE flag:# O_TMPFILE is read as O_DIRECTORY. Trying to open a directory# with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a# directory cannot be open to write. Set flag to False to not# try again.# The filesystem of the directory does not support O_TMPFILE.# For example, OSError(95, 'Operation not supported').# On Linux kernel older than 3.11, trying to open a regular# file (or a symbolic link to a regular file) with O_TMPFILE# fails with NotADirectoryError, because O_TMPFILE is read as# O_DIRECTORY.# Fallback to _mkstemp_inner().# The method caching trick from NamedTemporaryFile# won't work here, because _file may change from a# BytesIO/StringIO instance to a real file. So we list# all the methods directly.# Context management protocol# file protocol# PermissionError is raised on FreeBSD for directoriesb'Temporary files. + +This module provides generic, low- and high-level interfaces for +creating temporary files and directories. All of the interfaces +provided by this module can be used without fear of race conditions +except for 'mktemp'. 'mktemp' is subject to race conditions and +should not be used; it is provided for backward compatibility only. + +The default path names are returned as str. If you supply bytes as +input, all return values will be in bytes. Ex: + + >>> tempfile.mkstemp() + (4, '/tmp/tmptpu9nin8') + >>> tempfile.mkdtemp(suffix=b'') + b'/tmp/tmppbi8f0hy' + +This module also provides some data items to the user: + + TMP_MAX - maximum number of names that will be tried before + giving up. + tempdir - If this is set to a string before the first use of + any routine from this module, it will be considered as + another candidate location to store temporary files. +'u'Temporary files. + +This module provides generic, low- and high-level interfaces for +creating temporary files and directories. All of the interfaces +provided by this module can be used without fear of race conditions +except for 'mktemp'. 'mktemp' is subject to race conditions and +should not be used; it is provided for backward compatibility only. + +The default path names are returned as str. If you supply bytes as +input, all return values will be in bytes. Ex: + + >>> tempfile.mkstemp() + (4, '/tmp/tmptpu9nin8') + >>> tempfile.mkdtemp(suffix=b'') + b'/tmp/tmppbi8f0hy' + +This module also provides some data items to the user: + + TMP_MAX - maximum number of names that will be tried before + giving up. + tempdir - If this is set to a string before the first use of + any routine from this module, it will be considered as + another candidate location to store temporary files. +'b'NamedTemporaryFile'u'NamedTemporaryFile'b'TemporaryFile'u'TemporaryFile'b'SpooledTemporaryFile'u'SpooledTemporaryFile'b'TemporaryDirectory'u'TemporaryDirectory'b'mkstemp'u'mkstemp'b'mkdtemp'u'mkdtemp'b'mktemp'u'mktemp'b'TMP_MAX'u'TMP_MAX'b'gettempprefix'u'gettempprefix'b'tempdir'u'tempdir'b'gettempdir'u'gettempdir'b'gettempprefixb'u'gettempprefixb'b'gettempdirb'u'gettempdirb'b'O_NOFOLLOW'u'O_NOFOLLOW'b'tmp'u'tmp'b'Look at the type of all args and divine their implied return type.'u'Look at the type of all args and divine their implied return type.'b'Can't mix bytes and non-bytes in path components.'u'Can't mix bytes and non-bytes in path components.'b'Common parameter processing for most APIs in this module.'u'Common parameter processing for most APIs in this module.'b'An instance of _RandomNameSequence generates an endless + sequence of unpredictable strings which can safely be incorporated + into file names. Each string is eight characters long. Multiple + threads can safely use the same instance at the same time. + + _RandomNameSequence is an iterator.'u'An instance of _RandomNameSequence generates an endless + sequence of unpredictable strings which can safely be incorporated + into file names. Each string is eight characters long. Multiple + threads can safely use the same instance at the same time. + + _RandomNameSequence is an iterator.'b'abcdefghijklmnopqrstuvwxyz0123456789_'u'abcdefghijklmnopqrstuvwxyz0123456789_'b'_rng_pid'u'_rng_pid'b'Generate a list of candidate temporary directories which + _get_default_tempdir will try.'u'Generate a list of candidate temporary directories which + _get_default_tempdir will try.'b'TMPDIR'u'TMPDIR'b'TEMP'u'TEMP'b'TMP'u'TMP'b'~\AppData\Local\Temp'u'~\AppData\Local\Temp'b'%SYSTEMROOT%\Temp'u'%SYSTEMROOT%\Temp'b'c:\temp'u'c:\temp'b'c:\tmp'u'c:\tmp'b'\temp'u'\temp'b'\tmp'u'\tmp'b'/tmp'u'/tmp'b'/var/tmp'u'/var/tmp'b'/usr/tmp'u'/usr/tmp'b'Calculate the default directory to use for temporary files. + This routine should be called exactly once. + + We determine whether or not a candidate temp dir is usable by + trying to create and write to a file in that directory. If this + is successful, the test file is deleted. To prevent denial of + service, the name of the test file must be randomized.'u'Calculate the default directory to use for temporary files. + This routine should be called exactly once. + + We determine whether or not a candidate temp dir is usable by + trying to create and write to a file in that directory. If this + is successful, the test file is deleted. To prevent denial of + service, the name of the test file must be randomized.'b'blat'b'No usable temporary directory found in %s'u'No usable temporary directory found in %s'b'Common setup sequence for all user-callable interfaces.'u'Common setup sequence for all user-callable interfaces.'b'Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.'u'Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.'b'tempfile.mkstemp'u'tempfile.mkstemp'b'No usable temporary file name found'u'No usable temporary file name found'b'The default prefix for temporary directories.'u'The default prefix for temporary directories.'b'The default prefix for temporary directories as bytes.'u'The default prefix for temporary directories as bytes.'b'Accessor for tempfile.tempdir.'u'Accessor for tempfile.tempdir.'b'A bytes version of tempfile.gettempdir().'u'A bytes version of tempfile.gettempdir().'b'User-callable function to create and return a unique temporary + file. The return value is a pair (fd, name) where fd is the + file descriptor returned by os.open, and name is the filename. + + If 'suffix' is not None, the file name will end with that suffix, + otherwise there will be no suffix. + + If 'prefix' is not None, the file name will begin with that prefix, + otherwise a default prefix is used. + + If 'dir' is not None, the file will be created in that directory, + otherwise a default directory is used. + + If 'text' is specified and true, the file is opened in text + mode. Else (the default) the file is opened in binary mode. + + If any of 'suffix', 'prefix' and 'dir' are not None, they must be the + same type. If they are bytes, the returned name will be bytes; str + otherwise. + + The file is readable and writable only by the creating user ID. + If the operating system uses permission bits to indicate whether a + file is executable, the file is executable by no one. The file + descriptor is not inherited by children of this process. + + Caller is responsible for deleting the file when done with it. + 'u'User-callable function to create and return a unique temporary + file. The return value is a pair (fd, name) where fd is the + file descriptor returned by os.open, and name is the filename. + + If 'suffix' is not None, the file name will end with that suffix, + otherwise there will be no suffix. + + If 'prefix' is not None, the file name will begin with that prefix, + otherwise a default prefix is used. + + If 'dir' is not None, the file will be created in that directory, + otherwise a default directory is used. + + If 'text' is specified and true, the file is opened in text + mode. Else (the default) the file is opened in binary mode. + + If any of 'suffix', 'prefix' and 'dir' are not None, they must be the + same type. If they are bytes, the returned name will be bytes; str + otherwise. + + The file is readable and writable only by the creating user ID. + If the operating system uses permission bits to indicate whether a + file is executable, the file is executable by no one. The file + descriptor is not inherited by children of this process. + + Caller is responsible for deleting the file when done with it. + 'b'User-callable function to create and return a unique temporary + directory. The return value is the pathname of the directory. + + Arguments are as for mkstemp, except that the 'text' argument is + not accepted. + + The directory is readable, writable, and searchable only by the + creating user. + + Caller is responsible for deleting the directory when done with it. + 'u'User-callable function to create and return a unique temporary + directory. The return value is the pathname of the directory. + + Arguments are as for mkstemp, except that the 'text' argument is + not accepted. + + The directory is readable, writable, and searchable only by the + creating user. + + Caller is responsible for deleting the directory when done with it. + 'b'tempfile.mkdtemp'u'tempfile.mkdtemp'b'No usable temporary directory name found'u'No usable temporary directory name found'b'User-callable function to return a unique temporary file name. The + file is not created. + + Arguments are similar to mkstemp, except that the 'text' argument is + not accepted, and suffix=None, prefix=None and bytes file names are not + supported. + + THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may + refer to a file that did not exist at some point, but by the time + you get around to creating it, someone else may have beaten you to + the punch. + 'u'User-callable function to return a unique temporary file name. The + file is not created. + + Arguments are similar to mkstemp, except that the 'text' argument is + not accepted, and suffix=None, prefix=None and bytes file names are not + supported. + + THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may + refer to a file that did not exist at some point, but by the time + you get around to creating it, someone else may have beaten you to + the punch. + 'b'No usable temporary filename found'u'No usable temporary filename found'b'A separate object allowing proper closing of a temporary file's + underlying file object, without adding a __del__ method to the + temporary file.'u'A separate object allowing proper closing of a temporary file's + underlying file object, without adding a __del__ method to the + temporary file.'b'Temporary file wrapper + + This class provides a wrapper around files opened for + temporary use. In particular, it seeks to automatically + remove the file when it is no longer needed. + 'u'Temporary file wrapper + + This class provides a wrapper around files opened for + temporary use. In particular, it seeks to automatically + remove the file when it is no longer needed. + 'b' + Close the temporary file, possibly deleting it. + 'u' + Close the temporary file, possibly deleting it. + 'b'Create and return a temporary file. + Arguments: + 'prefix', 'suffix', 'dir' -- as for mkstemp. + 'mode' -- the mode argument to io.open (default "w+b"). + 'buffering' -- the buffer size argument to io.open (default -1). + 'encoding' -- the encoding argument to io.open (default None) + 'newline' -- the newline argument to io.open (default None) + 'delete' -- whether the file is deleted on close (default True). + 'errors' -- the errors argument to io.open (default None) + The file is created as mkstemp() would do it. + + Returns an object with a file-like interface; the name of the file + is accessible as its 'name' attribute. The file will be automatically + deleted when it is closed unless the 'delete' argument is set to False. + 'u'Create and return a temporary file. + Arguments: + 'prefix', 'suffix', 'dir' -- as for mkstemp. + 'mode' -- the mode argument to io.open (default "w+b"). + 'buffering' -- the buffer size argument to io.open (default -1). + 'encoding' -- the encoding argument to io.open (default None) + 'newline' -- the newline argument to io.open (default None) + 'delete' -- whether the file is deleted on close (default True). + 'errors' -- the errors argument to io.open (default None) + The file is created as mkstemp() would do it. + + Returns an object with a file-like interface; the name of the file + is accessible as its 'name' attribute. The file will be automatically + deleted when it is closed unless the 'delete' argument is set to False. + 'b'O_TMPFILE'u'O_TMPFILE'b'Create and return a temporary file. + Arguments: + 'prefix', 'suffix', 'dir' -- as for mkstemp. + 'mode' -- the mode argument to io.open (default "w+b"). + 'buffering' -- the buffer size argument to io.open (default -1). + 'encoding' -- the encoding argument to io.open (default None) + 'newline' -- the newline argument to io.open (default None) + 'errors' -- the errors argument to io.open (default None) + The file is created as mkstemp() would do it. + + Returns an object with a file-like interface. The file has no + name, and will cease to exist when it is closed. + 'u'Create and return a temporary file. + Arguments: + 'prefix', 'suffix', 'dir' -- as for mkstemp. + 'mode' -- the mode argument to io.open (default "w+b"). + 'buffering' -- the buffer size argument to io.open (default -1). + 'encoding' -- the encoding argument to io.open (default None) + 'newline' -- the newline argument to io.open (default None) + 'errors' -- the errors argument to io.open (default None) + The file is created as mkstemp() would do it. + + Returns an object with a file-like interface. The file has no + name, and will cease to exist when it is closed. + 'b'Temporary file wrapper, specialized to switch from BytesIO + or StringIO to a real file when it exceeds a certain size or + when a fileno is needed. + 'u'Temporary file wrapper, specialized to switch from BytesIO + or StringIO to a real file when it exceeds a certain size or + when a fileno is needed. + 'b'buffering'u'buffering'b'suffix'u'suffix'b'newline'u'newline'b'Cannot enter context with closed file'u'Cannot enter context with closed file'b'Create and return a temporary directory. This has the same + behavior as mkdtemp but can be used as a context manager. For + example: + + with TemporaryDirectory() as tmpdir: + ... + + Upon exiting the context, the directory and everything contained + in it are removed. + 'u'Create and return a temporary directory. This has the same + behavior as mkdtemp but can be used as a context manager. For + example: + + with TemporaryDirectory() as tmpdir: + ... + + Upon exiting the context, the directory and everything contained + in it are removed. + 'b'Implicitly cleaning up {!r}'u'Implicitly cleaning up {!r}'b'<{} {!r}>'u'<{} {!r}>'u'tempfile'B0B110115200B1152001200B1200B134B1501800B180019200B19200B200230400B2304002400B2400B30038400B384004800B4800B5057600B57600B600B759600B9600BRKINTBS0BS1BSDLYCDSUSPCEOFCEOLCEOTCERASECFLUSHCINTRCKILLCLNEXTCLOCALCQUITCR0CR1CR212288CR3CRDLYCREADCRPRNT196608CRTSCTSCS5CS6CS7CS8CSIZECSTARTCSTOPCSTOPBCSUSPCWERASEECHOECHOCTLECHOEECHOKECHOKEECHONLECHOPRTEXTAEXTBFF0FF1FFDLY2147772029FIOASYNC536897025FIOCLEX2147772030FIONBIO536897026FIONCLEX1074030207FIONREADFLUSHOHUPCLICANONICRNLIEXTENIGNBRKIGNCRIGNPARIMAXBELINLCRINPCKISIGISTRIPIXANYIXOFFIXONNCCSNL0NL1NLDLYNOFLSHOCRNLOFDELOFILLONLCRONLRETONOCROPOSTPARENBPARMRKPARODDPENDINTAB0TAB1TAB2TAB3TABDLYTCIFLUSHTCIOFFTCIOFLUSHTCIONTCOFLUSHTCOOFFTCOONTCSADRAINTCSANOWTCSASOFT2147775586TIOCCONS536900621TIOCEXCL1074033690TIOCGETD1074033783TIOCGPGRP1074295912TIOCGWINSZ2147775595TIOCMBIC2147775596TIOCMBIS1074033770TIOCMGET2147775597TIOCMSETTIOCM_CARTIOCM_CDTIOCM_CTSTIOCM_DSRTIOCM_DTRTIOCM_LETIOCM_RITIOCM_RNGTIOCM_RTSTIOCM_SRTIOCM_ST536900721TIOCNOTTY536900622TIOCNXCL1074033779TIOCOUTQ2147775600TIOCPKTTIOCPKT_DATATIOCPKT_DOSTOPTIOCPKT_FLUSHREADTIOCPKT_FLUSHWRITETIOCPKT_NOSTOPTIOCPKT_STARTTIOCPKT_STOP536900705TIOCSCTTY2147775515TIOCSETD2147775606TIOCSPGRP2147578994TIOCSTI2148037735TIOCSWINSZTOSTOPVDISCARDVEOFVEOLVEOL2VERASEVINTRVKILLVLNEXTVMINVQUITVREPRINTVSTARTVSTOPVSUSPVT0VT1VTDLYVTIMEVWERASEu'This module provides an interface to the Posix calls for tty I/O control. +For a complete description of these calls, see the Posix or Unix manual +pages. It is only available for those Unix versions that support Posix +termios style tty I/O control. + +All functions in this module take a file descriptor fd as their first +argument. This can be an integer file descriptor, such as returned by +sys.stdin.fileno(), or a file object, such as sys.stdin itself.'u'/Users/pwntester/.pyenv/versions/3.8.13/lib/python3.8/lib-dynload/termios.cpython-38-darwin.so'u'termios'termios.errortcdraintcflowtcflushtcsendbreaktermiosTest runner and result class for the regression test suite. + +ETRegressionTestResulttestsuite__suite__e__start_time__results__getId_add_resultsystem-outsystem-errv2__makeErrorDicterr_typeerr_valueerr_tbfailureskipped UNEXPECTED_SUCCESSflavorQuietRegressionTestRunnerget_test_runner_classTestTeststest_passtest_pass_slowtest_failfailure messagetest_errorerror messagerunner_clsOutput:XML: b'Test runner and result class for the regression test suite. + +'u'Test runner and result class for the regression test suite. + +'b'testsuite'u'testsuite'b'testcase'u'testcase'b'completed'u'completed'b'time'b'system-out'u'system-out'b'system-err'u'system-err'b'skipped 'u'skipped 'b'UNEXPECTED_SUCCESS'u'UNEXPECTED_SUCCESS'b'failures'u'failures'b'failure message'u'failure message'b'error message'u'error message'b'Output:'u'Output:'b'XML: 'u'XML: 'u'test.support.testresult'u'support.testresult'u'testresult'text_file + +provides the TextFile class, which gives an interface to text files +that (optionally) takes care of stripping comments, ignoring blank +lines, and joining lines with backslashes.Provides a file-like object that takes care of all the things you + commonly want to do when processing a text file that has some + line-by-line syntax: strip comments (as long as "#" is your + comment character), skip blank lines, join adjacent lines by + escaping the newline (ie. backslash at end of line), strip + leading and/or trailing whitespace. All of these are optional + and independently controllable. + + Provides a 'warn()' method so you can generate warning messages that + report physical line number, even if the logical line in question + spans multiple physical lines. Also provides 'unreadline()' for + implementing line-at-a-time lookahead. + + Constructor is called as: + + TextFile (filename=None, file=None, **options) + + It bombs (RuntimeError) if both 'filename' and 'file' are None; + 'filename' should be a string, and 'file' a file object (or + something that provides 'readline()' and 'close()' methods). It is + recommended that you supply at least 'filename', so that TextFile + can include it in warning messages. If 'file' is not supplied, + TextFile creates its own using 'io.open()'. + + The options are all boolean, and affect the value returned by + 'readline()': + strip_comments [default: true] + strip from "#" to end-of-line, as well as any whitespace + leading up to the "#" -- unless it is escaped by a backslash + lstrip_ws [default: false] + strip leading whitespace from each line before returning it + rstrip_ws [default: true] + strip trailing whitespace (including line terminator!) from + each line before returning it + skip_blanks [default: true} + skip lines that are empty *after* stripping comments and + whitespace. (If both lstrip_ws and rstrip_ws are false, + then some lines may consist of solely whitespace: these will + *not* be skipped, even if 'skip_blanks' is true.) + join_lines [default: false] + if a backslash is the last non-newline character on a line + after stripping comments and whitespace, join the following line + to it to form one "logical line"; if N consecutive lines end + with a backslash, then N+1 physical lines will be joined to + form one logical line. + collapse_join [default: false] + strip leading whitespace from lines that are joined to their + predecessor; only matters if (join_lines and not lstrip_ws) + errors [default: 'strict'] + error handler used to decode the file content + + Note that since 'rstrip_ws' can strip the trailing newline, the + semantics of 'readline()' must differ from those of the builtin file + object's 'readline()' method! In particular, 'readline()' returns + None for end-of-file: an empty string might just be a blank line (or + an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is + not.lstrip_wsrstrip_wscollapse_joindefault_optionsConstruct a new TextFile object. At least one of 'filename' + (a string) and 'file' (a file-like object) must be supplied. + They keyword argument options are described above and affect + the values returned by 'readline()'.you must supply either or both of 'filename' and 'file'invalid TextFile option '%s'linebufOpen a new file named 'filename'. This overrides both the + 'filename' and 'file' arguments to the constructor.Close the current file and forget everything we know about it + (filename, current line number).gen_erroroutmsglines %d-%d: line %d: error: Print (to stderr) a warning message tied to the current logical + line in the current file. If the current logical line in the + file spans multiple physical lines, the warning refers to the + whole range, eg. "lines 3-5". If 'line' supplied, it overrides + the current line number; it may be a list or tuple to indicate a + range of physical lines, or an integer for a single physical + line.warning: Read and return a single logical line from the current file (or + from an internal buffer if lines have previously been "unread" + with 'unreadline()'). If the 'join_lines' option is true, this + may involve reading multiple physical lines concatenated into a + single string. Updates the current line number, so calling + 'warn()' after 'readline()' emits a warning about the physical + line(s) just read. Returns None on end-of-file, since the empty + string can occur if 'rstrip_ws' is true but 'strip_blanks' is + not.buildup_line\#continuation line immediately precedes end-of-file"continuation line immediately precedes ""end-of-file"\ +Read and return the list of all logical lines remaining in the + current file.Push 'line' (a string) onto an internal buffer that will be + checked by future 'readline()' calls. Handy for implementing + a parser with line-at-a-time lookahead.# set values for all options -- either from client option hash# or fallback to default_options# sanity check client option hash# assuming that file is at BOF!# 'linebuf' is a stack of lines that will be emptied before we# actually read from the file; it's only populated by an# 'unreadline()' operation# If any "unread" lines waiting in 'linebuf', return the top# one. (We don't actually buffer read-ahead data -- lines only# get put in 'linebuf' if the client explicitly does an# 'unreadline()'.# read the line, make it None if EOF# Look for the first "#" in the line. If none, never# mind. If we find one and it's the first character, or# is not preceded by "\", then it starts a comment --# strip the comment, strip whitespace before it, and# carry on. Otherwise, it's just an escaped "#", so# unescape it (and any other escaped "#"'s that might be# lurking in there) and otherwise leave the line alone.# no "#" -- no comments# It's definitely a comment -- either "#" is the first# character, or it's elsewhere and unescaped.# Have to preserve the trailing newline, because it's# the job of a later step (rstrip_ws) to remove it --# and if rstrip_ws is false, we'd better preserve it!# (NB. this means that if the final line is all comment# and has no trailing newline, we will think that it's# EOF; I think that's OK.)# If all that's left is whitespace, then skip line# *now*, before we try to join it to 'buildup_line' --# that way constructs like# hello \\# # comment that should be ignored# there# result in "hello there".# it's an escaped "#"# did previous line end with a backslash? then accumulate# oops: end of file# careful: pay attention to line number when incrementing it# just an ordinary line, read it as usual# still have to be careful about incrementing the line number!# strip whitespace however the client wants (leading and# trailing, or one or the other, or neither)# blank line (whether we rstrip'ed or not)? skip to next line# if appropriate# well, I guess there's some actual content there: return itb'text_file + +provides the TextFile class, which gives an interface to text files +that (optionally) takes care of stripping comments, ignoring blank +lines, and joining lines with backslashes.'u'text_file + +provides the TextFile class, which gives an interface to text files +that (optionally) takes care of stripping comments, ignoring blank +lines, and joining lines with backslashes.'b'Provides a file-like object that takes care of all the things you + commonly want to do when processing a text file that has some + line-by-line syntax: strip comments (as long as "#" is your + comment character), skip blank lines, join adjacent lines by + escaping the newline (ie. backslash at end of line), strip + leading and/or trailing whitespace. All of these are optional + and independently controllable. + + Provides a 'warn()' method so you can generate warning messages that + report physical line number, even if the logical line in question + spans multiple physical lines. Also provides 'unreadline()' for + implementing line-at-a-time lookahead. + + Constructor is called as: + + TextFile (filename=None, file=None, **options) + + It bombs (RuntimeError) if both 'filename' and 'file' are None; + 'filename' should be a string, and 'file' a file object (or + something that provides 'readline()' and 'close()' methods). It is + recommended that you supply at least 'filename', so that TextFile + can include it in warning messages. If 'file' is not supplied, + TextFile creates its own using 'io.open()'. + + The options are all boolean, and affect the value returned by + 'readline()': + strip_comments [default: true] + strip from "#" to end-of-line, as well as any whitespace + leading up to the "#" -- unless it is escaped by a backslash + lstrip_ws [default: false] + strip leading whitespace from each line before returning it + rstrip_ws [default: true] + strip trailing whitespace (including line terminator!) from + each line before returning it + skip_blanks [default: true} + skip lines that are empty *after* stripping comments and + whitespace. (If both lstrip_ws and rstrip_ws are false, + then some lines may consist of solely whitespace: these will + *not* be skipped, even if 'skip_blanks' is true.) + join_lines [default: false] + if a backslash is the last non-newline character on a line + after stripping comments and whitespace, join the following line + to it to form one "logical line"; if N consecutive lines end + with a backslash, then N+1 physical lines will be joined to + form one logical line. + collapse_join [default: false] + strip leading whitespace from lines that are joined to their + predecessor; only matters if (join_lines and not lstrip_ws) + errors [default: 'strict'] + error handler used to decode the file content + + Note that since 'rstrip_ws' can strip the trailing newline, the + semantics of 'readline()' must differ from those of the builtin file + object's 'readline()' method! In particular, 'readline()' returns + None for end-of-file: an empty string might just be a blank line (or + an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is + not.'u'Provides a file-like object that takes care of all the things you + commonly want to do when processing a text file that has some + line-by-line syntax: strip comments (as long as "#" is your + comment character), skip blank lines, join adjacent lines by + escaping the newline (ie. backslash at end of line), strip + leading and/or trailing whitespace. All of these are optional + and independently controllable. + + Provides a 'warn()' method so you can generate warning messages that + report physical line number, even if the logical line in question + spans multiple physical lines. Also provides 'unreadline()' for + implementing line-at-a-time lookahead. + + Constructor is called as: + + TextFile (filename=None, file=None, **options) + + It bombs (RuntimeError) if both 'filename' and 'file' are None; + 'filename' should be a string, and 'file' a file object (or + something that provides 'readline()' and 'close()' methods). It is + recommended that you supply at least 'filename', so that TextFile + can include it in warning messages. If 'file' is not supplied, + TextFile creates its own using 'io.open()'. + + The options are all boolean, and affect the value returned by + 'readline()': + strip_comments [default: true] + strip from "#" to end-of-line, as well as any whitespace + leading up to the "#" -- unless it is escaped by a backslash + lstrip_ws [default: false] + strip leading whitespace from each line before returning it + rstrip_ws [default: true] + strip trailing whitespace (including line terminator!) from + each line before returning it + skip_blanks [default: true} + skip lines that are empty *after* stripping comments and + whitespace. (If both lstrip_ws and rstrip_ws are false, + then some lines may consist of solely whitespace: these will + *not* be skipped, even if 'skip_blanks' is true.) + join_lines [default: false] + if a backslash is the last non-newline character on a line + after stripping comments and whitespace, join the following line + to it to form one "logical line"; if N consecutive lines end + with a backslash, then N+1 physical lines will be joined to + form one logical line. + collapse_join [default: false] + strip leading whitespace from lines that are joined to their + predecessor; only matters if (join_lines and not lstrip_ws) + errors [default: 'strict'] + error handler used to decode the file content + + Note that since 'rstrip_ws' can strip the trailing newline, the + semantics of 'readline()' must differ from those of the builtin file + object's 'readline()' method! In particular, 'readline()' returns + None for end-of-file: an empty string might just be a blank line (or + an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is + not.'b'strip_comments'u'strip_comments'b'skip_blanks'u'skip_blanks'b'lstrip_ws'u'lstrip_ws'b'rstrip_ws'u'rstrip_ws'b'join_lines'u'join_lines'b'collapse_join'u'collapse_join'b'Construct a new TextFile object. At least one of 'filename' + (a string) and 'file' (a file-like object) must be supplied. + They keyword argument options are described above and affect + the values returned by 'readline()'.'u'Construct a new TextFile object. At least one of 'filename' + (a string) and 'file' (a file-like object) must be supplied. + They keyword argument options are described above and affect + the values returned by 'readline()'.'b'you must supply either or both of 'filename' and 'file''u'you must supply either or both of 'filename' and 'file''b'invalid TextFile option '%s''u'invalid TextFile option '%s''b'Open a new file named 'filename'. This overrides both the + 'filename' and 'file' arguments to the constructor.'u'Open a new file named 'filename'. This overrides both the + 'filename' and 'file' arguments to the constructor.'b'Close the current file and forget everything we know about it + (filename, current line number).'u'Close the current file and forget everything we know about it + (filename, current line number).'b'lines %d-%d: 'u'lines %d-%d: 'b'line %d: 'u'line %d: 'b'error: 'u'error: 'b'Print (to stderr) a warning message tied to the current logical + line in the current file. If the current logical line in the + file spans multiple physical lines, the warning refers to the + whole range, eg. "lines 3-5". If 'line' supplied, it overrides + the current line number; it may be a list or tuple to indicate a + range of physical lines, or an integer for a single physical + line.'u'Print (to stderr) a warning message tied to the current logical + line in the current file. If the current logical line in the + file spans multiple physical lines, the warning refers to the + whole range, eg. "lines 3-5". If 'line' supplied, it overrides + the current line number; it may be a list or tuple to indicate a + range of physical lines, or an integer for a single physical + line.'b'warning: 'u'warning: 'b'Read and return a single logical line from the current file (or + from an internal buffer if lines have previously been "unread" + with 'unreadline()'). If the 'join_lines' option is true, this + may involve reading multiple physical lines concatenated into a + single string. Updates the current line number, so calling + 'warn()' after 'readline()' emits a warning about the physical + line(s) just read. Returns None on end-of-file, since the empty + string can occur if 'rstrip_ws' is true but 'strip_blanks' is + not.'u'Read and return a single logical line from the current file (or + from an internal buffer if lines have previously been "unread" + with 'unreadline()'). If the 'join_lines' option is true, this + may involve reading multiple physical lines concatenated into a + single string. Updates the current line number, so calling + 'warn()' after 'readline()' emits a warning about the physical + line(s) just read. Returns None on end-of-file, since the empty + string can occur if 'rstrip_ws' is true but 'strip_blanks' is + not.'b'\#'u'\#'b'continuation line immediately precedes end-of-file'u'continuation line immediately precedes end-of-file'b'\ +'u'\ +'b'Read and return the list of all logical lines remaining in the + current file.'u'Read and return the list of all logical lines remaining in the + current file.'b'Push 'line' (a string) onto an internal buffer that will be + checked by future 'readline()' calls. Handy for implementing + a parser with line-at-a-time lookahead.'u'Push 'line' (a string) onto an internal buffer that will be + checked by future 'readline()' calls. Handy for implementing + a parser with line-at-a-time lookahead.'u'distutils.text_file'u'text_file'Text wrapping and filling. +TextWrappershorten + _whitespace + Object for wrapping/filling text. The public interface consists of + the wrap() and fill() methods; the other methods are just there for + subclasses to override in order to tweak the default behaviour. + If you want to completely replace the main wrapping algorithm, + you'll probably have to override _wrap_chunks(). + + Several instance attributes control various aspects of wrapping: + width (default: 70) + the maximum width of wrapped lines (unless break_long_words + is false) + initial_indent (default: "") + string that will be prepended to the first line of wrapped + output. Counts towards the line's width. + subsequent_indent (default: "") + string that will be prepended to all lines save the first + of wrapped output; also counts towards each line's width. + expand_tabs (default: true) + Expand tabs in input text to spaces before further processing. + Each tab will become 0 .. 'tabsize' spaces, depending on its position + in its line. If false, each tab is treated as a single character. + tabsize (default: 8) + Expand tabs in input text to 0 .. 'tabsize' spaces, unless + 'expand_tabs' is false. + replace_whitespace (default: true) + Replace all whitespace characters in the input text by spaces + after tab expansion. Note that if expand_tabs is false and + replace_whitespace is true, every tab will be converted to a + single space! + fix_sentence_endings (default: false) + Ensure that sentence-ending punctuation is always followed + by two spaces. Off by default because the algorithm is + (unavoidably) imperfect. + break_long_words (default: true) + Break words longer than 'width'. If false, those words will not + be broken, and some lines might be longer than 'width'. + break_on_hyphens (default: true) + Allow breaking hyphenated words. If true, wrapping will occur + preferably on whitespaces and right after hyphens part of + compound words. + drop_whitespace (default: true) + Drop leading and trailing whitespace from lines. + max_lines (default: None) + Truncate wrapped lines. + placeholder (default: ' [...]') + Append to the last line of truncated text. + unicode_whitespace_transuspace[\w!"\'&.,?]word_punct[^\d\W]letter[^nowhitespace + ( # any whitespace + %(ws)s+ + | # em-dash between words + (?<=%(wp)s) -{2,} (?=\w) + | # word, possibly hyphenated + %(nws)s+? (?: + # hyphenated word + -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-)) + (?= %(lt)s -? %(lt)s) + | # end of word + (?=%(ws)s|\Z) + | # em-dash + (?<=%(wp)s) (?=-{2,}\w) + ) + )wpnwswordsep_re(%s+)wordsep_simple_re[a-z][\.\!\?][\"\']?\Zr'[a-z]'r'[\.\!\?]'r'[\"\']?'r'\Z'sentence_end_rereplace_whitespacefix_sentence_endingsbreak_long_wordsdrop_whitespacebreak_on_hyphensmax_linesplaceholder_munge_whitespace_munge_whitespace(text : string) -> string + + Munge whitespace in text: expand tabs and convert all other + whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" + becomes " foo bar baz". + _split_split(text : string) -> [string] + + Split the text to wrap into indivisible chunks. Chunks are + not quite the same as words; see _wrap_chunks() for full + details. As an example, the text + Look, goof-ball -- use the -b option! + breaks into the following chunks: + 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', + 'use', ' ', 'the', ' ', '-b', ' ', 'option!' + if break_on_hyphens is True, or in: + 'Look,', ' ', 'goof-ball', ' ', '--', ' ', + 'use', ' ', 'the', ' ', '-b', ' ', option!' + otherwise. + _fix_sentence_endings_fix_sentence_endings(chunks : [string]) + + Correct for sentence endings buried in 'chunks'. Eg. when the + original text contains "... foo.\nBar ...", munge_whitespace() + and split() will convert that to [..., "foo.", " ", "Bar", ...] + which has one too few spaces; this method simply changes the one + space to two. + patsearch_handle_long_wordreversed_chunks_handle_long_word(chunks : [string], + cur_line : [string], + cur_len : int, width : int) + + Handle a chunk of text (most likely a word, not whitespace) that + is too long to fit in any line. + space_left_wrap_chunks_wrap_chunks(chunks : [string]) -> [string] + + Wrap a sequence of text chunks and return a list of lines of + length 'self.width' or less. (If 'break_long_words' is false, + some lines may be longer than this.) Chunks correspond roughly + to words and the whitespace between them: each chunk is + indivisible (modulo 'break_long_words'), but a line break can + come between any two chunks. Chunks should not have internal + whitespace; ie. a chunk is either all whitespace or a "word". + Whitespace chunks will be removed from the beginning and end of + lines, but apart from that whitespace is preserved. + invalid width %r (must be > 0)placeholder too large for max widthprev_line_split_chunkswrap(text : string) -> [string] + + Reformat the single paragraph in 'text' so it fits in lines of + no more than 'self.width' columns, and return a list of wrapped + lines. Tabs in 'text' are expanded with string.expandtabs(), + and all other whitespace characters (including newline) are + converted to space. + fill(text : string) -> string + + Reformat the single paragraph in 'text' to fit in lines of no + more than 'self.width' columns, and return a new string + containing the entire wrapped paragraph. + Wrap a single paragraph of text, returning a list of wrapped lines. + + Reformat the single paragraph in 'text' so it fits in lines of no + more than 'width' columns, and return a list of wrapped lines. By + default, tabs in 'text' are expanded with string.expandtabs(), and + all other whitespace characters (including newline) are converted to + space. See TextWrapper class for available keyword args to customize + wrapping behaviour. + Fill a single paragraph of text, returning a new string. + + Reformat the single paragraph in 'text' to fit in lines of no more + than 'width' columns, and return a new string containing the entire + wrapped paragraph. As with wrap(), tabs are expanded and other + whitespace characters converted to space. See TextWrapper class for + available keyword args to customize wrapping behaviour. + Collapse and truncate the given text to fit in the given width. + + The text first has its whitespace collapsed. If it then fits in + the *width*, it is returned as is. Otherwise, as many words + as possible are joined and then the placeholder is appended:: + + >>> textwrap.shorten("Hello world!", width=12) + 'Hello world!' + >>> textwrap.shorten("Hello world!", width=11) + 'Hello [...]' + ^[ ]+$_whitespace_only_re(^[ ]*)(?:[^ +])_leading_whitespace_reRemove any common leading whitespace from every line in `text`. + + This can be used to make triple-quoted strings line up with the left + edge of the display, while still presenting them in the source code + in indented form. + + Note that tabs and spaces are both treated as whitespace, but they + are not equal: the lines " hello" and "\thello" are + considered to have no common leading whitespace. + + Entirely blank lines are normalized to a newline character. + line = %r, margin = %r(?m)^Adds 'prefix' to the beginning of selected lines in 'text'. + + If 'predicate' is provided, 'prefix' will only be added to the lines + where 'predicate(line)' is True. If 'predicate' is not provided, + it will default to adding 'prefix' to all non-empty lines that do not + consist solely of whitespace characters. + prefixed_linesHello there. + This is indented.# Copyright (C) 1999-2001 Gregory P. Ward.# Copyright (C) 2002, 2003 Python Software Foundation.# Written by Greg Ward # Hardcode the recognized whitespace characters to the US-ASCII# whitespace characters. The main reason for doing this is that# some Unicode spaces (like \u00a0) are non-breaking whitespaces.# This funky little regex is just the trick for splitting# text up into word-wrappable chunks. E.g.# "Hello there -- you goof-ball, use the -b option!"# splits into# Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!# (after stripping out empty strings).# This less funky little regex just split on recognized spaces. E.g.# Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/# XXX this is not locale- or charset-aware -- string.lowercase# is US-ASCII only (and therefore English-only)# lowercase letter# sentence-ending punct.# optional end-of-quote# end of chunk# (possibly useful for subclasses to override)# Figure out when indent is larger than the specified width, and make# sure at least one character is stripped off on every pass# If we're allowed to break long words, then do so: put as much# of the next chunk onto the current line as will fit.# Otherwise, we have to preserve the long word intact. Only add# it to the current line if there's nothing already there --# that minimizes how much we violate the width constraint.# If we're not allowed to break long words, and there's already# text on the current line, do nothing. Next time through the# main loop of _wrap_chunks(), we'll wind up here again, but# cur_len will be zero, so the next line will be entirely# devoted to the long word that we can't handle right now.# Arrange in reverse order so items can be efficiently popped# from a stack of chucks.# Start the list of chunks that will make up the current line.# cur_len is just the length of all the chunks in cur_line.# Figure out which static string will prefix this line.# Maximum width for this line.# First chunk on line is whitespace -- drop it, unless this# is the very beginning of the text (ie. no lines started yet).# Can at least squeeze this chunk onto the current line.# Nope, this line is full.# The current line is full, and the next chunk is too big to# fit on *any* line (not just this one).# If the last chunk on this line is all whitespace, drop it.# Convert current line back to a string and store it in# list of all lines (return value).# -- Public interface ----------------------------------------------# -- Convenience interface ---------------------------------------------# -- Loosely related functionality -------------------------------------# Look for the longest leading string of spaces and tabs common to# all lines.# Current line more deeply indented than previous winner:# no change (previous winner is still on top).# Current line consistent with and no deeper than previous winner:# it's the new winner.# Find the largest common whitespace between current line and previous# winner.# sanity check (testing/debugging only)#print dedent("\tfoo\n\tbar")#print dedent(" \thello there\n \t how are you?")b'Text wrapping and filling. +'u'Text wrapping and filling. +'b'TextWrapper'u'TextWrapper'b'wrap'u'wrap'b'dedent'u'dedent'b'shorten'u'shorten'b' + 'u' + 'b' + Object for wrapping/filling text. The public interface consists of + the wrap() and fill() methods; the other methods are just there for + subclasses to override in order to tweak the default behaviour. + If you want to completely replace the main wrapping algorithm, + you'll probably have to override _wrap_chunks(). + + Several instance attributes control various aspects of wrapping: + width (default: 70) + the maximum width of wrapped lines (unless break_long_words + is false) + initial_indent (default: "") + string that will be prepended to the first line of wrapped + output. Counts towards the line's width. + subsequent_indent (default: "") + string that will be prepended to all lines save the first + of wrapped output; also counts towards each line's width. + expand_tabs (default: true) + Expand tabs in input text to spaces before further processing. + Each tab will become 0 .. 'tabsize' spaces, depending on its position + in its line. If false, each tab is treated as a single character. + tabsize (default: 8) + Expand tabs in input text to 0 .. 'tabsize' spaces, unless + 'expand_tabs' is false. + replace_whitespace (default: true) + Replace all whitespace characters in the input text by spaces + after tab expansion. Note that if expand_tabs is false and + replace_whitespace is true, every tab will be converted to a + single space! + fix_sentence_endings (default: false) + Ensure that sentence-ending punctuation is always followed + by two spaces. Off by default because the algorithm is + (unavoidably) imperfect. + break_long_words (default: true) + Break words longer than 'width'. If false, those words will not + be broken, and some lines might be longer than 'width'. + break_on_hyphens (default: true) + Allow breaking hyphenated words. If true, wrapping will occur + preferably on whitespaces and right after hyphens part of + compound words. + drop_whitespace (default: true) + Drop leading and trailing whitespace from lines. + max_lines (default: None) + Truncate wrapped lines. + placeholder (default: ' [...]') + Append to the last line of truncated text. + 'u' + Object for wrapping/filling text. The public interface consists of + the wrap() and fill() methods; the other methods are just there for + subclasses to override in order to tweak the default behaviour. + If you want to completely replace the main wrapping algorithm, + you'll probably have to override _wrap_chunks(). + + Several instance attributes control various aspects of wrapping: + width (default: 70) + the maximum width of wrapped lines (unless break_long_words + is false) + initial_indent (default: "") + string that will be prepended to the first line of wrapped + output. Counts towards the line's width. + subsequent_indent (default: "") + string that will be prepended to all lines save the first + of wrapped output; also counts towards each line's width. + expand_tabs (default: true) + Expand tabs in input text to spaces before further processing. + Each tab will become 0 .. 'tabsize' spaces, depending on its position + in its line. If false, each tab is treated as a single character. + tabsize (default: 8) + Expand tabs in input text to 0 .. 'tabsize' spaces, unless + 'expand_tabs' is false. + replace_whitespace (default: true) + Replace all whitespace characters in the input text by spaces + after tab expansion. Note that if expand_tabs is false and + replace_whitespace is true, every tab will be converted to a + single space! + fix_sentence_endings (default: false) + Ensure that sentence-ending punctuation is always followed + by two spaces. Off by default because the algorithm is + (unavoidably) imperfect. + break_long_words (default: true) + Break words longer than 'width'. If false, those words will not + be broken, and some lines might be longer than 'width'. + break_on_hyphens (default: true) + Allow breaking hyphenated words. If true, wrapping will occur + preferably on whitespaces and right after hyphens part of + compound words. + drop_whitespace (default: true) + Drop leading and trailing whitespace from lines. + max_lines (default: None) + Truncate wrapped lines. + placeholder (default: ' [...]') + Append to the last line of truncated text. + 'b'[\w!"\'&.,?]'u'[\w!"\'&.,?]'b'[^\d\W]'u'[^\d\W]'b'[^'u'[^'b' + ( # any whitespace + %(ws)s+ + | # em-dash between words + (?<=%(wp)s) -{2,} (?=\w) + | # word, possibly hyphenated + %(nws)s+? (?: + # hyphenated word + -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-)) + (?= %(lt)s -? %(lt)s) + | # end of word + (?=%(ws)s|\Z) + | # em-dash + (?<=%(wp)s) (?=-{2,}\w) + ) + )'u' + ( # any whitespace + %(ws)s+ + | # em-dash between words + (?<=%(wp)s) -{2,} (?=\w) + | # word, possibly hyphenated + %(nws)s+? (?: + # hyphenated word + -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-)) + (?= %(lt)s -? %(lt)s) + | # end of word + (?=%(ws)s|\Z) + | # em-dash + (?<=%(wp)s) (?=-{2,}\w) + ) + )'b'wp'u'wp'b'nws'u'nws'b'(%s+)'u'(%s+)'b'[a-z][\.\!\?][\"\']?\Z'u'[a-z][\.\!\?][\"\']?\Z'b'_munge_whitespace(text : string) -> string + + Munge whitespace in text: expand tabs and convert all other + whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" + becomes " foo bar baz". + 'u'_munge_whitespace(text : string) -> string + + Munge whitespace in text: expand tabs and convert all other + whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" + becomes " foo bar baz". + 'b'_split(text : string) -> [string] + + Split the text to wrap into indivisible chunks. Chunks are + not quite the same as words; see _wrap_chunks() for full + details. As an example, the text + Look, goof-ball -- use the -b option! + breaks into the following chunks: + 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', + 'use', ' ', 'the', ' ', '-b', ' ', 'option!' + if break_on_hyphens is True, or in: + 'Look,', ' ', 'goof-ball', ' ', '--', ' ', + 'use', ' ', 'the', ' ', '-b', ' ', option!' + otherwise. + 'u'_split(text : string) -> [string] + + Split the text to wrap into indivisible chunks. Chunks are + not quite the same as words; see _wrap_chunks() for full + details. As an example, the text + Look, goof-ball -- use the -b option! + breaks into the following chunks: + 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', + 'use', ' ', 'the', ' ', '-b', ' ', 'option!' + if break_on_hyphens is True, or in: + 'Look,', ' ', 'goof-ball', ' ', '--', ' ', + 'use', ' ', 'the', ' ', '-b', ' ', option!' + otherwise. + 'b'_fix_sentence_endings(chunks : [string]) + + Correct for sentence endings buried in 'chunks'. Eg. when the + original text contains "... foo.\nBar ...", munge_whitespace() + and split() will convert that to [..., "foo.", " ", "Bar", ...] + which has one too few spaces; this method simply changes the one + space to two. + 'u'_fix_sentence_endings(chunks : [string]) + + Correct for sentence endings buried in 'chunks'. Eg. when the + original text contains "... foo.\nBar ...", munge_whitespace() + and split() will convert that to [..., "foo.", " ", "Bar", ...] + which has one too few spaces; this method simply changes the one + space to two. + 'b'_handle_long_word(chunks : [string], + cur_line : [string], + cur_len : int, width : int) + + Handle a chunk of text (most likely a word, not whitespace) that + is too long to fit in any line. + 'u'_handle_long_word(chunks : [string], + cur_line : [string], + cur_len : int, width : int) + + Handle a chunk of text (most likely a word, not whitespace) that + is too long to fit in any line. + 'b'_wrap_chunks(chunks : [string]) -> [string] + + Wrap a sequence of text chunks and return a list of lines of + length 'self.width' or less. (If 'break_long_words' is false, + some lines may be longer than this.) Chunks correspond roughly + to words and the whitespace between them: each chunk is + indivisible (modulo 'break_long_words'), but a line break can + come between any two chunks. Chunks should not have internal + whitespace; ie. a chunk is either all whitespace or a "word". + Whitespace chunks will be removed from the beginning and end of + lines, but apart from that whitespace is preserved. + 'u'_wrap_chunks(chunks : [string]) -> [string] + + Wrap a sequence of text chunks and return a list of lines of + length 'self.width' or less. (If 'break_long_words' is false, + some lines may be longer than this.) Chunks correspond roughly + to words and the whitespace between them: each chunk is + indivisible (modulo 'break_long_words'), but a line break can + come between any two chunks. Chunks should not have internal + whitespace; ie. a chunk is either all whitespace or a "word". + Whitespace chunks will be removed from the beginning and end of + lines, but apart from that whitespace is preserved. + 'b'invalid width %r (must be > 0)'u'invalid width %r (must be > 0)'b'placeholder too large for max width'u'placeholder too large for max width'b'wrap(text : string) -> [string] + + Reformat the single paragraph in 'text' so it fits in lines of + no more than 'self.width' columns, and return a list of wrapped + lines. Tabs in 'text' are expanded with string.expandtabs(), + and all other whitespace characters (including newline) are + converted to space. + 'u'wrap(text : string) -> [string] + + Reformat the single paragraph in 'text' so it fits in lines of + no more than 'self.width' columns, and return a list of wrapped + lines. Tabs in 'text' are expanded with string.expandtabs(), + and all other whitespace characters (including newline) are + converted to space. + 'b'fill(text : string) -> string + + Reformat the single paragraph in 'text' to fit in lines of no + more than 'self.width' columns, and return a new string + containing the entire wrapped paragraph. + 'u'fill(text : string) -> string + + Reformat the single paragraph in 'text' to fit in lines of no + more than 'self.width' columns, and return a new string + containing the entire wrapped paragraph. + 'b'Wrap a single paragraph of text, returning a list of wrapped lines. + + Reformat the single paragraph in 'text' so it fits in lines of no + more than 'width' columns, and return a list of wrapped lines. By + default, tabs in 'text' are expanded with string.expandtabs(), and + all other whitespace characters (including newline) are converted to + space. See TextWrapper class for available keyword args to customize + wrapping behaviour. + 'u'Wrap a single paragraph of text, returning a list of wrapped lines. + + Reformat the single paragraph in 'text' so it fits in lines of no + more than 'width' columns, and return a list of wrapped lines. By + default, tabs in 'text' are expanded with string.expandtabs(), and + all other whitespace characters (including newline) are converted to + space. See TextWrapper class for available keyword args to customize + wrapping behaviour. + 'b'Fill a single paragraph of text, returning a new string. + + Reformat the single paragraph in 'text' to fit in lines of no more + than 'width' columns, and return a new string containing the entire + wrapped paragraph. As with wrap(), tabs are expanded and other + whitespace characters converted to space. See TextWrapper class for + available keyword args to customize wrapping behaviour. + 'u'Fill a single paragraph of text, returning a new string. + + Reformat the single paragraph in 'text' to fit in lines of no more + than 'width' columns, and return a new string containing the entire + wrapped paragraph. As with wrap(), tabs are expanded and other + whitespace characters converted to space. See TextWrapper class for + available keyword args to customize wrapping behaviour. + 'b'Collapse and truncate the given text to fit in the given width. + + The text first has its whitespace collapsed. If it then fits in + the *width*, it is returned as is. Otherwise, as many words + as possible are joined and then the placeholder is appended:: + + >>> textwrap.shorten("Hello world!", width=12) + 'Hello world!' + >>> textwrap.shorten("Hello world!", width=11) + 'Hello [...]' + 'u'Collapse and truncate the given text to fit in the given width. + + The text first has its whitespace collapsed. If it then fits in + the *width*, it is returned as is. Otherwise, as many words + as possible are joined and then the placeholder is appended:: + + >>> textwrap.shorten("Hello world!", width=12) + 'Hello world!' + >>> textwrap.shorten("Hello world!", width=11) + 'Hello [...]' + 'b'^[ ]+$'u'^[ ]+$'b'(^[ ]*)(?:[^ +])'u'(^[ ]*)(?:[^ +])'b'Remove any common leading whitespace from every line in `text`. + + This can be used to make triple-quoted strings line up with the left + edge of the display, while still presenting them in the source code + in indented form. + + Note that tabs and spaces are both treated as whitespace, but they + are not equal: the lines " hello" and "\thello" are + considered to have no common leading whitespace. + + Entirely blank lines are normalized to a newline character. + 'u'Remove any common leading whitespace from every line in `text`. + + This can be used to make triple-quoted strings line up with the left + edge of the display, while still presenting them in the source code + in indented form. + + Note that tabs and spaces are both treated as whitespace, but they + are not equal: the lines " hello" and "\thello" are + considered to have no common leading whitespace. + + Entirely blank lines are normalized to a newline character. + 'b'line = %r, margin = %r'u'line = %r, margin = %r'b'(?m)^'u'(?m)^'b'Adds 'prefix' to the beginning of selected lines in 'text'. + + If 'predicate' is provided, 'prefix' will only be added to the lines + where 'predicate(line)' is True. If 'predicate' is not provided, + it will default to adding 'prefix' to all non-empty lines that do not + consist solely of whitespace characters. + 'u'Adds 'prefix' to the beginning of selected lines in 'text'. + + If 'predicate' is provided, 'prefix' will only be added to the lines + where 'predicate(line)' is True. If 'predicate' is not provided, + it will default to adding 'prefix' to all non-empty lines that do not + consist solely of whitespace characters. + 'b'Hello there. + This is indented.'u'Hello there. + This is indented.'u'textwrap'Implements ThreadPoolExecutor._threads_queues_workerwork_queue_initializer_failed_idle_semaphoreException in workerBrokenThreadPool + Raised when a worker thread in a ThreadPoolExecutor failed initializing. + _counterthread_name_prefixInitializes a new ThreadPoolExecutor instance. + + Args: + max_workers: The maximum number of threads that can be used to + execute the given calls. + thread_name_prefix: An optional name prefix to give our threads. + initializer: A callable used to initialize worker threads. + initargs: A tuple of arguments to pass to the initializer. + _work_queueThreadPoolExecutor-%d_thread_name_prefixdescriptor 'submit' of 'ThreadPoolExecutor' object needs an argument"descriptor 'submit' of 'ThreadPoolExecutor' object "_adjust_thread_countnum_threads%s_%dthread_nameA thread initializer failed, the thread pool is not usable anymore'A thread initializer failed, the thread pool ''is not usable anymore'# Workers are created as daemon threads. This is done to allow the interpreter# to exit when there are still idle threads in a ThreadPoolExecutor's thread# pool (i.e. shutdown() was not called). However, allowing workers to die with# the interpreter has two undesirable properties:# threads finish.# Break a reference cycle with the exception 'exc'# attempt to increment idle count# Exit if:# - The executor that owns the worker has been collected OR# - The executor that owns the worker has been shutdown.# Notice other workers# Used to assign unique thread names when thread_name_prefix is not supplied.# ThreadPoolExecutor is often used to:# * CPU bound task which releases GIL# * I/O bound task (which releases GIL, of course)# We use cpu_count + 4 for both types of tasks.# But we limit it to 32 to avoid consuming surprisingly large resource# on many core machine.# if idle threads are available, don't spin new threads# When the executor gets lost, the weakref callback will wake up# the worker threads.# Drain work queue and mark pending futures failedb'Implements ThreadPoolExecutor.'u'Implements ThreadPoolExecutor.'b'Exception in worker'u'Exception in worker'b' + Raised when a worker thread in a ThreadPoolExecutor failed initializing. + 'u' + Raised when a worker thread in a ThreadPoolExecutor failed initializing. + 'b'Initializes a new ThreadPoolExecutor instance. + + Args: + max_workers: The maximum number of threads that can be used to + execute the given calls. + thread_name_prefix: An optional name prefix to give our threads. + initializer: A callable used to initialize worker threads. + initargs: A tuple of arguments to pass to the initializer. + 'u'Initializes a new ThreadPoolExecutor instance. + + Args: + max_workers: The maximum number of threads that can be used to + execute the given calls. + thread_name_prefix: An optional name prefix to give our threads. + initializer: A callable used to initialize worker threads. + initargs: A tuple of arguments to pass to the initializer. + 'b'ThreadPoolExecutor-%d'u'ThreadPoolExecutor-%d'b'descriptor 'submit' of 'ThreadPoolExecutor' object needs an argument'u'descriptor 'submit' of 'ThreadPoolExecutor' object needs an argument'b'%s_%d'u'%s_%d'b'A thread initializer failed, the thread pool is not usable anymore'u'A thread initializer failed, the thread pool is not usable anymore'u'concurrent.futures.thread'u'futures.thread'Thread module emulating a subset of Java's threading model._islice_dequeactive_countBrokenBarrierErrorTimerThreadErrorExceptHookArgs_start_new_thread_CRLock_profile_hook_trace_hookSet a profile function for all threads started from the threading module. + + The func will be passed to sys.setprofile() for each thread, before its + run() method is called. + + Set a trace function for all threads started from the threading module. + + The func will be passed to sys.settrace() for each thread, before its run() + method is called. + + Factory function that returns a new reentrant lock. + + A reentrant lock must be released by the thread that acquired it. Once a + thread has acquired a reentrant lock, the same thread may acquire it again + without blocking; the thread must release it once for each time it has + acquired it. + + _PyRLock_RLockThis class implements reentrant lock objects. + + A reentrant lock must be released by the thread that acquired it. Once a + thread has acquired a reentrant lock, the same thread may acquire it + again without blocking; the thread must release it once for each time it + has acquired it. + + _owner<%s %s.%s object owner=%r count=%d at %s>Acquire a lock, blocking or non-blocking. + + When invoked without arguments: if this thread already owns the lock, + increment the recursion level by one, and return immediately. Otherwise, + if another thread owns the lock, block until the lock is unlocked. Once + the lock is unlocked (not owned by any thread), then grab ownership, set + the recursion level to one, and return. If more than one thread is + blocked waiting until the lock is unlocked, only one at a time will be + able to grab ownership of the lock. There is no return value in this + case. + + When invoked with the blocking argument set to true, do the same thing + as when called without arguments, and return true. + + When invoked with the blocking argument set to false, do not block. If a + call without an argument would block, return false immediately; + otherwise, do the same thing as when called without arguments, and + return true. + + When invoked with the floating-point timeout argument set to a positive + value, block for at most the number of seconds specified by timeout + and as long as the lock cannot be acquired. Return true if the lock has + been acquired, false if the timeout has elapsed. + + Release a lock, decrementing the recursion level. + + If after the decrement it is zero, reset the lock to unlocked (not owned + by any thread), and if any other threads are blocked waiting for the + lock to become unlocked, allow exactly one of them to proceed. If after + the decrement the recursion level is still nonzero, the lock remains + locked and owned by the calling thread. + + Only call this method when the calling thread owns the lock. A + RuntimeError is raised if this method is called when the lock is + unlocked. + + There is no return value. + + Class that implements a condition variable. + + A condition variable allows one or more threads to wait until they are + notified by another thread. + + If the lock argument is given and not None, it must be a Lock or RLock + object, and it is used as the underlying lock. Otherwise, a new RLock object + is created and used as the underlying lock. + + Wait until notified or until a timeout occurs. + + If the calling thread has not acquired the lock when this method is + called, a RuntimeError is raised. + + This method releases the underlying lock, and then blocks until it is + awakened by a notify() or notify_all() call for the same condition + variable in another thread, or until the optional timeout occurs. Once + awakened or timed out, it re-acquires the lock and returns. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + When the underlying lock is an RLock, it is not released using its + release() method, since this may not actually unlock the lock when it + was acquired multiple times recursively. Instead, an internal interface + of the RLock class is used, which really unlocks it even when it has + been recursively acquired several times. Another internal interface is + then used to restore the recursion level when the lock is reacquired. + + saved_stategotitWait until a condition evaluates to True. + + predicate should be a callable which result will be interpreted as a + boolean value. A timeout may be provided giving the maximum time to + wait. + + waittimeWake up one or more threads waiting on this condition, if any. + + If the calling thread has not acquired the lock when this method is + called, a RuntimeError is raised. + + This method wakes up at most n of the threads waiting for the condition + variable; it is a no-op if no threads are waiting. + + all_waiterswaiters_to_notifyWake up all threads waiting on this condition. + + If the calling thread has not acquired the lock when this method + is called, a RuntimeError is raised. + + notifyAllThis class implements semaphore objects. + + Semaphores manage a counter representing the number of release() calls minus + the number of acquire() calls, plus an initial value. The acquire() method + blocks if necessary until it can return without making the counter + negative. If not given, value defaults to 1. + + semaphore initial value must be >= 0Acquire a semaphore, decrementing the internal counter by one. + + When invoked without arguments: if the internal counter is larger than + zero on entry, decrement it by one and return immediately. If it is zero + on entry, block, waiting until some other thread has called release() to + make it larger than zero. This is done with proper interlocking so that + if multiple acquire() calls are blocked, release() will wake exactly one + of them up. The implementation may pick one at random, so the order in + which blocked threads are awakened should not be relied on. There is no + return value in this case. + + When invoked with blocking set to true, do the same thing as when called + without arguments, and return true. + + When invoked with blocking set to false, do not block. If a call without + an argument would block, return false immediately; otherwise, do the + same thing as when called without arguments, and return true. + + When invoked with a timeout other than None, it will block for at + most timeout seconds. If acquire does not complete successfully in + that interval, return false. Return true otherwise. + + can't specify timeout for non-blocking acquireRelease a semaphore, incrementing the internal counter by one. + + When the counter is zero on entry and another thread is waiting for it + to become larger than zero again, wake up that thread. + + Implements a bounded semaphore. + + A bounded semaphore checks to make sure its current value doesn't exceed its + initial value. If it does, ValueError is raised. In most situations + semaphores are used to guard resources with limited capacity. + + If the semaphore is released too many times it's a sign of a bug. If not + given, value defaults to 1. + + Like regular semaphores, bounded semaphores manage a counter representing + the number of release() calls minus the number of acquire() calls, plus an + initial value. The acquire() method blocks if necessary until it can return + without making the counter negative. If not given, value defaults to 1. + + _initial_valueRelease a semaphore, incrementing the internal counter by one. + + When the counter is zero on entry and another thread is waiting for it + to become larger than zero again, wake up that thread. + + If the number of releases exceeds the number of acquires, + raise a ValueError. + + Semaphore released too many timesClass implementing event objects. + + Events manage a flag that can be set to true with the set() method and reset + to false with the clear() method. The wait() method blocks until the flag is + true. The flag is initially false. + + _flag_reset_internal_locksReturn true if and only if the internal flag is true.isSetSet the internal flag to true. + + All threads waiting for it to become true are awakened. Threads + that call wait() once the flag is true will not block at all. + + Reset the internal flag to false. + + Subsequently, threads calling wait() will block until set() is called to + set the internal flag to true again. + + Block until the internal flag is true. + + If the internal flag is true on entry, return immediately. Otherwise, + block until another thread calls set() to set the flag to true, or until + the optional timeout occurs. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + This method returns the internal flag on exit, so it will always return + True except if a timeout is given and the operation times out. + + signaledImplements a Barrier. + + Useful for synchronizing a fixed number of threads at known synchronization + points. Threads block on 'wait()' and are simultaneously awoken once they + have all made that call. + + Create a barrier, initialised to 'parties' threads. + + 'action' is a callable which, when supplied, will be called by one of + the threads after they have all entered the barrier and just prior to + releasing them all. If a 'timeout' is provided, it is used as the + default for all subsequent 'wait()' calls. + + _action_timeout_partiesWait for the barrier. + + When the specified number of threads have started waiting, they are all + simultaneously awoken. If an 'action' was provided for the barrier, one + of the threads will have executed that callback prior to returning. + Returns an individual index number from 0 to 'parties-1'. + + _enter_release_breakReset the barrier to the initial state. + + Any threads currently waiting will get the BrokenBarrier exception + raised. + + Place the barrier into a 'broken' state. + + Useful in case of error. Any currently waiting threads and threads + attempting to 'wait()' will have BrokenBarrierError raised. + + Return the number of threads required to trip the barrier.n_waitingReturn the number of threads currently waiting at the barrier.brokenReturn True if the barrier is in a broken state._newnameThread-%d_active_limbo_lock_limbo_shutdown_locks_lock_shutdown_locksA class that represents a thread of control. + + This class can be safely subclassed in a limited fashion. There are two ways + to specify the activity: by passing a callable object to the constructor, or + by overriding the run() method in a subclass. + + _initializedThis constructor should always be called with keyword arguments. Arguments are: + + *group* should be None; reserved for future extension when a ThreadGroup + class is implemented. + + *target* is the callable object to be invoked by the run() + method. Defaults to None, meaning nothing is called. + + *name* is the thread name. By default, a unique name is constructed of + the form "Thread-N" where N is a small decimal number. + + *args* is the argument tuple for the target invocation. Defaults to (). + + *kwargs* is a dictionary of keyword arguments for the target + invocation. Defaults to {}. + + If a subclass overrides the constructor, it must make sure to invoke + the base class constructor (Thread.__init__()) before doing anything + else to the thread. + + _daemonic_ident_native_id_tstate_lock_started_is_stopped_stderr_make_invoke_excepthook_invoke_excepthook_set_tstate_lockThread.__init__() was not called daemon %s<%s(%s, %s)>Start the thread's activity. + + It must be called at most once per thread object. It arranges for the + object's run() method to be invoked in a separate thread of control. + + This method will raise a RuntimeError if called more than once on the + same thread object. + + thread.__init__() not calledthreads can only be started onceMethod representing the thread's activity. + + You may override this method in a subclass. The standard run() method + invokes the callable object passed to the object's constructor as the + target argument, if any, with sequential and keyword arguments taken + from the args and kwargs arguments, respectively. + + _bootstrap_inner_set_ident + Set a lock object which will be released by the interpreter when + the underlying thread state (see pystate.h) gets deleted. + _deleteRemove current thread from the dict of currently running threads.Wait until the thread terminates. + + This blocks the calling thread until the thread whose join() method is + called terminates -- either normally or through an unhandled exception + or until the optional timeout occurs. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). As join() always returns None, you must call + is_alive() after join() to decide whether a timeout happened -- if the + thread is still alive, the join() call timed out. + + When the timeout argument is not present or None, the operation will + block until the thread terminates. + + A thread can be join()ed many times. + + join() raises a RuntimeError if an attempt is made to join the current + thread as that would cause a deadlock. It is also an error to join() a + thread before it has been started and attempts to do so raises the same + exception. + + Thread.__init__() not calledcannot join thread before it is startedcannot join current thread_wait_for_tstate_lockA string used for identification purposes only. + + It has no semantics. Multiple threads may be given the same name. The + initial name is set by the constructor. + + Thread identifier of this thread or None if it has not been started. + + This is a nonzero integer. See the get_ident() function. Thread + identifiers may be recycled when a thread exits and another thread is + created. The identifier is available even after the thread has exited. + + native_idNative integral thread ID of this thread, or None if it has not been started. + + This is a non-negative integer. See the get_native_id() function. + This represents the Thread ID as reported by the kernel. + + Return whether the thread is alive. + + This method returns True just before the run() method starts until just + after the run() method terminates. The module function enumerate() + returns a list of all alive threads. + + isAliveReturn whether the thread is alive. + + This method is deprecated, use is_alive() instead. + isAlive() is deprecated, use is_alive() insteadA boolean value indicating whether this thread is a daemon thread. + + This must be set before start() is called, otherwise RuntimeError is + raised. Its initial value is inherited from the creating thread; the + main thread is not a daemon thread and therefore all threads created in + the main thread default to daemon = False. + + The entire Python program exits when only daemon threads are left. + + cannot set daemon status of active threadisDaemonsetDaemongetNamesetName_print_exceptionexc_type exc_value exc_traceback thread + Handle uncaught Thread.run() exception. + Exception in thread old_excepthookold_sys_excepthookthreading.excepthook is Nonesys.excepthook is Nonesys_exc_infolocal_printlocal_sysinvoke_excepthookException in threading.excepthook:sys_excepthookCall a function after a specified number of seconds: + + t = Timer(30.0, f, args=None, kwargs=None) + t.start() + t.cancel() # stop the timer's action if it's still waiting + + Stop the timer if it hasn't finished yet.MainThread_DummyThreadDummy-%dcannot join a dummy threadReturn the current Thread object, corresponding to the caller's thread of control. + + If the caller's thread of control was not created through the threading + module, a dummy thread object with limited functionality is returned. + + currentThreadReturn the number of Thread objects currently alive. + + The returned count is equal to the length of the list returned by + enumerate(). + + activeCount_enumerateReturn a list of all Thread objects currently alive. + + The list includes daemonic threads, dummy thread objects created by + current_thread(), and the main thread. It excludes terminated threads and + threads that have not yet been started. + + _main_thread + Wait until the Python thread state of all non-daemon threads get deleted. + tlockReturn the main thread object. + + In normal conditions, the main thread is the thread from which the + Python interpreter was started. + _threading_local + Cleanup threading module state that should not exist after a fork. + new_active# Note regarding PEP 8 compliant names# This threading model was originally inspired by Java, and inherited# the convention of camelCase function and method names from that# language. Those original names are not in any imminent danger of# being deprecated (even for Py3k),so this module provides them as an# alias for the PEP 8 compliant names# Note that using the new PEP 8 compliant names facilitates substitution# with the multiprocessing module, which doesn't provide the old# Java inspired names.# Rename some stuff so "from threading import *" is safe# Support for profile and trace hooks# Synchronization classes# Internal methods used by condition variables# Export the lock's acquire() and release() methods# If the lock defines _release_save() and/or _acquire_restore(),# these override the default implementations (which just call# release() and acquire() on the lock). Ditto for _is_owned().# No state to save# Ignore saved state# Return True if lock is owned by current_thread.# This method is called only if _lock doesn't have _is_owned().# restore state no matter what (e.g., KeyboardInterrupt)# After Tim Peters' semaphore class, but not quite the same (no maximum)# After Tim Peters' event class (without is_posted())# private! called by Thread._reset_internal_locks by _after_fork()# A barrier class. Inspired in part by the pthread_barrier_* api and# the CyclicBarrier class from Java. See# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/# CyclicBarrier.html# for information.# We maintain two main states, 'filling' and 'draining' enabling the barrier# to be cyclic. Threads are not allowed into it until it has fully drained# since the previous cycle. In addition, a 'resetting' state exists which is# similar to 'draining' except that threads leave with a BrokenBarrierError,# and a 'broken' state in which all threads get the exception.#0 filling, 1, draining, -1 resetting, -2 broken# Block while the barrier drains.# We release the barrier# We wait until someone releases us# Wake up any threads waiting for barrier to drain.# Block until the barrier is ready for us, or raise an exception# if it is broken.# It is draining or resetting, wait until done#see if the barrier is in a broken state# Optionally run the 'action' and release the threads waiting# in the barrier.# enter draining state#an exception during the _action handler. Break and reraise# Wait in the barrier until we are released. Raise an exception# if the barrier is reset or broken.#timed out. Break the barrier# If we are the last thread to exit the barrier, signal any threads# waiting for the barrier to drain.#resetting or draining#reset the barrier, waking up threads#was broken, set it to reset state#which clears when the last thread exits# An internal error was detected. The barrier is set to# a broken state all parties awakened.# We don't need synchronization here since this is an ephemeral result# anyway. It returns the correct value in the steady state.# exception raised by the Barrier class# Helper to generate new thread names# Consume 0 so first non-main thread has id 1.# Active thread administration# maps thread id to Thread object# Set of Thread._tstate_lock locks of non-daemon threads used by _shutdown()# to wait until all Python thread states get deleted:# see Thread._set_tstate_lock().# Main class for threads# Copy of sys.stderr used by self._invoke_excepthook()# For debugging and _after_fork()# private! Called by _after_fork() to reset our internal locks as# they may be in an invalid state leading to a deadlock or crash.# The thread isn't alive after fork: it doesn't have a tstate# anymore.# easy way to get ._is_stopped set when appropriate# Avoid a refcycle if the thread is running a function with# an argument that has a member that points to the thread.# Wrapper around the real bootstrap code that ignores# exceptions during interpreter cleanup. Those typically# happen when a daemon thread wakes up at an unfortunate# moment, finds the world around it destroyed, and raises some# random exception *** while trying to report the exception in# _bootstrap_inner() below ***. Those random exceptions# don't help anybody, and they confuse users, so we suppress# them. We suppress them only when it appears that the world# indeed has already been destroyed, so that exceptions in# _bootstrap_inner() during normal business hours are properly# reported. Also, we only suppress them for daemonic threads;# if a non-daemonic encounters this, something else is wrong.# We don't call self._delete() because it also# grabs _active_limbo_lock.# After calling ._stop(), .is_alive() returns False and .join() returns# immediately. ._tstate_lock must be released before calling ._stop().# Normal case: C code at the end of the thread's life# (release_sentinel in _threadmodule.c) releases ._tstate_lock, and# that's detected by our ._wait_for_tstate_lock(), called by .join()# and .is_alive(). Any number of threads _may_ call ._stop()# simultaneously (for example, if multiple threads are blocked in# .join() calls), and they're not serialized. That's harmless -# they'll just make redundant rebindings of ._is_stopped and# ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the# "assert self._is_stopped" in ._wait_for_tstate_lock() always works# (the assert is executed only if ._tstate_lock is None).# Special case: _main_thread releases ._tstate_lock via this# module's _shutdown() function.# There must not be any python code between the previous line# and after the lock is released. Otherwise a tracing function# could try to acquire the lock again in the same thread, (in# current_thread()), and would block.# the behavior of a negative timeout isn't documented, but# historically .join(timeout=x) for x<0 has acted as if timeout=0# Issue #18808: wait for the thread state to be gone.# At the end of the thread's life, after all knowledge of the thread# is removed from C data structures, C code releases our _tstate_lock.# This method passes its arguments to _tstate_lock.acquire().# If the lock is acquired, the C code is done, and self._stop() is# called. That sets ._is_stopped to True, and ._tstate_lock to None.# already determined that the C code is done# Simple Python implementation if _thread._excepthook() is not available# silently ignore SystemExit# do nothing if sys.stderr is None and sys.stderr was None# when the thread was created# do nothing if sys.stderr is None and args.thread is None# Create a local namespace to ensure that variables remain alive# when _invoke_excepthook() is called, even if it is called late during# Python shutdown. It is mostly needed for daemon threads.# Break reference cycle (exception stored in a variable)# The timer class was contributed by Itamar Shtull-Trauring# Special thread class to represent the main thread# Dummy thread class to represent threads not started here.# These aren't garbage collected when they die, nor can they be waited for.# If they invoke anything in threading.py that calls current_thread(), they# leave an entry in the _active dict forever after.# Their purpose is to return *something* from current_thread().# They are marked as daemon threads so we won't wait for them# when we exit (conform previous semantics).# Global API functions# Same as enumerate(), but without the lock. Internal use only.# Create the main thread object,# and make it available for the interpreter# (Py_Main) as threading._shutdown.# Obscure: other threads may be waiting to join _main_thread. That's# dubious, but some code does it. We can't wait for C code to release# the main thread's tstate_lock - that won't happen until the interpreter# is nearly dead. So we release it here. Note that just calling _stop()# isn't enough: other threads may already be waiting on _tstate_lock.# _shutdown() was already called# Main thread# The main thread isn't finished yet, so its thread state lock can't have# been released.# Join all non-deamon threads# mimick Thread.join()# new threads can be spawned while we were waiting for the other# threads to complete# get thread-local implementation, either from the thread# module, or from the python fallback# Reset _active_limbo_lock, in case we forked while the lock was held# by another (non-forked) thread. http://bugs.python.org/issue874900# fork() only copied the current thread; clear references to others.# fork() was called in a thread which was not spawned# by threading.Thread. For example, a thread spawned# by thread.start_new_thread().# reset _shutdown() locks: threads re-register their _tstate_lock below# Dangling thread instances must still have their locks reset,# because someone may join() them.# Any lock/condition variable may be currently locked or in an# invalid state, so we reinitialize them.# There is only one active thread. We reset the ident to# its new value since it can have changed.# All the others are already stopped.b'Thread module emulating a subset of Java's threading model.'u'Thread module emulating a subset of Java's threading model.'b'get_ident'u'get_ident'b'active_count'u'active_count'b'current_thread'u'current_thread'b'main_thread'u'main_thread'b'TIMEOUT_MAX'u'TIMEOUT_MAX'b'RLock'u'RLock'b'Thread'u'Thread'b'Barrier'u'Barrier'b'BrokenBarrierError'u'BrokenBarrierError'b'Timer'u'Timer'b'ThreadError'u'ThreadError'b'setprofile'u'setprofile'b'settrace'u'settrace'b'stack_size'u'stack_size'b'excepthook'u'excepthook'b'ExceptHookArgs'u'ExceptHookArgs'b'get_native_id'u'get_native_id'b'Set a profile function for all threads started from the threading module. + + The func will be passed to sys.setprofile() for each thread, before its + run() method is called. + + 'u'Set a profile function for all threads started from the threading module. + + The func will be passed to sys.setprofile() for each thread, before its + run() method is called. + + 'b'Set a trace function for all threads started from the threading module. + + The func will be passed to sys.settrace() for each thread, before its run() + method is called. + + 'u'Set a trace function for all threads started from the threading module. + + The func will be passed to sys.settrace() for each thread, before its run() + method is called. + + 'b'Factory function that returns a new reentrant lock. + + A reentrant lock must be released by the thread that acquired it. Once a + thread has acquired a reentrant lock, the same thread may acquire it again + without blocking; the thread must release it once for each time it has + acquired it. + + 'u'Factory function that returns a new reentrant lock. + + A reentrant lock must be released by the thread that acquired it. Once a + thread has acquired a reentrant lock, the same thread may acquire it again + without blocking; the thread must release it once for each time it has + acquired it. + + 'b'This class implements reentrant lock objects. + + A reentrant lock must be released by the thread that acquired it. Once a + thread has acquired a reentrant lock, the same thread may acquire it + again without blocking; the thread must release it once for each time it + has acquired it. + + 'u'This class implements reentrant lock objects. + + A reentrant lock must be released by the thread that acquired it. Once a + thread has acquired a reentrant lock, the same thread may acquire it + again without blocking; the thread must release it once for each time it + has acquired it. + + 'b'<%s %s.%s object owner=%r count=%d at %s>'u'<%s %s.%s object owner=%r count=%d at %s>'b'Acquire a lock, blocking or non-blocking. + + When invoked without arguments: if this thread already owns the lock, + increment the recursion level by one, and return immediately. Otherwise, + if another thread owns the lock, block until the lock is unlocked. Once + the lock is unlocked (not owned by any thread), then grab ownership, set + the recursion level to one, and return. If more than one thread is + blocked waiting until the lock is unlocked, only one at a time will be + able to grab ownership of the lock. There is no return value in this + case. + + When invoked with the blocking argument set to true, do the same thing + as when called without arguments, and return true. + + When invoked with the blocking argument set to false, do not block. If a + call without an argument would block, return false immediately; + otherwise, do the same thing as when called without arguments, and + return true. + + When invoked with the floating-point timeout argument set to a positive + value, block for at most the number of seconds specified by timeout + and as long as the lock cannot be acquired. Return true if the lock has + been acquired, false if the timeout has elapsed. + + 'u'Acquire a lock, blocking or non-blocking. + + When invoked without arguments: if this thread already owns the lock, + increment the recursion level by one, and return immediately. Otherwise, + if another thread owns the lock, block until the lock is unlocked. Once + the lock is unlocked (not owned by any thread), then grab ownership, set + the recursion level to one, and return. If more than one thread is + blocked waiting until the lock is unlocked, only one at a time will be + able to grab ownership of the lock. There is no return value in this + case. + + When invoked with the blocking argument set to true, do the same thing + as when called without arguments, and return true. + + When invoked with the blocking argument set to false, do not block. If a + call without an argument would block, return false immediately; + otherwise, do the same thing as when called without arguments, and + return true. + + When invoked with the floating-point timeout argument set to a positive + value, block for at most the number of seconds specified by timeout + and as long as the lock cannot be acquired. Return true if the lock has + been acquired, false if the timeout has elapsed. + + 'b'Release a lock, decrementing the recursion level. + + If after the decrement it is zero, reset the lock to unlocked (not owned + by any thread), and if any other threads are blocked waiting for the + lock to become unlocked, allow exactly one of them to proceed. If after + the decrement the recursion level is still nonzero, the lock remains + locked and owned by the calling thread. + + Only call this method when the calling thread owns the lock. A + RuntimeError is raised if this method is called when the lock is + unlocked. + + There is no return value. + + 'u'Release a lock, decrementing the recursion level. + + If after the decrement it is zero, reset the lock to unlocked (not owned + by any thread), and if any other threads are blocked waiting for the + lock to become unlocked, allow exactly one of them to proceed. If after + the decrement the recursion level is still nonzero, the lock remains + locked and owned by the calling thread. + + Only call this method when the calling thread owns the lock. A + RuntimeError is raised if this method is called when the lock is + unlocked. + + There is no return value. + + 'b'Class that implements a condition variable. + + A condition variable allows one or more threads to wait until they are + notified by another thread. + + If the lock argument is given and not None, it must be a Lock or RLock + object, and it is used as the underlying lock. Otherwise, a new RLock object + is created and used as the underlying lock. + + 'u'Class that implements a condition variable. + + A condition variable allows one or more threads to wait until they are + notified by another thread. + + If the lock argument is given and not None, it must be a Lock or RLock + object, and it is used as the underlying lock. Otherwise, a new RLock object + is created and used as the underlying lock. + + 'b''u''b'Wait until notified or until a timeout occurs. + + If the calling thread has not acquired the lock when this method is + called, a RuntimeError is raised. + + This method releases the underlying lock, and then blocks until it is + awakened by a notify() or notify_all() call for the same condition + variable in another thread, or until the optional timeout occurs. Once + awakened or timed out, it re-acquires the lock and returns. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + When the underlying lock is an RLock, it is not released using its + release() method, since this may not actually unlock the lock when it + was acquired multiple times recursively. Instead, an internal interface + of the RLock class is used, which really unlocks it even when it has + been recursively acquired several times. Another internal interface is + then used to restore the recursion level when the lock is reacquired. + + 'u'Wait until notified or until a timeout occurs. + + If the calling thread has not acquired the lock when this method is + called, a RuntimeError is raised. + + This method releases the underlying lock, and then blocks until it is + awakened by a notify() or notify_all() call for the same condition + variable in another thread, or until the optional timeout occurs. Once + awakened or timed out, it re-acquires the lock and returns. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + When the underlying lock is an RLock, it is not released using its + release() method, since this may not actually unlock the lock when it + was acquired multiple times recursively. Instead, an internal interface + of the RLock class is used, which really unlocks it even when it has + been recursively acquired several times. Another internal interface is + then used to restore the recursion level when the lock is reacquired. + + 'b'Wait until a condition evaluates to True. + + predicate should be a callable which result will be interpreted as a + boolean value. A timeout may be provided giving the maximum time to + wait. + + 'u'Wait until a condition evaluates to True. + + predicate should be a callable which result will be interpreted as a + boolean value. A timeout may be provided giving the maximum time to + wait. + + 'b'Wake up one or more threads waiting on this condition, if any. + + If the calling thread has not acquired the lock when this method is + called, a RuntimeError is raised. + + This method wakes up at most n of the threads waiting for the condition + variable; it is a no-op if no threads are waiting. + + 'u'Wake up one or more threads waiting on this condition, if any. + + If the calling thread has not acquired the lock when this method is + called, a RuntimeError is raised. + + This method wakes up at most n of the threads waiting for the condition + variable; it is a no-op if no threads are waiting. + + 'b'Wake up all threads waiting on this condition. + + If the calling thread has not acquired the lock when this method + is called, a RuntimeError is raised. + + 'u'Wake up all threads waiting on this condition. + + If the calling thread has not acquired the lock when this method + is called, a RuntimeError is raised. + + 'b'This class implements semaphore objects. + + Semaphores manage a counter representing the number of release() calls minus + the number of acquire() calls, plus an initial value. The acquire() method + blocks if necessary until it can return without making the counter + negative. If not given, value defaults to 1. + + 'u'This class implements semaphore objects. + + Semaphores manage a counter representing the number of release() calls minus + the number of acquire() calls, plus an initial value. The acquire() method + blocks if necessary until it can return without making the counter + negative. If not given, value defaults to 1. + + 'b'semaphore initial value must be >= 0'u'semaphore initial value must be >= 0'b'Acquire a semaphore, decrementing the internal counter by one. + + When invoked without arguments: if the internal counter is larger than + zero on entry, decrement it by one and return immediately. If it is zero + on entry, block, waiting until some other thread has called release() to + make it larger than zero. This is done with proper interlocking so that + if multiple acquire() calls are blocked, release() will wake exactly one + of them up. The implementation may pick one at random, so the order in + which blocked threads are awakened should not be relied on. There is no + return value in this case. + + When invoked with blocking set to true, do the same thing as when called + without arguments, and return true. + + When invoked with blocking set to false, do not block. If a call without + an argument would block, return false immediately; otherwise, do the + same thing as when called without arguments, and return true. + + When invoked with a timeout other than None, it will block for at + most timeout seconds. If acquire does not complete successfully in + that interval, return false. Return true otherwise. + + 'u'Acquire a semaphore, decrementing the internal counter by one. + + When invoked without arguments: if the internal counter is larger than + zero on entry, decrement it by one and return immediately. If it is zero + on entry, block, waiting until some other thread has called release() to + make it larger than zero. This is done with proper interlocking so that + if multiple acquire() calls are blocked, release() will wake exactly one + of them up. The implementation may pick one at random, so the order in + which blocked threads are awakened should not be relied on. There is no + return value in this case. + + When invoked with blocking set to true, do the same thing as when called + without arguments, and return true. + + When invoked with blocking set to false, do not block. If a call without + an argument would block, return false immediately; otherwise, do the + same thing as when called without arguments, and return true. + + When invoked with a timeout other than None, it will block for at + most timeout seconds. If acquire does not complete successfully in + that interval, return false. Return true otherwise. + + 'b'can't specify timeout for non-blocking acquire'u'can't specify timeout for non-blocking acquire'b'Release a semaphore, incrementing the internal counter by one. + + When the counter is zero on entry and another thread is waiting for it + to become larger than zero again, wake up that thread. + + 'u'Release a semaphore, incrementing the internal counter by one. + + When the counter is zero on entry and another thread is waiting for it + to become larger than zero again, wake up that thread. + + 'b'Implements a bounded semaphore. + + A bounded semaphore checks to make sure its current value doesn't exceed its + initial value. If it does, ValueError is raised. In most situations + semaphores are used to guard resources with limited capacity. + + If the semaphore is released too many times it's a sign of a bug. If not + given, value defaults to 1. + + Like regular semaphores, bounded semaphores manage a counter representing + the number of release() calls minus the number of acquire() calls, plus an + initial value. The acquire() method blocks if necessary until it can return + without making the counter negative. If not given, value defaults to 1. + + 'u'Implements a bounded semaphore. + + A bounded semaphore checks to make sure its current value doesn't exceed its + initial value. If it does, ValueError is raised. In most situations + semaphores are used to guard resources with limited capacity. + + If the semaphore is released too many times it's a sign of a bug. If not + given, value defaults to 1. + + Like regular semaphores, bounded semaphores manage a counter representing + the number of release() calls minus the number of acquire() calls, plus an + initial value. The acquire() method blocks if necessary until it can return + without making the counter negative. If not given, value defaults to 1. + + 'b'Release a semaphore, incrementing the internal counter by one. + + When the counter is zero on entry and another thread is waiting for it + to become larger than zero again, wake up that thread. + + If the number of releases exceeds the number of acquires, + raise a ValueError. + + 'u'Release a semaphore, incrementing the internal counter by one. + + When the counter is zero on entry and another thread is waiting for it + to become larger than zero again, wake up that thread. + + If the number of releases exceeds the number of acquires, + raise a ValueError. + + 'b'Semaphore released too many times'u'Semaphore released too many times'b'Class implementing event objects. + + Events manage a flag that can be set to true with the set() method and reset + to false with the clear() method. The wait() method blocks until the flag is + true. The flag is initially false. + + 'u'Class implementing event objects. + + Events manage a flag that can be set to true with the set() method and reset + to false with the clear() method. The wait() method blocks until the flag is + true. The flag is initially false. + + 'b'Return true if and only if the internal flag is true.'u'Return true if and only if the internal flag is true.'b'Set the internal flag to true. + + All threads waiting for it to become true are awakened. Threads + that call wait() once the flag is true will not block at all. + + 'u'Set the internal flag to true. + + All threads waiting for it to become true are awakened. Threads + that call wait() once the flag is true will not block at all. + + 'b'Reset the internal flag to false. + + Subsequently, threads calling wait() will block until set() is called to + set the internal flag to true again. + + 'u'Reset the internal flag to false. + + Subsequently, threads calling wait() will block until set() is called to + set the internal flag to true again. + + 'b'Block until the internal flag is true. + + If the internal flag is true on entry, return immediately. Otherwise, + block until another thread calls set() to set the flag to true, or until + the optional timeout occurs. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + This method returns the internal flag on exit, so it will always return + True except if a timeout is given and the operation times out. + + 'u'Block until the internal flag is true. + + If the internal flag is true on entry, return immediately. Otherwise, + block until another thread calls set() to set the flag to true, or until + the optional timeout occurs. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + This method returns the internal flag on exit, so it will always return + True except if a timeout is given and the operation times out. + + 'b'Implements a Barrier. + + Useful for synchronizing a fixed number of threads at known synchronization + points. Threads block on 'wait()' and are simultaneously awoken once they + have all made that call. + + 'u'Implements a Barrier. + + Useful for synchronizing a fixed number of threads at known synchronization + points. Threads block on 'wait()' and are simultaneously awoken once they + have all made that call. + + 'b'Create a barrier, initialised to 'parties' threads. + + 'action' is a callable which, when supplied, will be called by one of + the threads after they have all entered the barrier and just prior to + releasing them all. If a 'timeout' is provided, it is used as the + default for all subsequent 'wait()' calls. + + 'u'Create a barrier, initialised to 'parties' threads. + + 'action' is a callable which, when supplied, will be called by one of + the threads after they have all entered the barrier and just prior to + releasing them all. If a 'timeout' is provided, it is used as the + default for all subsequent 'wait()' calls. + + 'b'Wait for the barrier. + + When the specified number of threads have started waiting, they are all + simultaneously awoken. If an 'action' was provided for the barrier, one + of the threads will have executed that callback prior to returning. + Returns an individual index number from 0 to 'parties-1'. + + 'u'Wait for the barrier. + + When the specified number of threads have started waiting, they are all + simultaneously awoken. If an 'action' was provided for the barrier, one + of the threads will have executed that callback prior to returning. + Returns an individual index number from 0 to 'parties-1'. + + 'b'Reset the barrier to the initial state. + + Any threads currently waiting will get the BrokenBarrier exception + raised. + + 'u'Reset the barrier to the initial state. + + Any threads currently waiting will get the BrokenBarrier exception + raised. + + 'b'Place the barrier into a 'broken' state. + + Useful in case of error. Any currently waiting threads and threads + attempting to 'wait()' will have BrokenBarrierError raised. + + 'u'Place the barrier into a 'broken' state. + + Useful in case of error. Any currently waiting threads and threads + attempting to 'wait()' will have BrokenBarrierError raised. + + 'b'Return the number of threads required to trip the barrier.'u'Return the number of threads required to trip the barrier.'b'Return the number of threads currently waiting at the barrier.'u'Return the number of threads currently waiting at the barrier.'b'Return True if the barrier is in a broken state.'u'Return True if the barrier is in a broken state.'b'Thread-%d'u'Thread-%d'b'A class that represents a thread of control. + + This class can be safely subclassed in a limited fashion. There are two ways + to specify the activity: by passing a callable object to the constructor, or + by overriding the run() method in a subclass. + + 'u'A class that represents a thread of control. + + This class can be safely subclassed in a limited fashion. There are two ways + to specify the activity: by passing a callable object to the constructor, or + by overriding the run() method in a subclass. + + 'b'This constructor should always be called with keyword arguments. Arguments are: + + *group* should be None; reserved for future extension when a ThreadGroup + class is implemented. + + *target* is the callable object to be invoked by the run() + method. Defaults to None, meaning nothing is called. + + *name* is the thread name. By default, a unique name is constructed of + the form "Thread-N" where N is a small decimal number. + + *args* is the argument tuple for the target invocation. Defaults to (). + + *kwargs* is a dictionary of keyword arguments for the target + invocation. Defaults to {}. + + If a subclass overrides the constructor, it must make sure to invoke + the base class constructor (Thread.__init__()) before doing anything + else to the thread. + + 'u'This constructor should always be called with keyword arguments. Arguments are: + + *group* should be None; reserved for future extension when a ThreadGroup + class is implemented. + + *target* is the callable object to be invoked by the run() + method. Defaults to None, meaning nothing is called. + + *name* is the thread name. By default, a unique name is constructed of + the form "Thread-N" where N is a small decimal number. + + *args* is the argument tuple for the target invocation. Defaults to (). + + *kwargs* is a dictionary of keyword arguments for the target + invocation. Defaults to {}. + + If a subclass overrides the constructor, it must make sure to invoke + the base class constructor (Thread.__init__()) before doing anything + else to the thread. + + 'b'Thread.__init__() was not called'u'Thread.__init__() was not called'b' daemon'u' daemon'b' %s'u' %s'b'<%s(%s, %s)>'u'<%s(%s, %s)>'b'Start the thread's activity. + + It must be called at most once per thread object. It arranges for the + object's run() method to be invoked in a separate thread of control. + + This method will raise a RuntimeError if called more than once on the + same thread object. + + 'u'Start the thread's activity. + + It must be called at most once per thread object. It arranges for the + object's run() method to be invoked in a separate thread of control. + + This method will raise a RuntimeError if called more than once on the + same thread object. + + 'b'thread.__init__() not called'u'thread.__init__() not called'b'threads can only be started once'u'threads can only be started once'b'Method representing the thread's activity. + + You may override this method in a subclass. The standard run() method + invokes the callable object passed to the object's constructor as the + target argument, if any, with sequential and keyword arguments taken + from the args and kwargs arguments, respectively. + + 'u'Method representing the thread's activity. + + You may override this method in a subclass. The standard run() method + invokes the callable object passed to the object's constructor as the + target argument, if any, with sequential and keyword arguments taken + from the args and kwargs arguments, respectively. + + 'b' + Set a lock object which will be released by the interpreter when + the underlying thread state (see pystate.h) gets deleted. + 'u' + Set a lock object which will be released by the interpreter when + the underlying thread state (see pystate.h) gets deleted. + 'b'Remove current thread from the dict of currently running threads.'u'Remove current thread from the dict of currently running threads.'b'Wait until the thread terminates. + + This blocks the calling thread until the thread whose join() method is + called terminates -- either normally or through an unhandled exception + or until the optional timeout occurs. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). As join() always returns None, you must call + is_alive() after join() to decide whether a timeout happened -- if the + thread is still alive, the join() call timed out. + + When the timeout argument is not present or None, the operation will + block until the thread terminates. + + A thread can be join()ed many times. + + join() raises a RuntimeError if an attempt is made to join the current + thread as that would cause a deadlock. It is also an error to join() a + thread before it has been started and attempts to do so raises the same + exception. + + 'u'Wait until the thread terminates. + + This blocks the calling thread until the thread whose join() method is + called terminates -- either normally or through an unhandled exception + or until the optional timeout occurs. + + When the timeout argument is present and not None, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). As join() always returns None, you must call + is_alive() after join() to decide whether a timeout happened -- if the + thread is still alive, the join() call timed out. + + When the timeout argument is not present or None, the operation will + block until the thread terminates. + + A thread can be join()ed many times. + + join() raises a RuntimeError if an attempt is made to join the current + thread as that would cause a deadlock. It is also an error to join() a + thread before it has been started and attempts to do so raises the same + exception. + + 'b'Thread.__init__() not called'u'Thread.__init__() not called'b'cannot join thread before it is started'u'cannot join thread before it is started'b'cannot join current thread'u'cannot join current thread'b'A string used for identification purposes only. + + It has no semantics. Multiple threads may be given the same name. The + initial name is set by the constructor. + + 'u'A string used for identification purposes only. + + It has no semantics. Multiple threads may be given the same name. The + initial name is set by the constructor. + + 'b'Thread identifier of this thread or None if it has not been started. + + This is a nonzero integer. See the get_ident() function. Thread + identifiers may be recycled when a thread exits and another thread is + created. The identifier is available even after the thread has exited. + + 'u'Thread identifier of this thread or None if it has not been started. + + This is a nonzero integer. See the get_ident() function. Thread + identifiers may be recycled when a thread exits and another thread is + created. The identifier is available even after the thread has exited. + + 'b'Native integral thread ID of this thread, or None if it has not been started. + + This is a non-negative integer. See the get_native_id() function. + This represents the Thread ID as reported by the kernel. + + 'u'Native integral thread ID of this thread, or None if it has not been started. + + This is a non-negative integer. See the get_native_id() function. + This represents the Thread ID as reported by the kernel. + + 'b'Return whether the thread is alive. + + This method returns True just before the run() method starts until just + after the run() method terminates. The module function enumerate() + returns a list of all alive threads. + + 'u'Return whether the thread is alive. + + This method returns True just before the run() method starts until just + after the run() method terminates. The module function enumerate() + returns a list of all alive threads. + + 'b'Return whether the thread is alive. + + This method is deprecated, use is_alive() instead. + 'u'Return whether the thread is alive. + + This method is deprecated, use is_alive() instead. + 'b'isAlive() is deprecated, use is_alive() instead'u'isAlive() is deprecated, use is_alive() instead'b'A boolean value indicating whether this thread is a daemon thread. + + This must be set before start() is called, otherwise RuntimeError is + raised. Its initial value is inherited from the creating thread; the + main thread is not a daemon thread and therefore all threads created in + the main thread default to daemon = False. + + The entire Python program exits when only daemon threads are left. + + 'u'A boolean value indicating whether this thread is a daemon thread. + + This must be set before start() is called, otherwise RuntimeError is + raised. Its initial value is inherited from the creating thread; the + main thread is not a daemon thread and therefore all threads created in + the main thread default to daemon = False. + + The entire Python program exits when only daemon threads are left. + + 'b'cannot set daemon status of active thread'u'cannot set daemon status of active thread'b'exc_type exc_value exc_traceback thread'u'exc_type exc_value exc_traceback thread'b' + Handle uncaught Thread.run() exception. + 'u' + Handle uncaught Thread.run() exception. + 'b'Exception in thread 'u'Exception in thread 'b'threading.excepthook is None'u'threading.excepthook is None'b'sys.excepthook is None'u'sys.excepthook is None'b'Exception in threading.excepthook:'u'Exception in threading.excepthook:'b'Call a function after a specified number of seconds: + + t = Timer(30.0, f, args=None, kwargs=None) + t.start() + t.cancel() # stop the timer's action if it's still waiting + + 'u'Call a function after a specified number of seconds: + + t = Timer(30.0, f, args=None, kwargs=None) + t.start() + t.cancel() # stop the timer's action if it's still waiting + + 'b'Stop the timer if it hasn't finished yet.'u'Stop the timer if it hasn't finished yet.'b'MainThread'u'MainThread'b'Dummy-%d'u'Dummy-%d'b'cannot join a dummy thread'u'cannot join a dummy thread'b'Return the current Thread object, corresponding to the caller's thread of control. + + If the caller's thread of control was not created through the threading + module, a dummy thread object with limited functionality is returned. + + 'u'Return the current Thread object, corresponding to the caller's thread of control. + + If the caller's thread of control was not created through the threading + module, a dummy thread object with limited functionality is returned. + + 'b'Return the number of Thread objects currently alive. + + The returned count is equal to the length of the list returned by + enumerate(). + + 'u'Return the number of Thread objects currently alive. + + The returned count is equal to the length of the list returned by + enumerate(). + + 'b'Return a list of all Thread objects currently alive. + + The list includes daemonic threads, dummy thread objects created by + current_thread(), and the main thread. It excludes terminated threads and + threads that have not yet been started. + + 'u'Return a list of all Thread objects currently alive. + + The list includes daemonic threads, dummy thread objects created by + current_thread(), and the main thread. It excludes terminated threads and + threads that have not yet been started. + + 'b' + Wait until the Python thread state of all non-daemon threads get deleted. + 'u' + Wait until the Python thread state of all non-daemon threads get deleted. + 'b'Return the main thread object. + + In normal conditions, the main thread is the thread from which the + Python interpreter was started. + 'u'Return the main thread object. + + In normal conditions, the main thread is the thread from which the + Python interpreter was started. + 'b' + Cleanup threading module state that should not exist after a fork. + 'u' + Cleanup threading module state that should not exist after a fork. + 'u'threading'CLOCK_MONOTONICCLOCK_MONOTONIC_RAWCLOCK_PROCESS_CPUTIME_IDCLOCK_REALTIMECLOCK_THREAD_CPUTIME_IDCLOCK_UPTIME_RAW_STRUCT_TM_ITEMSu'This module provides various functions to manipulate time values. + +There are two standard representations of time. One is the number +of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer +or a floating point number (to represent fractions of seconds). +The Epoch is system-defined; on Unix, it is generally January 1st, 1970. +The actual value can be retrieved by calling gmtime(0). + +The other representation is a tuple of 9 integers giving local time. +The tuple items are: + year (including century, e.g. 1998) + month (1-12) + day (1-31) + hours (0-23) + minutes (0-59) + seconds (0-59) + weekday (0-6, Monday is 0) + Julian day (day in the year, 1-366) + DST (Daylight Savings Time) flag (-1, 0 or 1) +If the DST flag is 0, the time is given in the regular time zone; +if it is 1, the time is given in the DST time zone; +if it is -1, mktime() should guess based on the date and time. +'-7200altzoneclock_getresclock_gettimeclock_gettime_nsclock_settimeclock_settime_nsdaylightmonotonic_nsperf_counter_nsprocess_timeprocess_time_nsu'The time value as returned by gmtime(), localtime(), and strptime(), and + accepted by asctime(), mktime() and strftime(). May be considered as a + sequence of 9 integers. + + Note that several fields' values are not the same as those defined by + the C language standard for struct tm. For example, the value of the + field tm_year is the actual year, not year - 1900. See individual + fields' descriptions for details.'tm_hourtm_isdsttm_mdaytm_mintm_montm_sectm_wdaytm_ydaytm_yeartime.struct_timethread_timethread_time_nstime_ns-3600u'CET'u'CEST'Token constants (from "token.h").LSQBRSQBSEMIMINUSSLASHVBARAMPERLESSGREATERPERCENTBACKQUOTEEQEQUALNOTEQUALLESSEQUALGREATEREQUALTILDECIRCUMFLEXLEFTSHIFTRIGHTSHIFTDOUBLESTARPLUSEQUALMINEQUALSTAREQUALSLASHEQUALPERCENTEQUALAMPEREQUALVBAREQUALCIRCUMFLEXEQUALLEFTSHIFTEQUALRIGHTSHIFTEQUALDOUBLESTAREQUALDOUBLESLASHDOUBLESLASHEQUALATEQUALRARROWAWAITASYNCCOLONEQUALN_TOKENSNT_OFFSETISTERMINALISNONTERMINALISEOF# Taken from Python (r53757) and modified to include some tokens# originally monkeypatched in by pgen2.tokenize#--start constants--#--end constants--b'Token constants (from "token.h").'u'Token constants (from "token.h").'u'lib2to3.pgen2.token'u'pgen2.token'u'token'Token constants.TYPE_IGNORETYPE_COMMENT:=@=EXACT_TOKEN_TYPES# Auto-generated by Tools/scripts/generate_token.py# These aren't used by the C tokenizer but are needed for tokenize.py# Special definitions for cooperation with parserb'Token constants.'u'Token constants.'b'tok_name'u'tok_name'b'ISTERMINAL'u'ISTERMINAL'b'ISNONTERMINAL'u'ISNONTERMINAL'b'ISEOF'u'ISEOF'b':='u':='b'@='u'@='Tokenization help for Python programs. + +tokenize(readline) is a generator that breaks a stream of bytes into +Python tokens. It decodes the bytes according to PEP-0263 for +determining source file encoding. + +It accepts a readline-like method which is called repeatedly to get the +next line of input (or b"" for EOF). It generates 5-tuples with these +members: + + the token type (see token.py) + the token (a string) + the starting (row, column) indices of the token (a 2-tuple of ints) + the ending (row, column) indices of the token (a 2-tuple of ints) + the original line (string) + +It is designed to match the working of the Python tokenizer exactly, except +that it produces COMMENT tokens for comments and gives type OP for all +operators. Additionally, all token lists start with an ENCODING token +which tells you which encoding was used to decode the bytes stream. +GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger, Trent Nelson, Michael Foord'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ''Skip Montanaro, Raymond Hettinger, Trent Nelson, ''Michael Foord'_itertools^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)cookie_re^[ \t\f]*(?:[#\r\n]|$)blank_reuntokenizeTokenInfotype string start end line%d (%s)annotated_typeTokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)exact_type[ \f\t]*Whitespace#[^\r\n]*\\\r?\nIgnore\w+0[xX](?:_?[0-9a-fA-F])+Hexnumber0[bB](?:_?[01])+Binnumber0[oO](?:_?[0-7])+Octnumber(?:0(?:_?0)*|[1-9](?:_?[0-9])*)DecnumberIntnumber[eE][-+]?[0-9](?:_?[0-9])*Exponent[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?\.[0-9](?:_?[0-9])*Pointfloat[0-9](?:_?[0-9])*ExpfloatFloatnumber[0-9](?:_?[0-9])*[jJ][jJ]Imagnumber_all_string_prefixes_valid_string_prefixesStringPrefix[^'\\]*(?:\\.[^'\\]*)*'Single[^"\\]*(?:\\.[^"\\]*)*"Double[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''Single3[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""Double3Triple'[^\n'\\]*(?:\\.[^\n'\\]*)*'"[^\n"\\]*(?:\\.[^\n"\\]*)*"Special\r?\nFunnyPlainToken'[^\n'\\]*(?:\\.[^\n'\\]*)*"[^\n"\\]*(?:\\.[^\n"\\]*)*ContStr\\\r?\n|\ZPseudoExtrasPseudoTokenendpatssingle_quotedtriple_quotedTokenErrorStopTokenizingUntokenizerprev_rowprev_coladd_whitespacestart ({},{}) precedes previous end ({},{})row_offsetstartlinecompattok_typetoks_appendprevstringtoknumtokvalTransform tokens back into Python source code. + It returns a bytes object, encoded using the ENCODING + token, which is the first token sequence output by tokenize. + + Each element returned by the iterable must be a token sequence + with at least two elements, a token number and token value. If + only two tokens are passed, the resulting output is poor. + + Round-trip invariant for full input: + Untokenized source will match input source exactly + + Round-trip invariant for limited input: + # Output bytes will tokenize back to the input + t1 = [tok[:2] for tok in tokenize(f.readline)] + newcode = untokenize(t1) + readline = BytesIO(newcode).readline + t2 = [tok[:2] for tok in tokenize(readline)] + assert t1 == t2 + ut_get_normal_nameorig_encImitates get_normal_name in tokenizer.c.utf-8-iso-latin-1latin-1-iso-8859-1-iso-latin-1- + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, + but disagree, a SyntaxError will be raised. If the encoding cookie is an + invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, + 'utf-8-sig' is returned. + + If no encoding is specified, then the default of 'utf-8' will be returned. + bom_foundread_or_stopfind_cookieline_stringinvalid or missing encoding declaration{} for {!r}unknown encoding: unknown encoding for {!r}: {}encoding problem: utf-8encoding problem for {!r}: utf-8-sigutf-8-sigOpen a file in read only mode using the encoding detected by + detect_encoding(). + + The tokenize() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as bytes. Alternatively, readline + can be a callable function terminating with StopIteration: + readline = open(myfile, 'rb').__next__ # Example of alternate readline + + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple (srow, scol) of ints specifying the row and + column where the token begins in the source; a 2-tuple (erow, ecol) of + ints specifying the row and column where the token ends in the source; + and the line on which the token was found. The line passed is the + physical line. + + The first token sequence will always be an ENCODING token + which tells you which encoding was used to decode the bytes stream. + rl_genparenlevcontinuednumcharscontstrneedcontcontlineEOF in multi-line stringstrstartendprogendmatch\ +# +comment_tokenunindent does not match any outer indentation levelEOF in multi-line statementpseudomatchsposepos([{)]}Tokenize a source reading Python code as unicode strings. + + This has the same API as tokenize(), except that it expects the *readline* + callable to return str objects instead of bytes. + perror%s:%d:%d: error: %s%s: error: %serror: %spython -m tokenizefilename.pythe file to tokenize; defaults to stdin--exactdisplay token names using the exact typetoken_type%d,%d-%d,%d:token_range%-20s%-15s%-15rinterrupted +unexpected error: %s# Note: we use unicode matching for names ("\w") but ascii matching for# number literals.# Return the empty string, plus all of the valid string prefixes.# The valid string prefixes. Only contain the lower case versions,# and don't contain any permutations (include 'fr', but not# 'rf'). The various permutations will be generated.# if we add binary f-strings, add: ['fb', 'fbr']# create a list with upper and lower versions of each# character# Note that since _all_string_prefixes includes the empty string,# StringPrefix can be the empty string (making it optional).# Tail end of ' string.# Tail end of " string.# Tail end of ''' string.# Tail end of """ string.# Single-line ' or " string.# Sorting in reverse order puts the long operators before their prefixes.# Otherwise if = came before ==, == would get recognized as two instances# of =.# First (or only) line of ' or " string.# For a given string prefix plus quotes, endpats maps it to a regex# to match the remainder of that string. _prefix can be empty, for# a normal single or triple quoted string (with no prefix).# A set of all of the single and triple quoted string prefixes,# including the opening quotes.# Insert a space between two consecutive strings# Only care about the first 12 characters.# Decode as UTF-8. Either the line is an encoding declaration,# in which case it should be pure ASCII, or it must be UTF-8# per default encoding.# This behaviour mimics the Python interpreter# BOM will already have been stripped.# loop over lines in stream# We capture the value of the line variable here because# readline uses the empty string '' to signal end of input,# hence `line` itself will always be overwritten at the end# of this loop.# continued string# new statement# measure leading whitespace# skip comments or blank lines# count indents or dedents# continued statement# scan for tokens# ordinary number# all on one line# multiple lines# Check up to the first 3 chars of the token to see if# they're in the single_quoted set. If so, they start# a string.# We're using the first 3, because we're looking for# "rb'" (for example) at the start of the token. If# we switch to longer prefixes, this needs to be# adjusted.# Note that initial == token[:1].# Also note that single quote checking must come after# triple quote checking (above).# Again, using the first 3 chars of the# token. This is looking for the matching end# regex for the correct type of quote# character. So it's really looking for# endpats["'"] or endpats['"'], by trying to# skip string prefix characters, if any.# ordinary string# ordinary name# continued stmt# Add an implicit NEWLINE if the input doesn't end in one# pop remaining indent levels# Helper error handling routines# Parse the arguments and options# Tokenize the input# Output the tokenizationb'Tokenization help for Python programs. + +tokenize(readline) is a generator that breaks a stream of bytes into +Python tokens. It decodes the bytes according to PEP-0263 for +determining source file encoding. + +It accepts a readline-like method which is called repeatedly to get the +next line of input (or b"" for EOF). It generates 5-tuples with these +members: + + the token type (see token.py) + the token (a string) + the starting (row, column) indices of the token (a 2-tuple of ints) + the ending (row, column) indices of the token (a 2-tuple of ints) + the original line (string) + +It is designed to match the working of the Python tokenizer exactly, except +that it produces COMMENT tokens for comments and gives type OP for all +operators. Additionally, all token lists start with an ENCODING token +which tells you which encoding was used to decode the bytes stream. +'u'Tokenization help for Python programs. + +tokenize(readline) is a generator that breaks a stream of bytes into +Python tokens. It decodes the bytes according to PEP-0263 for +determining source file encoding. + +It accepts a readline-like method which is called repeatedly to get the +next line of input (or b"" for EOF). It generates 5-tuples with these +members: + + the token type (see token.py) + the token (a string) + the starting (row, column) indices of the token (a 2-tuple of ints) + the ending (row, column) indices of the token (a 2-tuple of ints) + the original line (string) + +It is designed to match the working of the Python tokenizer exactly, except +that it produces COMMENT tokens for comments and gives type OP for all +operators. Additionally, all token lists start with an ENCODING token +which tells you which encoding was used to decode the bytes stream. +'b'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger, Trent Nelson, Michael Foord'u'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger, Trent Nelson, Michael Foord'b'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)'u'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)'b'^[ \t\f]*(?:[#\r\n]|$)'b'tokenize'u'tokenize'b'generate_tokens'u'generate_tokens'b'detect_encoding'u'detect_encoding'b'untokenize'u'untokenize'b'TokenInfo'u'TokenInfo'b'type string start end line'u'type string start end line'b'%d (%s)'u'%d (%s)'b'TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)'u'TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)'b'[ \f\t]*'u'[ \f\t]*'b'#[^\r\n]*'u'#[^\r\n]*'b'\\\r?\n'u'\\\r?\n'b'\w+'u'\w+'b'0[xX](?:_?[0-9a-fA-F])+'u'0[xX](?:_?[0-9a-fA-F])+'b'0[bB](?:_?[01])+'u'0[bB](?:_?[01])+'b'0[oO](?:_?[0-7])+'u'0[oO](?:_?[0-7])+'b'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'u'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'b'[eE][-+]?[0-9](?:_?[0-9])*'u'[eE][-+]?[0-9](?:_?[0-9])*'b'[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?'u'[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?'b'\.[0-9](?:_?[0-9])*'u'\.[0-9](?:_?[0-9])*'b'[0-9](?:_?[0-9])*'u'[0-9](?:_?[0-9])*'b'[0-9](?:_?[0-9])*[jJ]'u'[0-9](?:_?[0-9])*[jJ]'b'[jJ]'u'[jJ]'b'[^'\\]*(?:\\.[^'\\]*)*''u'[^'\\]*(?:\\.[^'\\]*)*''b'[^"\\]*(?:\\.[^"\\]*)*"'u'[^"\\]*(?:\\.[^"\\]*)*"'b'[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*''''u'[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*''''b'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'u'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'b''[^\n'\\]*(?:\\.[^\n'\\]*)*''u''[^\n'\\]*(?:\\.[^\n'\\]*)*''b'"[^\n"\\]*(?:\\.[^\n"\\]*)*"'u'"[^\n"\\]*(?:\\.[^\n"\\]*)*"'b'\r?\n'u'\r?\n'b''[^\n'\\]*(?:\\.[^\n'\\]*)*'u''[^\n'\\]*(?:\\.[^\n'\\]*)*'b'"[^\n"\\]*(?:\\.[^\n"\\]*)*'u'"[^\n"\\]*(?:\\.[^\n"\\]*)*'b'\\\r?\n|\Z'u'\\\r?\n|\Z'b'start ({},{}) precedes previous end ({},{})'u'start ({},{}) precedes previous end ({},{})'b'Transform tokens back into Python source code. + It returns a bytes object, encoded using the ENCODING + token, which is the first token sequence output by tokenize. + + Each element returned by the iterable must be a token sequence + with at least two elements, a token number and token value. If + only two tokens are passed, the resulting output is poor. + + Round-trip invariant for full input: + Untokenized source will match input source exactly + + Round-trip invariant for limited input: + # Output bytes will tokenize back to the input + t1 = [tok[:2] for tok in tokenize(f.readline)] + newcode = untokenize(t1) + readline = BytesIO(newcode).readline + t2 = [tok[:2] for tok in tokenize(readline)] + assert t1 == t2 + 'u'Transform tokens back into Python source code. + It returns a bytes object, encoded using the ENCODING + token, which is the first token sequence output by tokenize. + + Each element returned by the iterable must be a token sequence + with at least two elements, a token number and token value. If + only two tokens are passed, the resulting output is poor. + + Round-trip invariant for full input: + Untokenized source will match input source exactly + + Round-trip invariant for limited input: + # Output bytes will tokenize back to the input + t1 = [tok[:2] for tok in tokenize(f.readline)] + newcode = untokenize(t1) + readline = BytesIO(newcode).readline + t2 = [tok[:2] for tok in tokenize(readline)] + assert t1 == t2 + 'b'Imitates get_normal_name in tokenizer.c.'u'Imitates get_normal_name in tokenizer.c.'b'utf-8-'u'utf-8-'b'iso-latin-1'u'iso-latin-1'b'latin-1-'u'latin-1-'b'iso-8859-1-'u'iso-8859-1-'b'iso-latin-1-'u'iso-latin-1-'b' + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, + but disagree, a SyntaxError will be raised. If the encoding cookie is an + invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, + 'utf-8-sig' is returned. + + If no encoding is specified, then the default of 'utf-8' will be returned. + 'u' + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, + but disagree, a SyntaxError will be raised. If the encoding cookie is an + invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, + 'utf-8-sig' is returned. + + If no encoding is specified, then the default of 'utf-8' will be returned. + 'b'invalid or missing encoding declaration'u'invalid or missing encoding declaration'b'{} for {!r}'u'{} for {!r}'b'unknown encoding: 'u'unknown encoding: 'b'unknown encoding for {!r}: {}'u'unknown encoding for {!r}: {}'b'encoding problem: utf-8'u'encoding problem: utf-8'b'encoding problem for {!r}: utf-8'u'encoding problem for {!r}: utf-8'b'-sig'u'-sig'b'utf-8-sig'u'utf-8-sig'b'Open a file in read only mode using the encoding detected by + detect_encoding(). + 'u'Open a file in read only mode using the encoding detected by + detect_encoding(). + 'b' + The tokenize() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as bytes. Alternatively, readline + can be a callable function terminating with StopIteration: + readline = open(myfile, 'rb').__next__ # Example of alternate readline + + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple (srow, scol) of ints specifying the row and + column where the token begins in the source; a 2-tuple (erow, ecol) of + ints specifying the row and column where the token ends in the source; + and the line on which the token was found. The line passed is the + physical line. + + The first token sequence will always be an ENCODING token + which tells you which encoding was used to decode the bytes stream. + 'u' + The tokenize() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as bytes. Alternatively, readline + can be a callable function terminating with StopIteration: + readline = open(myfile, 'rb').__next__ # Example of alternate readline + + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple (srow, scol) of ints specifying the row and + column where the token begins in the source; a 2-tuple (erow, ecol) of + ints specifying the row and column where the token ends in the source; + and the line on which the token was found. The line passed is the + physical line. + + The first token sequence will always be an ENCODING token + which tells you which encoding was used to decode the bytes stream. + 'b'EOF in multi-line string'u'EOF in multi-line string'b'\ +'u'\ +'b'# +'u'# +'b'unindent does not match any outer indentation level'u'unindent does not match any outer indentation level'b''u''b'EOF in multi-line statement'u'EOF in multi-line statement'b'([{'u'([{'b')]}'u')]}'b'Tokenize a source reading Python code as unicode strings. + + This has the same API as tokenize(), except that it expects the *readline* + callable to return str objects instead of bytes. + 'u'Tokenize a source reading Python code as unicode strings. + + This has the same API as tokenize(), except that it expects the *readline* + callable to return str objects instead of bytes. + 'b'%s:%d:%d: error: %s'u'%s:%d:%d: error: %s'b'%s: error: %s'u'%s: error: %s'b'error: %s'u'error: %s'b'python -m tokenize'u'python -m tokenize'b'filename.py'u'filename.py'b'the file to tokenize; defaults to stdin'u'the file to tokenize; defaults to stdin'b'--exact'u'--exact'b'exact'u'exact'b'display token names using the exact type'u'display token names using the exact type'b'%d,%d-%d,%d:'u'%d,%d-%d,%d:'b'%-20s%-15s%-15r'u'%-20s%-15s%-15r'b'interrupted +'u'interrupted +'b'unexpected error: %s'u'unexpected error: %s'Tokenization help for Python programs. + +generate_tokens(readline) is a generator that breaks a stream of +text into Python tokens. It accepts a readline-like method which is called +repeatedly to get the next line of input (or "" for EOF). It generates +5-tuples with these members: + + the token type (see token.py) + the token (a string) + the starting (row, column) indices of the token (a 2-tuple of ints) + the ending (row, column) indices of the token (a 2-tuple of ints) + the original line (string) + +It is designed to match the working of the Python tokenizer exactly, except +that it produces COMMENT tokens for comments and gives type OP for all +operators + +Older entry points + tokenize_loop(readline, tokeneater) + tokenize(readline, tokeneater=printtoken) +are the same, except instead of generating tokens, tokeneater is a callback +function to which the 5 fields described above are passed as 5 arguments, +each time a new token is found.GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanarolib2to3.pgen2.token_combinations0[bB]_?[01]+(?:_[01]+)*0[xX]_?[\da-fA-F]+(?:_[\da-fA-F]+)*[lL]?0[oO]?_?[0-7]+(?:_[0-7]+)*[lL]?[1-9]\d*(?:_\d+)*[lL]?0[lL]?[eE][-+]?\d+(?:_\d+)*\d+(?:_\d+)*\.(?:\d+(?:_\d+)*)?\.\d+(?:_\d+)*\d+(?:_\d+)*\d+(?:_\d+)*[jJ](?:[uUrRbBfF]|[rR][fFbB]|[fFbBuU][rR])?_litprefix\*\*=?>>=?<<=?//=?[+\-*/%&@|^=<>]=?Operator[][(){}]Bracket[:;.,`@]tokenprogpseudoprogsingle3progdouble3proguRUrURendprogsprinttokenxxx_todo_changemexxx_todo_changeme1srowscolerowecol%d,%d-%d,%d: %s %s + The tokenize() function accepts two parameters: one representing the + input stream, and one providing an output mechanism for tokenize(). + + The first parameter, readline, must be a callable object which provides + the same interface as the readline() method of built-in file objects. + Each call to the function should return one line of input as a string. + + The second parameter, tokeneater, must also be a callable object. It is + called once for each token, with five arguments, corresponding to the + tuples generated by generate_tokens(). + tokenize_looptoken_info + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read + in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, but + disagree, a SyntaxError will be raised. If the encoding cookie is an invalid + charset, raise a SyntaxError. Note that if a utf-8 bom is found, + 'utf-8-sig' is returned. + + If no encoding is specified, then the default of 'utf-8' will be returned. + Transform tokens back into Python source code. + + Each element returned by the iterable must be a token sequence + with at least two elements, a token number and token value. If + only two tokens are passed, the resulting output is poor. + + Round-trip invariant for full input: + Untokenized source will match input source exactly + + Round-trip invariant for limited input: + # Output text will tokenize the back to the input + t1 = [tok[:2] for tok in generate_tokens(f.readline)] + newcode = untokenize(t1) + readline = iter(newcode.splitlines(1)).next + t2 = [tok[:2] for tokin generate_tokens(readline)] + assert t1 == t2 + + The generate_tokens() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as a string. Alternately, readline + can be a callable function terminating with StopIteration: + readline = open(myfile).next # Example of alternate readline + + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple (srow, scol) of ints specifying the row and + column where the token begins in the source; a 2-tuple (erow, ecol) of + ints specifying the row and column where the token ends in the source; + and the line on which the token was found. The line passed is the + physical line. + stashedasync_defasync_def_indentasync_def_nlnl_pos# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.# Support bytes type in Python <= 2.5, so 2to3 turns itself into# valid Python 3 code.# Because of leftmost-then-longest match semantics, be sure to put the# longest operators first (e.g., if = came before ==, == would get# recognized as two instances of =).# backwards compatible interface# 'stashed' and 'async_*' are used for async/await parsing# This yield is new; needed for better idempotency:# testingb'Tokenization help for Python programs. + +generate_tokens(readline) is a generator that breaks a stream of +text into Python tokens. It accepts a readline-like method which is called +repeatedly to get the next line of input (or "" for EOF). It generates +5-tuples with these members: + + the token type (see token.py) + the token (a string) + the starting (row, column) indices of the token (a 2-tuple of ints) + the ending (row, column) indices of the token (a 2-tuple of ints) + the original line (string) + +It is designed to match the working of the Python tokenizer exactly, except +that it produces COMMENT tokens for comments and gives type OP for all +operators + +Older entry points + tokenize_loop(readline, tokeneater) + tokenize(readline, tokeneater=printtoken) +are the same, except instead of generating tokens, tokeneater is a callback +function to which the 5 fields described above are passed as 5 arguments, +each time a new token is found.'u'Tokenization help for Python programs. + +generate_tokens(readline) is a generator that breaks a stream of +text into Python tokens. It accepts a readline-like method which is called +repeatedly to get the next line of input (or "" for EOF). It generates +5-tuples with these members: + + the token type (see token.py) + the token (a string) + the starting (row, column) indices of the token (a 2-tuple of ints) + the ending (row, column) indices of the token (a 2-tuple of ints) + the original line (string) + +It is designed to match the working of the Python tokenizer exactly, except +that it produces COMMENT tokens for comments and gives type OP for all +operators + +Older entry points + tokenize_loop(readline, tokeneater) + tokenize(readline, tokeneater=printtoken) +are the same, except instead of generating tokens, tokeneater is a callback +function to which the 5 fields described above are passed as 5 arguments, +each time a new token is found.'b'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'u'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'b'0[bB]_?[01]+(?:_[01]+)*'u'0[bB]_?[01]+(?:_[01]+)*'b'0[xX]_?[\da-fA-F]+(?:_[\da-fA-F]+)*[lL]?'u'0[xX]_?[\da-fA-F]+(?:_[\da-fA-F]+)*[lL]?'b'0[oO]?_?[0-7]+(?:_[0-7]+)*[lL]?'u'0[oO]?_?[0-7]+(?:_[0-7]+)*[lL]?'b'[1-9]\d*(?:_\d+)*[lL]?'u'[1-9]\d*(?:_\d+)*[lL]?'b'0[lL]?'u'0[lL]?'b'[eE][-+]?\d+(?:_\d+)*'u'[eE][-+]?\d+(?:_\d+)*'b'\d+(?:_\d+)*\.(?:\d+(?:_\d+)*)?'u'\d+(?:_\d+)*\.(?:\d+(?:_\d+)*)?'b'\.\d+(?:_\d+)*'u'\.\d+(?:_\d+)*'b'\d+(?:_\d+)*'u'\d+(?:_\d+)*'b'\d+(?:_\d+)*[jJ]'u'\d+(?:_\d+)*[jJ]'b'(?:[uUrRbBfF]|[rR][fFbB]|[fFbBuU][rR])?'u'(?:[uUrRbBfF]|[rR][fFbB]|[fFbBuU][rR])?'b'\*\*=?'u'\*\*=?'b'>>=?'u'>>=?'b'<<=?'u'<<=?'b'//=?'u'//=?'b'[+\-*/%&@|^=<>]=?'u'[+\-*/%&@|^=<>]=?'b'[][(){}]'u'[][(){}]'b'[:;.,`@]'u'[:;.,`@]'u'R'b'uR'u'uR'b'Ur'u'Ur'b'UR'u'UR'b'%d,%d-%d,%d: %s %s'u'%d,%d-%d,%d: %s %s'b' + The tokenize() function accepts two parameters: one representing the + input stream, and one providing an output mechanism for tokenize(). + + The first parameter, readline, must be a callable object which provides + the same interface as the readline() method of built-in file objects. + Each call to the function should return one line of input as a string. + + The second parameter, tokeneater, must also be a callable object. It is + called once for each token, with five arguments, corresponding to the + tuples generated by generate_tokens(). + 'u' + The tokenize() function accepts two parameters: one representing the + input stream, and one providing an output mechanism for tokenize(). + + The first parameter, readline, must be a callable object which provides + the same interface as the readline() method of built-in file objects. + Each call to the function should return one line of input as a string. + + The second parameter, tokeneater, must also be a callable object. It is + called once for each token, with five arguments, corresponding to the + tuples generated by generate_tokens(). + 'b' + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read + in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, but + disagree, a SyntaxError will be raised. If the encoding cookie is an invalid + charset, raise a SyntaxError. Note that if a utf-8 bom is found, + 'utf-8-sig' is returned. + + If no encoding is specified, then the default of 'utf-8' will be returned. + 'u' + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read + in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, but + disagree, a SyntaxError will be raised. If the encoding cookie is an invalid + charset, raise a SyntaxError. Note that if a utf-8 bom is found, + 'utf-8-sig' is returned. + + If no encoding is specified, then the default of 'utf-8' will be returned. + 'b'Transform tokens back into Python source code. + + Each element returned by the iterable must be a token sequence + with at least two elements, a token number and token value. If + only two tokens are passed, the resulting output is poor. + + Round-trip invariant for full input: + Untokenized source will match input source exactly + + Round-trip invariant for limited input: + # Output text will tokenize the back to the input + t1 = [tok[:2] for tok in generate_tokens(f.readline)] + newcode = untokenize(t1) + readline = iter(newcode.splitlines(1)).next + t2 = [tok[:2] for tokin generate_tokens(readline)] + assert t1 == t2 + 'u'Transform tokens back into Python source code. + + Each element returned by the iterable must be a token sequence + with at least two elements, a token number and token value. If + only two tokens are passed, the resulting output is poor. + + Round-trip invariant for full input: + Untokenized source will match input source exactly + + Round-trip invariant for limited input: + # Output text will tokenize the back to the input + t1 = [tok[:2] for tok in generate_tokens(f.readline)] + newcode = untokenize(t1) + readline = iter(newcode.splitlines(1)).next + t2 = [tok[:2] for tokin generate_tokens(readline)] + assert t1 == t2 + 'b' + The generate_tokens() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as a string. Alternately, readline + can be a callable function terminating with StopIteration: + readline = open(myfile).next # Example of alternate readline + + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple (srow, scol) of ints specifying the row and + column where the token begins in the source; a 2-tuple (erow, ecol) of + ints specifying the row and column where the token ends in the source; + and the line on which the token was found. The line passed is the + physical line. + 'u' + The generate_tokens() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as a string. Alternately, readline + can be a callable function terminating with StopIteration: + readline = open(myfile).next # Example of alternate readline + + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple (srow, scol) of ints specifying the row and + column where the token begins in the source; a 2-tuple (erow, ecol) of + ints specifying the row and column where the token ends in the source; + and the line on which the token was found. The line passed is the + physical line. + 'u'lib2to3.pgen2.tokenize'u'pgen2.tokenize'Extract, format and print information about Python stack traces.extract_tbformat_stackformat_tbprint_lastprint_tbFrameSummarywalk_tbPrint the list of tuples as returned by extract_tb() or + extract_stack() as a formatted stack trace to the given file.from_listFormat a list of tuples or FrameSummary objects for printing. + + Given a list of tuples or FrameSummary objects as returned by + extract_tb() or extract_stack(), return a list of strings ready + for printing. + + Each string in the resulting list corresponds to the item with the + same index in the argument list. Each string ends in a newline; + the strings may contain internal newlines as well, for those items + whose source text line is not None. + Print up to 'limit' stack trace entries from the traceback 'tb'. + + If 'limit' is omitted or None, all entries are printed. If 'file' + is omitted or None, the output goes to sys.stderr; otherwise + 'file' should be an open file or file-like object with a write() + method. + A shorthand for 'format_list(extract_tb(tb, limit))'. + Return a StackSummary object representing a list of + pre-processed entries from traceback. + + This is useful for alternate formatting of stack traces. If + 'limit' is omitted or None, all entries are extracted. A + pre-processed stack trace entry is a FrameSummary object + containing attributes filename, lineno, name, and line + representing the information that is usually printed for a stack + trace. The line is a string with leading and trailing + whitespace stripped; if the source is not available it is None. + +The above exception was the direct cause of the following exception: + +"\nThe above exception was the direct cause ""of the following exception:\n\n"_cause_message +During handling of the above exception, another exception occurred: + +"\nDuring handling of the above exception, ""another exception occurred:\n\n"_context_messageetypePrint exception up to 'limit' stack trace entries from 'tb' to 'file'. + + This differs from print_tb() in the following ways: (1) if + traceback is not None, it prints a header "Traceback (most recent + call last):"; (2) it prints the exception type and value after the + stack trace; (3) if type is SyntaxError and value has the + appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error. + Format a stack trace and the exception information. + + The arguments have the same meaning as the corresponding arguments + to print_exception(). The return value is a list of strings, each + ending in a newline and some containing internal newlines. When + these lines are concatenated and printed, exactly the same text is + printed as does print_exception(). + Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. + + Normally, the list contains a single string; however, for + SyntaxError exceptions, it contains several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the list. + + _format_final_exc_line_some_strvaluestr%s: %s +Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.Like print_exc() but return a string.This is a shorthand for 'print_exception(sys.last_type, + sys.last_value, sys.last_traceback, limit, file)'.no last exceptionPrint a stack trace from its invocation point. + + The optional 'f' argument can be used to specify an alternate + stack frame at which to start. The optional 'limit' and 'file' + arguments have the same meaning as for print_exception(). + Shorthand for 'format_list(extract_stack(f, limit))'.Extract the raw traceback from the current stack frame. + + The return value has the same format as for extract_tb(). The + optional 'f' and 'limit' arguments have the same meaning as for + print_stack(). Each item in the list is a quadruple (filename, + line number, function name, text), and the entries are in order + from oldest to newest stack frame. + Clear all references to local variables in the frames of a traceback.A single frame from a traceback. + + - :attr:`filename` The filename for the frame. + - :attr:`lineno` The line within filename for the frame that was + active when the frame was captured. + - :attr:`name` The name of the function or method that was executing + when the frame was captured. + - :attr:`line` The text from the linecache module for the + of code that was running when the frame was captured. + - :attr:`locals` Either None if locals were not supplied, or a dict + mapping the name to the repr() of the variable. + _linelookup_lineConstruct a FrameSummary. + + :param lookup_line: If True, `linecache` is consulted for the source + code line. Otherwise, the line will be looked up when first needed. + :param locals: If supplied the frame locals, which will be captured as + object representations. + :param line: If provided, use this instead of looking up the line in + the linecache. + Walk a stack yielding the frame and line number for each frame. + + This will follow f.f_back from the given frame. If no frame is given, the + current stack is used. Usually used with StackSummary.extract. + Walk a traceback yielding the frame and line number for each frame. + + This will follow tb.tb_next (and thus is in the opposite order to + walk_stack). Usually used with StackSummary.extract. + _RECURSIVE_CUTOFFA stack of frames.frame_genCreate a StackSummary from a traceback or stack object. + + :param frame_gen: A generator that yields (frame, lineno) tuples to + include in the stack. + :param limit: None to include all frames or the number of frames to + include. + :param lookup_lines: If True, lookup lines for each frame immediately, + otherwise lookup is deferred until the frame is rendered. + :param capture_locals: If True, the local variables from each frame will + be captured as object representations into the FrameSummary. + tracebacklimitfnamesa_list + Create a StackSummary object from a supplied list of + FrameSummary objects or old-style list of tuples. + Format the stack ready for printing. + + Returns a list of strings ready for printing. Each string in the + resulting list corresponds to a single frame from the stack. + Each string ends in a newline; the strings may contain internal + newlines as well, for those items with source text lines. + + For long sequences of the same frame and line, the first few + repetitions are shown, followed by a summary line stating the exact + number of further repetitions. + last_filelast_name [Previous line repeated more time' more ''time'] + File "{}", line {}, in {} + {} + {name} = {value} +An exception ready for rendering. + + The traceback module captures enough attributes from the original exception + to this intermediary form to ensure that no references are held, while + still being able to fully print or format it. + + Use `from_exception` to create TracebackException instances from exception + objects, or the constructor to create TracebackException instances from + individual components. + + - :attr:`__cause__` A TracebackException of the original *__cause__*. + - :attr:`__context__` A TracebackException of the original *__context__*. + - :attr:`__suppress_context__` The *__suppress_context__* value from the + original exception. + - :attr:`stack` A `StackSummary` representing the traceback. + - :attr:`exc_type` The class of the original traceback. + - :attr:`filename` For syntax errors - the filename where the error + occurred. + - :attr:`lineno` For syntax errors - the linenumber where the error + occurred. + - :attr:`text` For syntax errors - the text where the error + occurred. + - :attr:`offset` For syntax errors - the offset into the text where the + error occurred. + - :attr:`msg` For syntax errors - the compiler error message. + _seen_load_linesfrom_exceptionCreate a TracebackException from an exception.Private API. force all lines in the stack to be loaded.Format the exception part of the traceback. + + The return value is a generator of strings, each ending in a newline. + + Normally, the generator emits a single string; however, for + SyntaxError exceptions, it emits several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the output. + stypesmodfilename_suffix File "{}", line {} + ({})badlinecaretspace {}^ +{}: {}{} +Format the exception. + + If chain is not *True*, *__cause__* and *__context__* will not be formatted. + + The return value is a generator of strings, each ending in a newline and + some containing internal newlines. `print_exception` is a wrapper around + this method which just prints the lines to a file. + + The message indicating which exception occurred is always the last + string in the output. + Traceback (most recent call last): +# Formatting and printing lists of traceback lines.# Printing and Extracting Tracebacks.# Exception formatting and output.# format_exception has ignored etype for some time, and code such as cgitb# passes in bogus values as a result. For compatibility with such code we# ignore it here (rather than in the new TracebackException API).# -- not official API but folk probably use these two functions.# --# Printing and Extracting Stacks.# Ignore the exception raised if the frame is still executing.# Also hardcoded in traceback.c.# Must defer line lookups until we have called checkcache.# If immediate lookup was desired, trigger lookups now.# While doing a fast-path check for isinstance(a_list, StackSummary) is# appealing, idlelib.run.cleanup_traceback and other similar code may# break this by making arbitrary frames plain tuples, so we need to# check on a frame by frame basis.# NB: we need to accept exc_traceback, exc_value, exc_traceback to# permit backwards compat with the existing API, otherwise we# need stub thunk objects just to glue it together.# Handle loops in __cause__ or __context__.# Gracefully handle (the way Python 2.4 and earlier did) the case of# being called with no type or value (None, None, None).# TODO: locals.# Capture now to permit freeing resources: only complication is in the# unofficial API _format_final_exc_line# Handle SyntaxError's specially# It was a syntax error; show exactly where the problem was found.# non-space whitespace (likes tabs) must be kept for alignmentb'Extract, format and print information about Python stack traces.'u'Extract, format and print information about Python stack traces.'b'extract_stack'u'extract_stack'b'extract_tb'u'extract_tb'b'format_exception'u'format_exception'b'format_exception_only'u'format_exception_only'b'format_list'u'format_list'b'format_stack'u'format_stack'b'format_tb'u'format_tb'b'print_exc'u'print_exc'b'format_exc'u'format_exc'b'print_exception'u'print_exception'b'print_last'u'print_last'b'print_stack'u'print_stack'b'print_tb'u'print_tb'b'clear_frames'u'clear_frames'b'FrameSummary'u'FrameSummary'b'StackSummary'u'StackSummary'b'TracebackException'u'TracebackException'b'walk_stack'u'walk_stack'b'walk_tb'u'walk_tb'b'Print the list of tuples as returned by extract_tb() or + extract_stack() as a formatted stack trace to the given file.'u'Print the list of tuples as returned by extract_tb() or + extract_stack() as a formatted stack trace to the given file.'b'Format a list of tuples or FrameSummary objects for printing. + + Given a list of tuples or FrameSummary objects as returned by + extract_tb() or extract_stack(), return a list of strings ready + for printing. + + Each string in the resulting list corresponds to the item with the + same index in the argument list. Each string ends in a newline; + the strings may contain internal newlines as well, for those items + whose source text line is not None. + 'u'Format a list of tuples or FrameSummary objects for printing. + + Given a list of tuples or FrameSummary objects as returned by + extract_tb() or extract_stack(), return a list of strings ready + for printing. + + Each string in the resulting list corresponds to the item with the + same index in the argument list. Each string ends in a newline; + the strings may contain internal newlines as well, for those items + whose source text line is not None. + 'b'Print up to 'limit' stack trace entries from the traceback 'tb'. + + If 'limit' is omitted or None, all entries are printed. If 'file' + is omitted or None, the output goes to sys.stderr; otherwise + 'file' should be an open file or file-like object with a write() + method. + 'u'Print up to 'limit' stack trace entries from the traceback 'tb'. + + If 'limit' is omitted or None, all entries are printed. If 'file' + is omitted or None, the output goes to sys.stderr; otherwise + 'file' should be an open file or file-like object with a write() + method. + 'b'A shorthand for 'format_list(extract_tb(tb, limit))'.'u'A shorthand for 'format_list(extract_tb(tb, limit))'.'b' + Return a StackSummary object representing a list of + pre-processed entries from traceback. + + This is useful for alternate formatting of stack traces. If + 'limit' is omitted or None, all entries are extracted. A + pre-processed stack trace entry is a FrameSummary object + containing attributes filename, lineno, name, and line + representing the information that is usually printed for a stack + trace. The line is a string with leading and trailing + whitespace stripped; if the source is not available it is None. + 'u' + Return a StackSummary object representing a list of + pre-processed entries from traceback. + + This is useful for alternate formatting of stack traces. If + 'limit' is omitted or None, all entries are extracted. A + pre-processed stack trace entry is a FrameSummary object + containing attributes filename, lineno, name, and line + representing the information that is usually printed for a stack + trace. The line is a string with leading and trailing + whitespace stripped; if the source is not available it is None. + 'b' +The above exception was the direct cause of the following exception: + +'u' +The above exception was the direct cause of the following exception: + +'b' +During handling of the above exception, another exception occurred: + +'u' +During handling of the above exception, another exception occurred: + +'b'Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + + This differs from print_tb() in the following ways: (1) if + traceback is not None, it prints a header "Traceback (most recent + call last):"; (2) it prints the exception type and value after the + stack trace; (3) if type is SyntaxError and value has the + appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error. + 'u'Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + + This differs from print_tb() in the following ways: (1) if + traceback is not None, it prints a header "Traceback (most recent + call last):"; (2) it prints the exception type and value after the + stack trace; (3) if type is SyntaxError and value has the + appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error. + 'b'Format a stack trace and the exception information. + + The arguments have the same meaning as the corresponding arguments + to print_exception(). The return value is a list of strings, each + ending in a newline and some containing internal newlines. When + these lines are concatenated and printed, exactly the same text is + printed as does print_exception(). + 'u'Format a stack trace and the exception information. + + The arguments have the same meaning as the corresponding arguments + to print_exception(). The return value is a list of strings, each + ending in a newline and some containing internal newlines. When + these lines are concatenated and printed, exactly the same text is + printed as does print_exception(). + 'b'Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. + + Normally, the list contains a single string; however, for + SyntaxError exceptions, it contains several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the list. + + 'u'Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. + + Normally, the list contains a single string; however, for + SyntaxError exceptions, it contains several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the list. + + 'b'%s: %s +'u'%s: %s +'b''u''b'Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.'u'Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.'b'Like print_exc() but return a string.'u'Like print_exc() but return a string.'b'This is a shorthand for 'print_exception(sys.last_type, + sys.last_value, sys.last_traceback, limit, file)'.'u'This is a shorthand for 'print_exception(sys.last_type, + sys.last_value, sys.last_traceback, limit, file)'.'b'last_type'u'last_type'b'no last exception'u'no last exception'b'Print a stack trace from its invocation point. + + The optional 'f' argument can be used to specify an alternate + stack frame at which to start. The optional 'limit' and 'file' + arguments have the same meaning as for print_exception(). + 'u'Print a stack trace from its invocation point. + + The optional 'f' argument can be used to specify an alternate + stack frame at which to start. The optional 'limit' and 'file' + arguments have the same meaning as for print_exception(). + 'b'Shorthand for 'format_list(extract_stack(f, limit))'.'u'Shorthand for 'format_list(extract_stack(f, limit))'.'b'Extract the raw traceback from the current stack frame. + + The return value has the same format as for extract_tb(). The + optional 'f' and 'limit' arguments have the same meaning as for + print_stack(). Each item in the list is a quadruple (filename, + line number, function name, text), and the entries are in order + from oldest to newest stack frame. + 'u'Extract the raw traceback from the current stack frame. + + The return value has the same format as for extract_tb(). The + optional 'f' and 'limit' arguments have the same meaning as for + print_stack(). Each item in the list is a quadruple (filename, + line number, function name, text), and the entries are in order + from oldest to newest stack frame. + 'b'Clear all references to local variables in the frames of a traceback.'u'Clear all references to local variables in the frames of a traceback.'b'A single frame from a traceback. + + - :attr:`filename` The filename for the frame. + - :attr:`lineno` The line within filename for the frame that was + active when the frame was captured. + - :attr:`name` The name of the function or method that was executing + when the frame was captured. + - :attr:`line` The text from the linecache module for the + of code that was running when the frame was captured. + - :attr:`locals` Either None if locals were not supplied, or a dict + mapping the name to the repr() of the variable. + 'u'A single frame from a traceback. + + - :attr:`filename` The filename for the frame. + - :attr:`lineno` The line within filename for the frame that was + active when the frame was captured. + - :attr:`name` The name of the function or method that was executing + when the frame was captured. + - :attr:`line` The text from the linecache module for the + of code that was running when the frame was captured. + - :attr:`locals` Either None if locals were not supplied, or a dict + mapping the name to the repr() of the variable. + 'b'_line'u'_line'b'locals'u'locals'b'Construct a FrameSummary. + + :param lookup_line: If True, `linecache` is consulted for the source + code line. Otherwise, the line will be looked up when first needed. + :param locals: If supplied the frame locals, which will be captured as + object representations. + :param line: If provided, use this instead of looking up the line in + the linecache. + 'u'Construct a FrameSummary. + + :param lookup_line: If True, `linecache` is consulted for the source + code line. Otherwise, the line will be looked up when first needed. + :param locals: If supplied the frame locals, which will be captured as + object representations. + :param line: If provided, use this instead of looking up the line in + the linecache. + 'b''u''b'Walk a stack yielding the frame and line number for each frame. + + This will follow f.f_back from the given frame. If no frame is given, the + current stack is used. Usually used with StackSummary.extract. + 'u'Walk a stack yielding the frame and line number for each frame. + + This will follow f.f_back from the given frame. If no frame is given, the + current stack is used. Usually used with StackSummary.extract. + 'b'Walk a traceback yielding the frame and line number for each frame. + + This will follow tb.tb_next (and thus is in the opposite order to + walk_stack). Usually used with StackSummary.extract. + 'u'Walk a traceback yielding the frame and line number for each frame. + + This will follow tb.tb_next (and thus is in the opposite order to + walk_stack). Usually used with StackSummary.extract. + 'b'A stack of frames.'u'A stack of frames.'b'Create a StackSummary from a traceback or stack object. + + :param frame_gen: A generator that yields (frame, lineno) tuples to + include in the stack. + :param limit: None to include all frames or the number of frames to + include. + :param lookup_lines: If True, lookup lines for each frame immediately, + otherwise lookup is deferred until the frame is rendered. + :param capture_locals: If True, the local variables from each frame will + be captured as object representations into the FrameSummary. + 'u'Create a StackSummary from a traceback or stack object. + + :param frame_gen: A generator that yields (frame, lineno) tuples to + include in the stack. + :param limit: None to include all frames or the number of frames to + include. + :param lookup_lines: If True, lookup lines for each frame immediately, + otherwise lookup is deferred until the frame is rendered. + :param capture_locals: If True, the local variables from each frame will + be captured as object representations into the FrameSummary. + 'b'tracebacklimit'u'tracebacklimit'b' + Create a StackSummary object from a supplied list of + FrameSummary objects or old-style list of tuples. + 'u' + Create a StackSummary object from a supplied list of + FrameSummary objects or old-style list of tuples. + 'b'Format the stack ready for printing. + + Returns a list of strings ready for printing. Each string in the + resulting list corresponds to a single frame from the stack. + Each string ends in a newline; the strings may contain internal + newlines as well, for those items with source text lines. + + For long sequences of the same frame and line, the first few + repetitions are shown, followed by a summary line stating the exact + number of further repetitions. + 'u'Format the stack ready for printing. + + Returns a list of strings ready for printing. Each string in the + resulting list corresponds to a single frame from the stack. + Each string ends in a newline; the strings may contain internal + newlines as well, for those items with source text lines. + + For long sequences of the same frame and line, the first few + repetitions are shown, followed by a summary line stating the exact + number of further repetitions. + 'b' [Previous line repeated 'u' [Previous line repeated 'b' more time'u' more time'b'] +'u'] +'b' File "{}", line {}, in {} +'u' File "{}", line {}, in {} +'b' {} +'u' {} +'b' {name} = {value} +'u' {name} = {value} +'b'An exception ready for rendering. + + The traceback module captures enough attributes from the original exception + to this intermediary form to ensure that no references are held, while + still being able to fully print or format it. + + Use `from_exception` to create TracebackException instances from exception + objects, or the constructor to create TracebackException instances from + individual components. + + - :attr:`__cause__` A TracebackException of the original *__cause__*. + - :attr:`__context__` A TracebackException of the original *__context__*. + - :attr:`__suppress_context__` The *__suppress_context__* value from the + original exception. + - :attr:`stack` A `StackSummary` representing the traceback. + - :attr:`exc_type` The class of the original traceback. + - :attr:`filename` For syntax errors - the filename where the error + occurred. + - :attr:`lineno` For syntax errors - the linenumber where the error + occurred. + - :attr:`text` For syntax errors - the text where the error + occurred. + - :attr:`offset` For syntax errors - the offset into the text where the + error occurred. + - :attr:`msg` For syntax errors - the compiler error message. + 'u'An exception ready for rendering. + + The traceback module captures enough attributes from the original exception + to this intermediary form to ensure that no references are held, while + still being able to fully print or format it. + + Use `from_exception` to create TracebackException instances from exception + objects, or the constructor to create TracebackException instances from + individual components. + + - :attr:`__cause__` A TracebackException of the original *__cause__*. + - :attr:`__context__` A TracebackException of the original *__context__*. + - :attr:`__suppress_context__` The *__suppress_context__* value from the + original exception. + - :attr:`stack` A `StackSummary` representing the traceback. + - :attr:`exc_type` The class of the original traceback. + - :attr:`filename` For syntax errors - the filename where the error + occurred. + - :attr:`lineno` For syntax errors - the linenumber where the error + occurred. + - :attr:`text` For syntax errors - the text where the error + occurred. + - :attr:`offset` For syntax errors - the offset into the text where the + error occurred. + - :attr:`msg` For syntax errors - the compiler error message. + 'b'Create a TracebackException from an exception.'u'Create a TracebackException from an exception.'b'Private API. force all lines in the stack to be loaded.'u'Private API. force all lines in the stack to be loaded.'b'Format the exception part of the traceback. + + The return value is a generator of strings, each ending in a newline. + + Normally, the generator emits a single string; however, for + SyntaxError exceptions, it emits several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the output. + 'u'Format the exception part of the traceback. + + The return value is a generator of strings, each ending in a newline. + + Normally, the generator emits a single string; however, for + SyntaxError exceptions, it emits several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the output. + 'b' File "{}", line {} +'u' File "{}", line {} +'b' ({})'u' ({})'b' {}^ +'u' {}^ +'b''u''b'{}: {}{} +'u'{}: {}{} +'b'Format the exception. + + If chain is not *True*, *__cause__* and *__context__* will not be formatted. + + The return value is a generator of strings, each ending in a newline and + some containing internal newlines. `print_exception` is a wrapper around + this method which just prints the lines to a file. + + The message indicating which exception occurred is always the last + string in the output. + 'u'Format the exception. + + If chain is not *True*, *__cause__* and *__context__* will not be formatted. + + The return value is a generator of strings, each ending in a newline and + some containing internal newlines. `print_exception` is a wrapper around + this method which just prints the lines to a file. + + The message indicating which exception occurred is always the last + string in the output. + 'b'Traceback (most recent call last): +'u'Traceback (most recent call last): +'u'traceback'_format_sizeunitKiBMiBGiBTiB%+.1f %s%.1f %s%+.0f %s%.0f %sStatistic + Statistic difference on memory allocations between two Snapshot instance. + %s: size=%s, count=%iaverage, average=%s_sort_keyStatisticDiff + Statistic difference on memory allocations between an old and a new + Snapshot instance. + size_diffcount_diff%s: size=%s (%s), count=%i (%+i)_compare_grouped_statsold_groupnew_groupstatistics + Frame of a traceback. + _frame + Sequence of Frame instances sorted from the oldest frame + to the most recent frame. + _framesmost_recent_firstframe_slice File "%s", line %s %sget_object_traceback + Get the traceback where the Python object *obj* was allocated. + Return a Traceback instance. + + Return None if the tracemalloc module is not tracing memory allocations or + did not trace the allocation of the object. + Trace + Trace of a memory block. + _trace_Tracestraces_traces_normalize_filenameBaseFilterinclusive_matchfilename_patternall_frames_filename_pattern_match_frame_impl_match_frame_match_tracebackDomainFilter_domainSnapshot + Snapshot of traces of memory blocks allocated by Python. + traceback_limit + Write the snapshot into a file. + + Load a snapshot from a file. + _filter_traceinclude_filtersexclude_filterstrace_filterfilter_traces + Create a new Snapshot instance with a filtered traces sequence, filters + is a list of Filter or DomainFilter instances. If filters is an empty + list, return a new Snapshot instance with a copy of the traces. + filters must be a list of filters, not %snew_traces_group_bykey_typecumulativeunknown key_type: %rcumulative mode cannot by used with key type %r"cumulative mode cannot by used ""with key type %r"tracebackstrace_traceback + Group statistics by key_type. Return a sorted list of Statistic + instances. + groupedcompare_toold_snapshot + Compute the differences with an old snapshot old_snapshot. Get + statistics as a sorted list of StatisticDiff instances, grouped by + group_by. + take_snapshot + Take a snapshot of traces of memory blocks allocated by Python. + the tracemalloc module must be tracing memory allocations to take a snapshot"the tracemalloc module must be tracing memory ""allocations to take a snapshot"# Import types and functions implemented in C# 3 digits (xx.x UNIT)# 4 or 5 digits (xxxx UNIT)# frame is a tuple: (filename: str, lineno: int)# frames is a tuple of frame tuples: see Frame constructor for the# format of a frame tuple; it is reversed, because _tracemalloc# returns frames sorted from most recent to oldest, but the# Python API expects oldest to most recent# trace is a tuple: (domain: int, size: int, traceback: tuple).# See Traceback constructor for the format of the traceback tuple.# traces is a tuple of trace tuples: see Trace constructor# traces is a tuple of trace tuples: see _Traces constructor for# the exact format# key_type == 'filename':# cumulative statisticsb'KiB'u'KiB'b'MiB'u'MiB'b'GiB'u'GiB'b'TiB'u'TiB'b'%+.1f %s'u'%+.1f %s'b'%.1f %s'u'%.1f %s'b'%+.0f %s'u'%+.0f %s'b'%.0f %s'u'%.0f %s'b' + Statistic difference on memory allocations between two Snapshot instance. + 'u' + Statistic difference on memory allocations between two Snapshot instance. + 'b'traceback'b'%s: size=%s, count=%i'u'%s: size=%s, count=%i'b', average=%s'u', average=%s'b''u''b' + Statistic difference on memory allocations between an old and a new + Snapshot instance. + 'u' + Statistic difference on memory allocations between an old and a new + Snapshot instance. + 'b'size_diff'u'size_diff'b'count_diff'u'count_diff'b'%s: size=%s (%s), count=%i (%+i)'u'%s: size=%s (%s), count=%i (%+i)'b''u''b' + Frame of a traceback. + 'u' + Frame of a traceback. + 'b'_frame'u'_frame'b''u''b' + Sequence of Frame instances sorted from the oldest frame + to the most recent frame. + 'u' + Sequence of Frame instances sorted from the oldest frame + to the most recent frame. + 'b'_frames'u'_frames'b''u''b' File "%s", line %s'u' File "%s", line %s'b' %s'u' %s'b' + Get the traceback where the Python object *obj* was allocated. + Return a Traceback instance. + + Return None if the tracemalloc module is not tracing memory allocations or + did not trace the allocation of the object. + 'u' + Get the traceback where the Python object *obj* was allocated. + Return a Traceback instance. + + Return None if the tracemalloc module is not tracing memory allocations or + did not trace the allocation of the object. + 'b' + Trace of a memory block. + 'u' + Trace of a memory block. + 'b'_trace'u'_trace'b''u''b''u''b' + Snapshot of traces of memory blocks allocated by Python. + 'u' + Snapshot of traces of memory blocks allocated by Python. + 'b' + Write the snapshot into a file. + 'u' + Write the snapshot into a file. + 'b' + Load a snapshot from a file. + 'u' + Load a snapshot from a file. + 'b' + Create a new Snapshot instance with a filtered traces sequence, filters + is a list of Filter or DomainFilter instances. If filters is an empty + list, return a new Snapshot instance with a copy of the traces. + 'u' + Create a new Snapshot instance with a filtered traces sequence, filters + is a list of Filter or DomainFilter instances. If filters is an empty + list, return a new Snapshot instance with a copy of the traces. + 'b'filters must be a list of filters, not %s'u'filters must be a list of filters, not %s'b'unknown key_type: %r'u'unknown key_type: %r'b'cumulative mode cannot by used with key type %r'u'cumulative mode cannot by used with key type %r'b' + Group statistics by key_type. Return a sorted list of Statistic + instances. + 'u' + Group statistics by key_type. Return a sorted list of Statistic + instances. + 'b' + Compute the differences with an old snapshot old_snapshot. Get + statistics as a sorted list of StatisticDiff instances, grouped by + group_by. + 'u' + Compute the differences with an old snapshot old_snapshot. Get + statistics as a sorted list of StatisticDiff instances, grouped by + group_by. + 'b' + Take a snapshot of traces of memory blocks allocated by Python. + 'u' + Take a snapshot of traces of memory blocks allocated by Python. + 'b'the tracemalloc module must be tracing memory allocations to take a snapshot'u'the tracemalloc module must be tracing memory allocations to take a snapshot'Abstract Transport class.DatagramTransportBase class for transports.Return True if the transport is closing or closed.Close the transport. + + Buffered data will be flushed asynchronously. No more data + will be received. After all buffered data is flushed, the + protocol's connection_lost() method will (eventually) be + called with None as its argument. + Set a new protocol.Return the current protocol.Interface for read-only transports.Return True if the transport is receiving.Interface for write-only transports.list_of_dataWrite a list (or any iterable) of data bytes to the transport. + + The default implementation concatenates the arguments and + calls write() on the result. + Close the write end after flushing buffered data. + + (This is like typing ^D into a UNIX program reading from stdin.) + + Data may still be received. + Interface representing a bidirectional transport. + + There may be several implementations, but typically, the user does + not implement new transports; rather, the platform provides some + useful transports that are implemented using the platform's best + practices. + + The user never instantiates a transport directly; they call a + utility function, passing it a protocol factory and other + information necessary to create the transport and protocol. (E.g. + EventLoop.create_connection() or EventLoop.create_server().) + + The utility function will asynchronously create a transport and a + protocol and hook them up by calling the protocol's + connection_made() method, passing it the transport. + + The implementation here raises NotImplemented for every method + except writelines(), which calls write() in a loop. + Interface for datagram (UDP) transports.Send data to the transport. + + This does not block; it buffers the data and arranges for it + to be sent out asynchronously. + addr is target socket address. + If addr is None use target address pointed on transport creation. + Get subprocess id.Get subprocess returncode. + + See also + http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode + Get transport for pipe with number fd.Send signal to subprocess. + + See also: + docs.python.org/3/library/subprocess#subprocess.Popen.send_signal + Stop the subprocess. + + Alias for close() method. + + On Posix OSs the method sends SIGTERM to the subprocess. + On Windows the Win32 API function TerminateProcess() + is called to stop the subprocess. + + See also: + http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate + Kill the subprocess. + + On Posix OSs the function sends SIGKILL to the subprocess. + On Windows kill() is an alias for terminate(). + + See also: + http://docs.python.org/3/library/subprocess#subprocess.Popen.kill + All the logic for (write) flow control in a mix-in base class. + + The subclass must implement get_write_buffer_size(). It must call + _maybe_pause_protocol() whenever the write buffer size increases, + and _maybe_resume_protocol() whenever it decreases. It may also + override set_write_buffer_limits() (e.g. to specify different + defaults). + + The subclass constructor must call super().__init__(extra). This + will call set_write_buffer_limits(). + + The user may call set_write_buffer_limits() and + get_write_buffer_size(), and their protocol's pause_writing() and + resume_writing() may be called. + _high_water_low_water_set_write_buffer_limitsprotocol.pause_writing() failedprotocol.resume_writing() failedget_write_buffer_limitshigh () must be >= low () must be >= 0b'Abstract Transport class.'u'Abstract Transport class.'b'BaseTransport'u'BaseTransport'b'ReadTransport'u'ReadTransport'b'WriteTransport'u'WriteTransport'b'Transport'u'Transport'b'DatagramTransport'u'DatagramTransport'b'SubprocessTransport'u'SubprocessTransport'b'Base class for transports.'u'Base class for transports.'b'_extra'u'_extra'b'Return True if the transport is closing or closed.'u'Return True if the transport is closing or closed.'b'Close the transport. + + Buffered data will be flushed asynchronously. No more data + will be received. After all buffered data is flushed, the + protocol's connection_lost() method will (eventually) be + called with None as its argument. + 'u'Close the transport. + + Buffered data will be flushed asynchronously. No more data + will be received. After all buffered data is flushed, the + protocol's connection_lost() method will (eventually) be + called with None as its argument. + 'b'Set a new protocol.'u'Set a new protocol.'b'Return the current protocol.'u'Return the current protocol.'b'Interface for read-only transports.'u'Interface for read-only transports.'b'Return True if the transport is receiving.'u'Return True if the transport is receiving.'b'Interface for write-only transports.'u'Interface for write-only transports.'b'Write a list (or any iterable) of data bytes to the transport. + + The default implementation concatenates the arguments and + calls write() on the result. + 'u'Write a list (or any iterable) of data bytes to the transport. + + The default implementation concatenates the arguments and + calls write() on the result. + 'b'Close the write end after flushing buffered data. + + (This is like typing ^D into a UNIX program reading from stdin.) + + Data may still be received. + 'u'Close the write end after flushing buffered data. + + (This is like typing ^D into a UNIX program reading from stdin.) + + Data may still be received. + 'b'Interface representing a bidirectional transport. + + There may be several implementations, but typically, the user does + not implement new transports; rather, the platform provides some + useful transports that are implemented using the platform's best + practices. + + The user never instantiates a transport directly; they call a + utility function, passing it a protocol factory and other + information necessary to create the transport and protocol. (E.g. + EventLoop.create_connection() or EventLoop.create_server().) + + The utility function will asynchronously create a transport and a + protocol and hook them up by calling the protocol's + connection_made() method, passing it the transport. + + The implementation here raises NotImplemented for every method + except writelines(), which calls write() in a loop. + 'u'Interface representing a bidirectional transport. + + There may be several implementations, but typically, the user does + not implement new transports; rather, the platform provides some + useful transports that are implemented using the platform's best + practices. + + The user never instantiates a transport directly; they call a + utility function, passing it a protocol factory and other + information necessary to create the transport and protocol. (E.g. + EventLoop.create_connection() or EventLoop.create_server().) + + The utility function will asynchronously create a transport and a + protocol and hook them up by calling the protocol's + connection_made() method, passing it the transport. + + The implementation here raises NotImplemented for every method + except writelines(), which calls write() in a loop. + 'b'Interface for datagram (UDP) transports.'u'Interface for datagram (UDP) transports.'b'Send data to the transport. + + This does not block; it buffers the data and arranges for it + to be sent out asynchronously. + addr is target socket address. + If addr is None use target address pointed on transport creation. + 'u'Send data to the transport. + + This does not block; it buffers the data and arranges for it + to be sent out asynchronously. + addr is target socket address. + If addr is None use target address pointed on transport creation. + 'b'Get subprocess id.'u'Get subprocess id.'b'Get subprocess returncode. + + See also + http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode + 'u'Get subprocess returncode. + + See also + http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode + 'b'Get transport for pipe with number fd.'u'Get transport for pipe with number fd.'b'Send signal to subprocess. + + See also: + docs.python.org/3/library/subprocess#subprocess.Popen.send_signal + 'u'Send signal to subprocess. + + See also: + docs.python.org/3/library/subprocess#subprocess.Popen.send_signal + 'b'Stop the subprocess. + + Alias for close() method. + + On Posix OSs the method sends SIGTERM to the subprocess. + On Windows the Win32 API function TerminateProcess() + is called to stop the subprocess. + + See also: + http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate + 'u'Stop the subprocess. + + Alias for close() method. + + On Posix OSs the method sends SIGTERM to the subprocess. + On Windows the Win32 API function TerminateProcess() + is called to stop the subprocess. + + See also: + http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate + 'b'Kill the subprocess. + + On Posix OSs the function sends SIGKILL to the subprocess. + On Windows kill() is an alias for terminate(). + + See also: + http://docs.python.org/3/library/subprocess#subprocess.Popen.kill + 'u'Kill the subprocess. + + On Posix OSs the function sends SIGKILL to the subprocess. + On Windows kill() is an alias for terminate(). + + See also: + http://docs.python.org/3/library/subprocess#subprocess.Popen.kill + 'b'All the logic for (write) flow control in a mix-in base class. + + The subclass must implement get_write_buffer_size(). It must call + _maybe_pause_protocol() whenever the write buffer size increases, + and _maybe_resume_protocol() whenever it decreases. It may also + override set_write_buffer_limits() (e.g. to specify different + defaults). + + The subclass constructor must call super().__init__(extra). This + will call set_write_buffer_limits(). + + The user may call set_write_buffer_limits() and + get_write_buffer_size(), and their protocol's pause_writing() and + resume_writing() may be called. + 'u'All the logic for (write) flow control in a mix-in base class. + + The subclass must implement get_write_buffer_size(). It must call + _maybe_pause_protocol() whenever the write buffer size increases, + and _maybe_resume_protocol() whenever it decreases. It may also + override set_write_buffer_limits() (e.g. to specify different + defaults). + + The subclass constructor must call super().__init__(extra). This + will call set_write_buffer_limits(). + + The user may call set_write_buffer_limits() and + get_write_buffer_size(), and their protocol's pause_writing() and + resume_writing() may be called. + 'b'_protocol_paused'u'_protocol_paused'b'_high_water'u'_high_water'b'_low_water'u'_low_water'b'protocol.pause_writing() failed'u'protocol.pause_writing() failed'b'protocol.resume_writing() failed'u'protocol.resume_writing() failed'b'high ('u'high ('b') must be >= low ('u') must be >= low ('b') must be >= 0'u') must be >= 0'u'asyncio.transports'u'transports'A socket-like wrapper for exposing real transport sockets. + + These objects can be safely returned by APIs like + `transport.get_extra_info('socket')`. All potentially disruptive + operations (like "socket.close()") are banned. + _naUsing on sockets returned from get_extra_info('socket') will be prohibited in asyncio 3.9. Please report your use case to bugs.python.org." on sockets returned from get_extra_info('socket') ""will be prohibited in asyncio 3.9. Please report your use case ""to bugs.python.org." NoReturn: + raise Exception('no way') + + This type is invalid in other positions, e.g., ``List[NoReturn]`` + will fail in static type checkers. + Special type construct to mark class variables. + + An annotation wrapped in ClassVar indicates that a given + attribute is intended to be used as a class variable and + should not be set on instances of that class. Usage:: + + class Starship: + stats: ClassVar[Dict[str, int]] = {} # class variable + damage: int = 10 # instance variable + + ClassVar accepts only types and cannot be further subscribed. + + Note that ClassVar is not a class itself, and should not + be used with isinstance() or issubclass(). + Special typing construct to indicate final names to type checkers. + + A final name cannot be re-assigned or overridden in a subclass. + For example: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties. + Union type; Union[X, Y] means either X or Y. + + To define a union, use e.g. Union[int, str]. Details: + - The arguments must be types and there must be at least one. + - None as an argument is a special case and is replaced by + type(None). + - Unions of unions are flattened, e.g.:: + + Union[Union[int, str], float] == Union[int, str, float] + + - Unions of a single argument vanish, e.g.:: + + Union[int] == int # The constructor actually returns int + + - Redundant arguments are skipped, e.g.:: + + Union[int, str, int] == Union[int, str] + + - When comparing unions, the argument order is ignored, e.g.:: + + Union[int, str] == Union[str, int] + + - You cannot subclass or instantiate a union. + - You can use Optional[X] as a shorthand for Union[X, None]. + Optional type. + + Optional[X] is equivalent to Union[X, None]. + Special typing form to define literal types (a.k.a. value types). + + This form can be used to indicate to type checkers that the corresponding + variable or function parameter has a value equivalent to the provided + literal (or one of several literals): + + def validate_simple(data: Any) -> Literal[True]: # always returns True + ... + + MODE = Literal['r', 'rb', 'w', 'wb'] + def open_helper(file: str, mode: MODE) -> str: + ... + + open_helper('/some/path', 'r') # Passes type check + open_helper('/other/path', 'typo') # Error in type checker + + Literal[...] cannot be subclassed. At runtime, an arbitrary value + is allowed as type argument to Literal[...], but type checkers may + impose restrictions. + Internal wrapper to hold a forward reference.__forward_arg____forward_code____forward_evaluated____forward_value____forward_is_argument__Forward reference must be a string -- got Forward reference must be an expression -- got Forward references must evaluate to types.ForwardRef(Type variable. + + Usage:: + + T = TypeVar('T') # Can be anything + A = TypeVar('A', str, bytes) # Must be str or bytes + + Type variables exist primarily for the benefit of static type + checkers. They serve as the parameters for generic types as well + as for generic function definitions. See class Generic for more + information on generic types. Generic functions work as follows: + + def repeat(x: T, n: int) -> List[T]: + '''Return a list containing n references to x.''' + return [x]*n + + def longest(x: A, y: A) -> A: + '''Return the longest of two strings.''' + return x if len(x) >= len(y) else y + + The latter example's signature is essentially the overloading + of (str, str) -> str and (bytes, bytes) -> bytes. Also note + that if the arguments are instances of some subclass of str, + the return type is still plain str. + + At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. + + Type variables defined with covariant=True or contravariant=True + can be used to declare covariant or contravariant generic types. + See PEP 484 for more details. By default generic types are invariant + in all type variables. + + Type variables can be introspected. e.g.: + + T.__name__ == 'T' + T.__constraints__ == () + T.__covariant__ == False + T.__contravariant__ = False + A.__constraints__ == (str, bytes) + + Note that only type variables defined in global scope can be pickled. + __bound____constraints____covariant____contravariant__constraintscovariantcontravariantBivariant types are not supported.Constraints cannot be combined with bound=...A single constraint is not allowedTypeVar(name, constraint, ...): constraints must be types.Bound must be a type.def_mod_normalize_aliasThe central part of internal API. + + This represents a generic version of type 'origin' with type arguments 'params'. + There are two kind of these aliases: user defined and special. The special ones + are wrappers around builtin collections and ABCs in collections.abc. These must + have 'name' always set. If 'inst' is False, then the alias can't be instantiated, + this is used by e.g. typing.List and typing.Dict. + _TypingEllipsis_TypingEmptyCannot subscript already-subscripted Parameters to generic types must be types.typing.Callabletyping.Callable[['typing.Callable''[['], '], 'Type cannot be instantiated; use " cannot be instantiated; ""use "() instead__orig_class__Subscripted generics cannot be used with class and instance checks"Subscripted generics cannot be used with"" class and instance checks"_VariadicGenericAliasSame as _GenericAlias above but for variadic aliases. Currently, + this is used only by special internal aliases: Tuple and Callable. + __getitem_inner__Callable must be used as Callable[[arg, ...], result]."Callable must be used as ""Callable[[arg, ...], result]."Callable[args, result]: args must be a list. Got "Callable[args, result]: args must be a list."" Got "Tuple[t, ...]: t must be a type.Tuple[t0, t1, ...]: each t must be a type.Callable[args, result]: result must be a type.Callable[[arg, ...], result]: each arg must be a type.Abstract base class for generic types. + + A generic type is typically declared by inheriting from + this class parameterized with one or more type variables. + For example, a generic mapping type might be defined as:: + + class Mapping(Generic[KT, VT]): + def __getitem__(self, key: KT) -> VT: + ... + # Etc. + + This class can then be used as follows:: + + def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: + try: + return mapping[key] + except KeyError: + return default + _is_protocol cannot be instantiated; it can be used only as a base class"it can be used only as a base class"Parameter list to [...] cannot be emptyParameters to [...] must all be type variables[...] must all be uniqueCannot inherit from plain GenericgvarsCannot inherit from Generic[...] multiple types.tvarsetgvarsets_varss_argsSome type variables () are not listed in Generic[") are"" not listed in Generic["Internal placeholder for () or []. Used by TupleMeta and CallableMeta + to allow empty list/tuple in specific places, without allowing them + to sneak in where prohibited. + Internal placeholder for ... (ellipsis)._is_runtime_protocol_TYPING_INTERNALS_SPECIAL_NAMES_MutableMapping__markerEXCLUDED_ATTRIBUTES_get_protocol_attrsCollect protocol members from a protocol class objects. + + This includes names actually defined in the class dictionary, as well + as names that appear in annotations. Special names (above) are skipped. + _is_callable_members_only_no_initProtocols cannot be instantiated_allow_reckless_class_cheksAllow instnance and class checks for special stdlib modules. + + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + _PROTO_WHITELIST_ProtocolMetaBase class for protocol classes. + + Protocol classes are defined as:: + + class Proto(Protocol): + def meth(self) -> int: + ... + + Such classes are primarily used with static type checkers that recognize + structural subtyping (static duck-typing), for example:: + + class C: + def meth(self) -> int: + return 0 + + def func(x: Proto) -> int: + return x.meth() + + func(C()) # Passes static type check + + See PEP 544 for details. Protocol classes decorated with + @typing.runtime_checkable act as simple-minded runtime protocols that check + only the presence of given attributes, ignoring their type signatures. + Protocol classes can be generic, they are defined as:: + + class GenProto(Protocol[T]): + def meth(self) -> T: + ... + _proto_hookInstance and class checks can only be used with @runtime_checkable protocols"Instance and class checks can only be used with"" @runtime_checkable protocols"Protocols with non-method members don't support issubclass()"Protocols with non-method members"" don't support issubclass()"Protocols can only inherit from other protocols, got %r'Protocols can only inherit from other'' protocols, got %r'Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + @runtime_checkable can be only applied to protocol classes, got %r'@runtime_checkable can be only applied to protocol classes,'' got %r'Cast a value to a type. + + This returns the value unchanged. To the type checker this + signals that the return value has the designated type, but at + runtime we intentionally don't check anything (we want this + to be as fast as possible). + _get_defaultsInternal helper to extract the default arguments, by name.pos_offset_allowed_typesReturn type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, and if necessary + adds Optional[t] if a default value equal to None is set. + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + __no_type_check__hintsbase_globalsnsobj{!r} is not a module, class, method, or function.'{!r} is not a module, class, method, ''or function.'Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar. + Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + Decorator to indicate that annotations are not type hints. + + The argument must be a class or function; if it is a class, it + applies recursively to all methods and classes defined in that class + (but not to methods defined in its superclasses or subclasses). + + This mutates the function(s) or class(es) in place. + arg_attrsDecorator to give another decorator the @no_type_check effect. + + This wraps the decorator with something that wraps the decorated + function in @no_type_check. + wrapped_decorator_overload_dummyHelper for @overload to raise when called.You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed."You should not call an overloaded function. ""A series of @overload-decorated functions ""outside a stub module should always be followed ""by an implementation that is not @overload-ed."Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + A decorator to indicate final methods and final classes. + + Use this decorator to indicate to type checkers that the decorated + method cannot be overridden, and decorated class cannot be subclassed. + For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. + KTVTT_coV_coVT_coT_contraCT_co_aliasCallable type; Callable[[int], str] is a function of (int) -> str. + + The subscription syntax must always be used with exactly two + values: the argument list and the return type. The argument list + must be a list of types or ellipsis; the return type must be a single type. + + There is no syntax to indicate optional or keyword arguments, + such function types are rarely used as callback types. + Tuple type; Tuple[X, Y] is the cross-product type of X and Y. + + Example: Tuple[T1, T2] is a tuple of two elements corresponding + to type variables T1 and T2. Tuple[int, float, str] is a tuple + of an int, a float and a string. + + To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. + A special construct usable to annotate class objects. + + For example, suppose we have the following classes:: + + class User: ... # Abstract base for User classes + class BasicUser(User): ... + class ProUser(User): ... + class TeamUser(User): ... + + And a function that takes a class argument that's a subclass of + User and returns an instance of the corresponding class:: + + U = TypeVar('U', bound=User) + def new_user(user_class: Type[U]) -> U: + user = user_class() + # (Here we could write the user object to a database) + return user + + joe = new_user(BasicUser) + + At this point the type checker knows that joe has type BasicUser. + An ABC with one abstract method __int__.An ABC with one abstract method __float__.An ABC with one abstract method __complex__.An ABC with one abstract method __bytes__.An ABC with one abstract method __index__.An ABC with one abstract method __abs__ that is covariant in its return type.An ABC with one abstract method __round__ that is covariant in its return type._make_nmtupleNamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a typenm_tpl_field_types_source_prohibitedNamedTupleMetadefaults_dictNon-default namedtuple field {field_name} cannot follow default field(s) {default_names}"Non-default namedtuple field {field_name} cannot ""follow default field(s) {default_names}"default_namesCannot overwrite NamedTuple attribute Typed version of namedtuple. + + Usage in Python versions >= 3.6:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + Alternative equivalent keyword syntax is also accepted:: + + Employee = NamedTuple('Employee', name=str, id=int) + + In Python versions <= 3.5 use:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + NamedTuple.__new__(): not enough argumentsPassing 'typename' as keyword argument is deprecatedNamedTuple.__new__() missing 1 required positional argument: 'typename'"NamedTuple.__new__() missing 1 required positional ""argument: 'typename'"NamedTuple.__new__() takes from 2 to 3 positional arguments but 'NamedTuple.__new__() takes from 2 to 3 ''positional arguments but ' were given'were given'Passing 'fields' as keyword argument is deprecatedEither list of fields or keywords can be provided to NamedTuple, not both"Either list of fields or keywords"" can be provided to NamedTuple, not both"($cls, typename, fields=None, /, **kwargs)_dict_new_typeddict_newTypedDict takes either a dict or keyword arguments, but not both"TypedDict takes either a dict or keyword arguments,"" but not both"__total___TypedDictMeta_check_failsTypedDict does not support instance and class checksCreate new typed dict class object. + + This method is called directly when TypedDict is subclassed, + or via _typeddict_new when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries + via _dict_new. + tp_dictannsTypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a typeA simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type that expects all of its + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime but is only enforced by type checkers. + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via Point2D.__annotations__. TypedDict + supports two additional equivalent forms:: + + Point2D = TypedDict('Point2D', x=int, y=int, label=str) + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality. + Usage:: + + class point2D(TypedDict, total=False): + x: int + y: int + + This means that a point2D TypedDict can have any of the keys omitted.A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The class syntax is only supported in Python 3.6+, while two other + syntax forms work for Python 2.7 and 3.2+ + NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy function that simply returns its argument. Usage:: + + UserId = NewType('UserId', int) + + def name_by_id(user_id: UserId) -> str: + ... + + UserId('user') # Fails type check + + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + + num = UserId(5) + 1 # type: int + new_type__supertype__IOGeneric base class for TextIO and BinaryIO. + + This is an abstract, generic version of the return of open(). + + NOTE: This does not distinguish between the different possible + classes (text vs. binary, read vs. write vs. read/write, + append-only, unbuffered). The TextIO and BinaryIO subclasses + below capture the distinctions between text vs. binary, which is + pervasive in the interface; however we currently do not offer a + way to track the other distinctions in the type system. + IO[AnyStr]BinaryIOTyped version of the return of open() in binary mode.TextIOTyped version of the return of open() in text mode.Wrapper namespace for IO generic classes..ioWrapper namespace for re type aliases..re# Avoid confusion with the re we export.# Please keep __all__ alphabetized within each category.# Super-special typing primitives.# ABCs (from collections.abc).# collections.abc.Set.# Structural checks, a.k.a. protocols.# Concrete collection types.# Not really a type.# One-off things.# The pseudo-submodules 're' and 'io' are part of the public# namespace, but excluded from __all__ because they might stomp on# legitimate imports of those modules.# Flatten out Union[Union[...], ...].# Weed out strict duplicates, preserving the first of each occurrence.# All real errors (not unhashable args) are raised below.# Close enough.# There is no '_type_check' call because arguments to Literal[...] are# values, not types.# for pickling# Special typing constructs Union, Optional, Generic, Callable and Tuple# use three special attributes for internal bookkeeping of generic types:# * __parameters__ is a tuple of unique free type parameters of a generic# type, for example, Dict[T, T].__parameters__ == (T,);# * __origin__ keeps a reference to a type that was subscripted,# e.g., Union[T, int].__origin__ == Union, or the non-generic version of# the type.# * __args__ is a tuple of all arguments used in subscripting,# e.g., Dict[T, int].__args__ == (T, int).# Mapping from non-generic type names that have a generic alias in typing# but with a different name.# This is not documented.# Can't subscript Generic[...] or Protocol[...].# We don't copy self._special.# generic version of an ABC or built-in class# We are careful for copy and pickle.# Also for simplicity we just don't relay all dunder names# Generic and Protocol can only be subscripted with unique type variables.# Subscripting a regular Generic subclass.# Look for Generic[T1, ..., Tn].# If found, tvars must be a subset of it.# If not found, tvars is it.# Also check for and reject plain Generic,# and reject multiple Generic[...].# These special attributes will be not collected as protocol members.# without object# PEP 544 prohibits using issubclass() with protocols that have non-method members.# For platforms without _getframe().# This metaclass is really unfortunate and exists only because of# the lack of __instancehook__.# We need this method for situations where attributes are# assigned in __init__.# All *methods* can be blocked by setting them to None.# Determine if this is a protocol or a concrete subclass.# Set (or override) the protocol subclass hook.# First, perform various sanity checks.# Same error message as for issubclass(1, int).# Second, perform the actual structural compatibility check.# Check if the members appears in the class dictionary...# ...or in annotations, if it is a sub-protocol.# We have nothing more to do for non-protocols...# ... otherwise check consistency of bases, and prohibit instantiation.# Some built-in functions don't have __code__, __defaults__, etc.# Classes require a special treatment.# Find globalns for the unwrapped object.# Return empty annotations for something that _could_ have them.# built-in classes# Some unconstrained type variables. These are used by the container types.# (These are not for export.)# Any type.# Key type.# Value type.# Any type covariant containers.# Value type covariant containers.# Ditto contravariant.# Internal type variable used for Type[].# A useful type variable with constraints. This represents string types.# (This one *is* for export!)# Various ABCs mimicking those in collections.abc.# Not generic.# NOTE: Mapping is only covariant in the value type.# Not generic# Prior to PEP 526, only _field_types attribute was assigned.# Now __annotations__ are used and _field_types is deprecated (remove in 3.9)# attributes prohibited to set in NamedTuple class syntax# update from user namespace without overriding special namedtuple attributes# allow the "cls" keyword be passed# allow the "typename" keyword be passed# allow the "fields" keyword be passed# Setting correct module is necessary to make typed dict classes pickleable.# Typed dicts are only for static structural subtyping.# Python-version-specific alias (Python 2: unicode; Python 3: str)# Constant that's True when type checking, but False here.b' +The typing module: Support for gradual typing as defined by PEP 484. + +At large scale, the structure of the module is following: +* Imports and exports, all public names should be explicitly added to __all__. +* Internal helper functions: these should never be used in code outside this module. +* _SpecialForm and its instances (special forms): Any, NoReturn, ClassVar, Union, Optional +* Two classes whose instances can be type arguments in addition to types: ForwardRef and TypeVar +* The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is + currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str], + etc., are instances of either of these classes. +* The public counterpart of the generics API consists of two classes: Generic and Protocol. +* Public helper functions: get_type_hints, overload, cast, no_type_check, + no_type_check_decorator. +* Generic aliases for collections.abc ABCs and few additional protocols. +* Special types: NewType, NamedTuple, TypedDict. +* Wrapper submodules for re and io related types. +'u' +The typing module: Support for gradual typing as defined by PEP 484. + +At large scale, the structure of the module is following: +* Imports and exports, all public names should be explicitly added to __all__. +* Internal helper functions: these should never be used in code outside this module. +* _SpecialForm and its instances (special forms): Any, NoReturn, ClassVar, Union, Optional +* Two classes whose instances can be type arguments in addition to types: ForwardRef and TypeVar +* The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is + currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str], + etc., are instances of either of these classes. +* The public counterpart of the generics API consists of two classes: Generic and Protocol. +* Public helper functions: get_type_hints, overload, cast, no_type_check, + no_type_check_decorator. +* Generic aliases for collections.abc ABCs and few additional protocols. +* Special types: NewType, NamedTuple, TypedDict. +* Wrapper submodules for re and io related types. +'b'Any'u'Any'b'ClassVar'u'ClassVar'b'Final'u'Final'b'ForwardRef'u'ForwardRef'b'Generic'u'Generic'b'Literal'u'Literal'b'Optional'u'Optional'b'Tuple'u'Tuple'b'Type'u'Type'b'TypeVar'u'TypeVar'b'Union'u'Union'b'AbstractSet'u'AbstractSet'b'ContextManager'u'ContextManager'b'AsyncContextManager'u'AsyncContextManager'b'SupportsAbs'u'SupportsAbs'b'SupportsBytes'u'SupportsBytes'b'SupportsComplex'u'SupportsComplex'b'SupportsFloat'u'SupportsFloat'b'SupportsIndex'u'SupportsIndex'b'SupportsInt'u'SupportsInt'b'SupportsRound'u'SupportsRound'b'Deque'u'Deque'b'Dict'u'Dict'b'DefaultDict'u'DefaultDict'b'List'u'List'b'FrozenSet'u'FrozenSet'b'NamedTuple'u'NamedTuple'b'TypedDict'u'TypedDict'b'AnyStr'u'AnyStr'b'cast'u'cast'b'get_args'u'get_args'b'get_origin'u'get_origin'b'get_type_hints'u'get_type_hints'b'NewType'u'NewType'b'no_type_check'u'no_type_check'b'no_type_check_decorator'u'no_type_check_decorator'b'NoReturn'u'NoReturn'b'overload'u'overload'b'runtime_checkable'u'runtime_checkable'b'Text'u'Text'b'TYPE_CHECKING'u'TYPE_CHECKING'b'Check that the argument is a type, and return it (internal helper). + + As a special case, accept None and return type(None) instead. Also wrap strings + into ForwardRef instances. Consider several corner cases, for example plain + special forms like Union are not valid, while Union[int, str] is OK, etc. + The msg argument is a human-readable error message, e.g:: + + "Union[arg, ...]: arg should be a type." + + We append the repr() of the actual value (truncated to 100 chars). + 'u'Check that the argument is a type, and return it (internal helper). + + As a special case, accept None and return type(None) instead. Also wrap strings + into ForwardRef instances. Consider several corner cases, for example plain + special forms like Union are not valid, while Union[int, str] is OK, etc. + The msg argument is a human-readable error message, e.g:: + + "Union[arg, ...]: arg should be a type." + + We append the repr() of the actual value (truncated to 100 chars). + 'b' is not valid as type argument'u' is not valid as type argument'b'Plain 'u'Plain 'b' Got 'u' Got 'b'Return the repr() of an object, special-casing types (internal helper). + + If obj is a type, we return a shorter version than the default + type.__repr__, based on the module and qualified name, which is + typically enough to uniquely identify a type. For everything + else, we fall back on repr(obj). + 'u'Return the repr() of an object, special-casing types (internal helper). + + If obj is a type, we return a shorter version than the default + type.__repr__, based on the module and qualified name, which is + typically enough to uniquely identify a type. For everything + else, we fall back on repr(obj). + 'b'Collect all type variable contained in types in order of + first appearance (lexicographic order). For example:: + + _collect_type_vars((T, List[S, T])) == (T, S) + 'u'Collect all type variable contained in types in order of + first appearance (lexicographic order). For example:: + + _collect_type_vars((T, List[S, T])) == (T, S) + 'b'Substitute type variables 'tvars' with substitutions 'subs'. + These two must have the same length. + 'u'Substitute type variables 'tvars' with substitutions 'subs'. + These two must have the same length. + 'b'Check correct count for parameters of a generic cls (internal helper). + This gives a nice error message in case of count mismatch. + 'u'Check correct count for parameters of a generic cls (internal helper). + This gives a nice error message in case of count mismatch. + 'b' is not a generic class'u' is not a generic class'b'Too 'u'Too 'b'many'u'many'b'few'u'few'b' parameters for 'u' parameters for 'b'; actual 'u'; actual 'b', expected 'u', expected 'b'An internal helper for Union creation and substitution: flatten Unions + among parameters, then remove duplicates. + 'u'An internal helper for Union creation and substitution: flatten Unions + among parameters, then remove duplicates. + 'b'Internal wrapper caching __getitem__ of generic types with a fallback to + original function for non-hashable arguments. + 'u'Internal wrapper caching __getitem__ of generic types with a fallback to + original function for non-hashable arguments. + 'b'Evaluate all forward references in the given type t. + For use of globalns and localns see the docstring for get_type_hints(). + 'u'Evaluate all forward references in the given type t. + For use of globalns and localns see the docstring for get_type_hints(). + 'b'Mixin to prohibit subclassing'u'Mixin to prohibit subclassing'b'_root'u'_root'b'Cannot subclass special typing classes'u'Cannot subclass special typing classes'b'Mixin to indicate that object should not be copied.'u'Mixin to indicate that object should not be copied.'b'Internal indicator of special typing constructs. + See _doc instance attribute for specific docs. + 'u'Internal indicator of special typing constructs. + See _doc instance attribute for specific docs. + 'b'_doc'u'_doc'b'Constructor. + + This only exists to give a better error message in case + someone tries to subclass a special typing object (not a good idea). + 'u'Constructor. + + This only exists to give a better error message in case + someone tries to subclass a special typing object (not a good idea). + 'b'Cannot subclass 'u'Cannot subclass 'b'Cannot instantiate 'u'Cannot instantiate 'b' cannot be used with isinstance()'u' cannot be used with isinstance()'b' cannot be used with issubclass()'u' cannot be used with issubclass()'b' accepts only single type.'u' accepts only single type.'b'Cannot take a Union of no types.'u'Cannot take a Union of no types.'b'Union[arg, ...]: each arg must be a type.'u'Union[arg, ...]: each arg must be a type.'b'Optional[t] requires a single type.'u'Optional[t] requires a single type.'b' is not subscriptable'u' is not subscriptable'b'Special type indicating an unconstrained type. + + - Any is compatible with every type. + - Any assumed to have all methods. + - All values assumed to be instances of Any. + + Note that all the above statements are true from the point of view of + static type checkers. At runtime, Any should not be used with instance + or class checks. + 'u'Special type indicating an unconstrained type. + + - Any is compatible with every type. + - Any assumed to have all methods. + - All values assumed to be instances of Any. + + Note that all the above statements are true from the point of view of + static type checkers. At runtime, Any should not be used with instance + or class checks. + 'b'Special type indicating functions that never return. + Example:: + + from typing import NoReturn + + def stop() -> NoReturn: + raise Exception('no way') + + This type is invalid in other positions, e.g., ``List[NoReturn]`` + will fail in static type checkers. + 'u'Special type indicating functions that never return. + Example:: + + from typing import NoReturn + + def stop() -> NoReturn: + raise Exception('no way') + + This type is invalid in other positions, e.g., ``List[NoReturn]`` + will fail in static type checkers. + 'b'Special type construct to mark class variables. + + An annotation wrapped in ClassVar indicates that a given + attribute is intended to be used as a class variable and + should not be set on instances of that class. Usage:: + + class Starship: + stats: ClassVar[Dict[str, int]] = {} # class variable + damage: int = 10 # instance variable + + ClassVar accepts only types and cannot be further subscribed. + + Note that ClassVar is not a class itself, and should not + be used with isinstance() or issubclass(). + 'u'Special type construct to mark class variables. + + An annotation wrapped in ClassVar indicates that a given + attribute is intended to be used as a class variable and + should not be set on instances of that class. Usage:: + + class Starship: + stats: ClassVar[Dict[str, int]] = {} # class variable + damage: int = 10 # instance variable + + ClassVar accepts only types and cannot be further subscribed. + + Note that ClassVar is not a class itself, and should not + be used with isinstance() or issubclass(). + 'b'Special typing construct to indicate final names to type checkers. + + A final name cannot be re-assigned or overridden in a subclass. + For example: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties. + 'u'Special typing construct to indicate final names to type checkers. + + A final name cannot be re-assigned or overridden in a subclass. + For example: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties. + 'b'Union type; Union[X, Y] means either X or Y. + + To define a union, use e.g. Union[int, str]. Details: + - The arguments must be types and there must be at least one. + - None as an argument is a special case and is replaced by + type(None). + - Unions of unions are flattened, e.g.:: + + Union[Union[int, str], float] == Union[int, str, float] + + - Unions of a single argument vanish, e.g.:: + + Union[int] == int # The constructor actually returns int + + - Redundant arguments are skipped, e.g.:: + + Union[int, str, int] == Union[int, str] + + - When comparing unions, the argument order is ignored, e.g.:: + + Union[int, str] == Union[str, int] + + - You cannot subclass or instantiate a union. + - You can use Optional[X] as a shorthand for Union[X, None]. + 'u'Union type; Union[X, Y] means either X or Y. + + To define a union, use e.g. Union[int, str]. Details: + - The arguments must be types and there must be at least one. + - None as an argument is a special case and is replaced by + type(None). + - Unions of unions are flattened, e.g.:: + + Union[Union[int, str], float] == Union[int, str, float] + + - Unions of a single argument vanish, e.g.:: + + Union[int] == int # The constructor actually returns int + + - Redundant arguments are skipped, e.g.:: + + Union[int, str, int] == Union[int, str] + + - When comparing unions, the argument order is ignored, e.g.:: + + Union[int, str] == Union[str, int] + + - You cannot subclass or instantiate a union. + - You can use Optional[X] as a shorthand for Union[X, None]. + 'b'Optional type. + + Optional[X] is equivalent to Union[X, None]. + 'u'Optional type. + + Optional[X] is equivalent to Union[X, None]. + 'b'Special typing form to define literal types (a.k.a. value types). + + This form can be used to indicate to type checkers that the corresponding + variable or function parameter has a value equivalent to the provided + literal (or one of several literals): + + def validate_simple(data: Any) -> Literal[True]: # always returns True + ... + + MODE = Literal['r', 'rb', 'w', 'wb'] + def open_helper(file: str, mode: MODE) -> str: + ... + + open_helper('/some/path', 'r') # Passes type check + open_helper('/other/path', 'typo') # Error in type checker + + Literal[...] cannot be subclassed. At runtime, an arbitrary value + is allowed as type argument to Literal[...], but type checkers may + impose restrictions. + 'u'Special typing form to define literal types (a.k.a. value types). + + This form can be used to indicate to type checkers that the corresponding + variable or function parameter has a value equivalent to the provided + literal (or one of several literals): + + def validate_simple(data: Any) -> Literal[True]: # always returns True + ... + + MODE = Literal['r', 'rb', 'w', 'wb'] + def open_helper(file: str, mode: MODE) -> str: + ... + + open_helper('/some/path', 'r') # Passes type check + open_helper('/other/path', 'typo') # Error in type checker + + Literal[...] cannot be subclassed. At runtime, an arbitrary value + is allowed as type argument to Literal[...], but type checkers may + impose restrictions. + 'b'Internal wrapper to hold a forward reference.'u'Internal wrapper to hold a forward reference.'b'__forward_arg__'u'__forward_arg__'b'__forward_code__'u'__forward_code__'b'__forward_evaluated__'u'__forward_evaluated__'b'__forward_value__'u'__forward_value__'b'__forward_is_argument__'u'__forward_is_argument__'b'Forward reference must be a string -- got 'u'Forward reference must be a string -- got 'b'Forward reference must be an expression -- got 'u'Forward reference must be an expression -- got 'b'Forward references must evaluate to types.'u'Forward references must evaluate to types.'b'ForwardRef('u'ForwardRef('b'Type variable. + + Usage:: + + T = TypeVar('T') # Can be anything + A = TypeVar('A', str, bytes) # Must be str or bytes + + Type variables exist primarily for the benefit of static type + checkers. They serve as the parameters for generic types as well + as for generic function definitions. See class Generic for more + information on generic types. Generic functions work as follows: + + def repeat(x: T, n: int) -> List[T]: + '''Return a list containing n references to x.''' + return [x]*n + + def longest(x: A, y: A) -> A: + '''Return the longest of two strings.''' + return x if len(x) >= len(y) else y + + The latter example's signature is essentially the overloading + of (str, str) -> str and (bytes, bytes) -> bytes. Also note + that if the arguments are instances of some subclass of str, + the return type is still plain str. + + At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. + + Type variables defined with covariant=True or contravariant=True + can be used to declare covariant or contravariant generic types. + See PEP 484 for more details. By default generic types are invariant + in all type variables. + + Type variables can be introspected. e.g.: + + T.__name__ == 'T' + T.__constraints__ == () + T.__covariant__ == False + T.__contravariant__ = False + A.__constraints__ == (str, bytes) + + Note that only type variables defined in global scope can be pickled. + 'u'Type variable. + + Usage:: + + T = TypeVar('T') # Can be anything + A = TypeVar('A', str, bytes) # Must be str or bytes + + Type variables exist primarily for the benefit of static type + checkers. They serve as the parameters for generic types as well + as for generic function definitions. See class Generic for more + information on generic types. Generic functions work as follows: + + def repeat(x: T, n: int) -> List[T]: + '''Return a list containing n references to x.''' + return [x]*n + + def longest(x: A, y: A) -> A: + '''Return the longest of two strings.''' + return x if len(x) >= len(y) else y + + The latter example's signature is essentially the overloading + of (str, str) -> str and (bytes, bytes) -> bytes. Also note + that if the arguments are instances of some subclass of str, + the return type is still plain str. + + At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. + + Type variables defined with covariant=True or contravariant=True + can be used to declare covariant or contravariant generic types. + See PEP 484 for more details. By default generic types are invariant + in all type variables. + + Type variables can be introspected. e.g.: + + T.__name__ == 'T' + T.__constraints__ == () + T.__covariant__ == False + T.__contravariant__ = False + A.__constraints__ == (str, bytes) + + Note that only type variables defined in global scope can be pickled. + 'b'__bound__'u'__bound__'b'__constraints__'u'__constraints__'b'__covariant__'u'__covariant__'b'__contravariant__'u'__contravariant__'b'Bivariant types are not supported.'u'Bivariant types are not supported.'b'Constraints cannot be combined with bound=...'u'Constraints cannot be combined with bound=...'b'A single constraint is not allowed'u'A single constraint is not allowed'b'TypeVar(name, constraint, ...): constraints must be types.'u'TypeVar(name, constraint, ...): constraints must be types.'b'Bound must be a type.'u'Bound must be a type.'b'frozenset'u'frozenset'b'The central part of internal API. + + This represents a generic version of type 'origin' with type arguments 'params'. + There are two kind of these aliases: user defined and special. The special ones + are wrappers around builtin collections and ABCs in collections.abc. These must + have 'name' always set. If 'inst' is False, then the alias can't be instantiated, + this is used by e.g. typing.List and typing.Dict. + 'u'The central part of internal API. + + This represents a generic version of type 'origin' with type arguments 'params'. + There are two kind of these aliases: user defined and special. The special ones + are wrappers around builtin collections and ABCs in collections.abc. These must + have 'name' always set. If 'inst' is False, then the alias can't be instantiated, + this is used by e.g. typing.List and typing.Dict. + 'b'Cannot subscript already-subscripted 'u'Cannot subscript already-subscripted 'b'Parameters to generic types must be types.'u'Parameters to generic types must be types.'b'typing.Callable'u'typing.Callable'b'typing.Callable[['u'typing.Callable[['b'], 'u'], 'b'Type 'u'Type 'b' cannot be instantiated; use 'u' cannot be instantiated; use 'b'() instead'u'() instead'b'__origin__'u'__origin__'b'_inst'u'_inst'b'_special'u'_special'b'Subscripted generics cannot be used with class and instance checks'u'Subscripted generics cannot be used with class and instance checks'b'Same as _GenericAlias above but for variadic aliases. Currently, + this is used only by special internal aliases: Tuple and Callable. + 'u'Same as _GenericAlias above but for variadic aliases. Currently, + this is used only by special internal aliases: Tuple and Callable. + 'b'Callable must be used as Callable[[arg, ...], result].'u'Callable must be used as Callable[[arg, ...], result].'b'Callable[args, result]: args must be a list. Got 'u'Callable[args, result]: args must be a list. Got 'b'Tuple[t, ...]: t must be a type.'u'Tuple[t, ...]: t must be a type.'b'Tuple[t0, t1, ...]: each t must be a type.'u'Tuple[t0, t1, ...]: each t must be a type.'b'Callable[args, result]: result must be a type.'u'Callable[args, result]: result must be a type.'b'Callable[[arg, ...], result]: each arg must be a type.'u'Callable[[arg, ...], result]: each arg must be a type.'b'Abstract base class for generic types. + + A generic type is typically declared by inheriting from + this class parameterized with one or more type variables. + For example, a generic mapping type might be defined as:: + + class Mapping(Generic[KT, VT]): + def __getitem__(self, key: KT) -> VT: + ... + # Etc. + + This class can then be used as follows:: + + def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: + try: + return mapping[key] + except KeyError: + return default + 'u'Abstract base class for generic types. + + A generic type is typically declared by inheriting from + this class parameterized with one or more type variables. + For example, a generic mapping type might be defined as:: + + class Mapping(Generic[KT, VT]): + def __getitem__(self, key: KT) -> VT: + ... + # Etc. + + This class can then be used as follows:: + + def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: + try: + return mapping[key] + except KeyError: + return default + 'b' cannot be instantiated; it can be used only as a base class'u' cannot be instantiated; it can be used only as a base class'b'Parameter list to 'u'Parameter list to 'b'[...] cannot be empty'u'[...] cannot be empty'b'Parameters to 'u'Parameters to 'b'[...] must all be type variables'u'[...] must all be type variables'b'[...] must all be unique'u'[...] must all be unique'b'Cannot inherit from plain Generic'u'Cannot inherit from plain Generic'b'Cannot inherit from Generic[...] multiple types.'u'Cannot inherit from Generic[...] multiple types.'b'Some type variables ('u'Some type variables ('b') are not listed in Generic['u') are not listed in Generic['b'Internal placeholder for () or []. Used by TupleMeta and CallableMeta + to allow empty list/tuple in specific places, without allowing them + to sneak in where prohibited. + 'u'Internal placeholder for () or []. Used by TupleMeta and CallableMeta + to allow empty list/tuple in specific places, without allowing them + to sneak in where prohibited. + 'b'Internal placeholder for ... (ellipsis).'u'Internal placeholder for ... (ellipsis).'b'__parameters__'u'__parameters__'b'__orig_class__'u'__orig_class__'b'_is_protocol'u'_is_protocol'b'_is_runtime_protocol'u'_is_runtime_protocol'b'__subclasshook__'u'__subclasshook__'b'_MutableMapping__marker'u'_MutableMapping__marker'b'Collect protocol members from a protocol class objects. + + This includes names actually defined in the class dictionary, as well + as names that appear in annotations. Special names (above) are skipped. + 'u'Collect protocol members from a protocol class objects. + + This includes names actually defined in the class dictionary, as well + as names that appear in annotations. Special names (above) are skipped. + 'b'Protocols cannot be instantiated'u'Protocols cannot be instantiated'b'Allow instnance and class checks for special stdlib modules. + + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + 'u'Allow instnance and class checks for special stdlib modules. + + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + 'b'contextlib'b'Base class for protocol classes. + + Protocol classes are defined as:: + + class Proto(Protocol): + def meth(self) -> int: + ... + + Such classes are primarily used with static type checkers that recognize + structural subtyping (static duck-typing), for example:: + + class C: + def meth(self) -> int: + return 0 + + def func(x: Proto) -> int: + return x.meth() + + func(C()) # Passes static type check + + See PEP 544 for details. Protocol classes decorated with + @typing.runtime_checkable act as simple-minded runtime protocols that check + only the presence of given attributes, ignoring their type signatures. + Protocol classes can be generic, they are defined as:: + + class GenProto(Protocol[T]): + def meth(self) -> T: + ... + 'u'Base class for protocol classes. + + Protocol classes are defined as:: + + class Proto(Protocol): + def meth(self) -> int: + ... + + Such classes are primarily used with static type checkers that recognize + structural subtyping (static duck-typing), for example:: + + class C: + def meth(self) -> int: + return 0 + + def func(x: Proto) -> int: + return x.meth() + + func(C()) # Passes static type check + + See PEP 544 for details. Protocol classes decorated with + @typing.runtime_checkable act as simple-minded runtime protocols that check + only the presence of given attributes, ignoring their type signatures. + Protocol classes can be generic, they are defined as:: + + class GenProto(Protocol[T]): + def meth(self) -> T: + ... + 'b'Instance and class checks can only be used with @runtime_checkable protocols'u'Instance and class checks can only be used with @runtime_checkable protocols'b'Protocols with non-method members don't support issubclass()'u'Protocols with non-method members don't support issubclass()'b'Protocols can only inherit from other protocols, got %r'u'Protocols can only inherit from other protocols, got %r'b'Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + 'u'Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + 'b'@runtime_checkable can be only applied to protocol classes, got %r'u'@runtime_checkable can be only applied to protocol classes, got %r'b'Cast a value to a type. + + This returns the value unchanged. To the type checker this + signals that the return value has the designated type, but at + runtime we intentionally don't check anything (we want this + to be as fast as possible). + 'u'Cast a value to a type. + + This returns the value unchanged. To the type checker this + signals that the return value has the designated type, but at + runtime we intentionally don't check anything (we want this + to be as fast as possible). + 'b'Internal helper to extract the default arguments, by name.'u'Internal helper to extract the default arguments, by name.'b'Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, and if necessary + adds Optional[t] if a default value equal to None is set. + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + 'u'Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, and if necessary + adds Optional[t] if a default value equal to None is set. + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + 'b'__no_type_check__'u'__no_type_check__'b'__globals__'u'__globals__'b'{!r} is not a module, class, method, or function.'u'{!r} is not a module, class, method, or function.'b'Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar. + Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + 'u'Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar. + Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + 'b'Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + 'u'Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + 'b'Decorator to indicate that annotations are not type hints. + + The argument must be a class or function; if it is a class, it + applies recursively to all methods and classes defined in that class + (but not to methods defined in its superclasses or subclasses). + + This mutates the function(s) or class(es) in place. + 'u'Decorator to indicate that annotations are not type hints. + + The argument must be a class or function; if it is a class, it + applies recursively to all methods and classes defined in that class + (but not to methods defined in its superclasses or subclasses). + + This mutates the function(s) or class(es) in place. + 'b'Decorator to give another decorator the @no_type_check effect. + + This wraps the decorator with something that wraps the decorated + function in @no_type_check. + 'u'Decorator to give another decorator the @no_type_check effect. + + This wraps the decorator with something that wraps the decorated + function in @no_type_check. + 'b'Helper for @overload to raise when called.'u'Helper for @overload to raise when called.'b'You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.'u'You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.'b'Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + 'u'Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + 'b'A decorator to indicate final methods and final classes. + + Use this decorator to indicate to type checkers that the decorated + method cannot be overridden, and decorated class cannot be subclassed. + For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. + 'u'A decorator to indicate final methods and final classes. + + Use this decorator to indicate to type checkers that the decorated + method cannot be overridden, and decorated class cannot be subclassed. + For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. + 'b'KT'u'KT'b'VT'u'VT'b'T_co'u'T_co'b'V_co'u'V_co'b'VT_co'u'VT_co'b'T_contra'u'T_contra'b'CT_co'u'CT_co'b'Callable type; Callable[[int], str] is a function of (int) -> str. + + The subscription syntax must always be used with exactly two + values: the argument list and the return type. The argument list + must be a list of types or ellipsis; the return type must be a single type. + + There is no syntax to indicate optional or keyword arguments, + such function types are rarely used as callback types. + 'u'Callable type; Callable[[int], str] is a function of (int) -> str. + + The subscription syntax must always be used with exactly two + values: the argument list and the return type. The argument list + must be a list of types or ellipsis; the return type must be a single type. + + There is no syntax to indicate optional or keyword arguments, + such function types are rarely used as callback types. + 'b'Tuple type; Tuple[X, Y] is the cross-product type of X and Y. + + Example: Tuple[T1, T2] is a tuple of two elements corresponding + to type variables T1 and T2. Tuple[int, float, str] is a tuple + of an int, a float and a string. + + To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. + 'u'Tuple type; Tuple[X, Y] is the cross-product type of X and Y. + + Example: Tuple[T1, T2] is a tuple of two elements corresponding + to type variables T1 and T2. Tuple[int, float, str] is a tuple + of an int, a float and a string. + + To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. + 'b'A special construct usable to annotate class objects. + + For example, suppose we have the following classes:: + + class User: ... # Abstract base for User classes + class BasicUser(User): ... + class ProUser(User): ... + class TeamUser(User): ... + + And a function that takes a class argument that's a subclass of + User and returns an instance of the corresponding class:: + + U = TypeVar('U', bound=User) + def new_user(user_class: Type[U]) -> U: + user = user_class() + # (Here we could write the user object to a database) + return user + + joe = new_user(BasicUser) + + At this point the type checker knows that joe has type BasicUser. + 'u'A special construct usable to annotate class objects. + + For example, suppose we have the following classes:: + + class User: ... # Abstract base for User classes + class BasicUser(User): ... + class ProUser(User): ... + class TeamUser(User): ... + + And a function that takes a class argument that's a subclass of + User and returns an instance of the corresponding class:: + + U = TypeVar('U', bound=User) + def new_user(user_class: Type[U]) -> U: + user = user_class() + # (Here we could write the user object to a database) + return user + + joe = new_user(BasicUser) + + At this point the type checker knows that joe has type BasicUser. + 'b'An ABC with one abstract method __int__.'u'An ABC with one abstract method __int__.'b'An ABC with one abstract method __float__.'u'An ABC with one abstract method __float__.'b'An ABC with one abstract method __complex__.'u'An ABC with one abstract method __complex__.'b'An ABC with one abstract method __bytes__.'u'An ABC with one abstract method __bytes__.'b'An ABC with one abstract method __index__.'u'An ABC with one abstract method __index__.'b'An ABC with one abstract method __abs__ that is covariant in its return type.'u'An ABC with one abstract method __abs__ that is covariant in its return type.'b'An ABC with one abstract method __round__ that is covariant in its return type.'u'An ABC with one abstract method __round__ that is covariant in its return type.'b'NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type'u'NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type'b'_field_types'u'_field_types'b'_source'u'_source'b'Non-default namedtuple field {field_name} cannot follow default field(s) {default_names}'u'Non-default namedtuple field {field_name} cannot follow default field(s) {default_names}'b'Cannot overwrite NamedTuple attribute 'u'Cannot overwrite NamedTuple attribute 'b'Typed version of namedtuple. + + Usage in Python versions >= 3.6:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + Alternative equivalent keyword syntax is also accepted:: + + Employee = NamedTuple('Employee', name=str, id=int) + + In Python versions <= 3.5 use:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + 'u'Typed version of namedtuple. + + Usage in Python versions >= 3.6:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + Alternative equivalent keyword syntax is also accepted:: + + Employee = NamedTuple('Employee', name=str, id=int) + + In Python versions <= 3.5 use:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + 'b'NamedTuple.__new__(): not enough arguments'u'NamedTuple.__new__(): not enough arguments'b'typename'u'typename'b'Passing 'typename' as keyword argument is deprecated'u'Passing 'typename' as keyword argument is deprecated'b'NamedTuple.__new__() missing 1 required positional argument: 'typename''u'NamedTuple.__new__() missing 1 required positional argument: 'typename''b'NamedTuple.__new__() takes from 2 to 3 positional arguments but 'u'NamedTuple.__new__() takes from 2 to 3 positional arguments but 'b' were given'u' were given'b'fields'u'fields'b'Passing 'fields' as keyword argument is deprecated'u'Passing 'fields' as keyword argument is deprecated'b'Either list of fields or keywords can be provided to NamedTuple, not both'u'Either list of fields or keywords can be provided to NamedTuple, not both'b'($cls, typename, fields=None, /, **kwargs)'u'($cls, typename, fields=None, /, **kwargs)'b'TypedDict takes either a dict or keyword arguments, but not both'u'TypedDict takes either a dict or keyword arguments, but not both'b'__total__'u'__total__'b'TypedDict does not support instance and class checks'u'TypedDict does not support instance and class checks'b'Create new typed dict class object. + + This method is called directly when TypedDict is subclassed, + or via _typeddict_new when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries + via _dict_new. + 'u'Create new typed dict class object. + + This method is called directly when TypedDict is subclassed, + or via _typeddict_new when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries + via _dict_new. + 'b'TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type'u'TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type'b'A simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type that expects all of its + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime but is only enforced by type checkers. + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via Point2D.__annotations__. TypedDict + supports two additional equivalent forms:: + + Point2D = TypedDict('Point2D', x=int, y=int, label=str) + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality. + Usage:: + + class point2D(TypedDict, total=False): + x: int + y: int + + This means that a point2D TypedDict can have any of the keys omitted.A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The class syntax is only supported in Python 3.6+, while two other + syntax forms work for Python 2.7 and 3.2+ + 'u'A simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type that expects all of its + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime but is only enforced by type checkers. + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via Point2D.__annotations__. TypedDict + supports two additional equivalent forms:: + + Point2D = TypedDict('Point2D', x=int, y=int, label=str) + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality. + Usage:: + + class point2D(TypedDict, total=False): + x: int + y: int + + This means that a point2D TypedDict can have any of the keys omitted.A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The class syntax is only supported in Python 3.6+, while two other + syntax forms work for Python 2.7 and 3.2+ + 'b'NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy function that simply returns its argument. Usage:: + + UserId = NewType('UserId', int) + + def name_by_id(user_id: UserId) -> str: + ... + + UserId('user') # Fails type check + + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + + num = UserId(5) + 1 # type: int + 'u'NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy function that simply returns its argument. Usage:: + + UserId = NewType('UserId', int) + + def name_by_id(user_id: UserId) -> str: + ... + + UserId('user') # Fails type check + + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + + num = UserId(5) + 1 # type: int + 'b'Generic base class for TextIO and BinaryIO. + + This is an abstract, generic version of the return of open(). + + NOTE: This does not distinguish between the different possible + classes (text vs. binary, read vs. write vs. read/write, + append-only, unbuffered). The TextIO and BinaryIO subclasses + below capture the distinctions between text vs. binary, which is + pervasive in the interface; however we currently do not offer a + way to track the other distinctions in the type system. + 'u'Generic base class for TextIO and BinaryIO. + + This is an abstract, generic version of the return of open(). + + NOTE: This does not distinguish between the different possible + classes (text vs. binary, read vs. write vs. read/write, + append-only, unbuffered). The TextIO and BinaryIO subclasses + below capture the distinctions between text vs. binary, which is + pervasive in the interface; however we currently do not offer a + way to track the other distinctions in the type system. + 'b'IO[AnyStr]'u'IO[AnyStr]'b'Typed version of the return of open() in binary mode.'u'Typed version of the return of open() in binary mode.'b'BinaryIO'u'BinaryIO'b'Typed version of the return of open() in text mode.'u'Typed version of the return of open() in text mode.'b'TextIO'u'TextIO'b'Wrapper namespace for IO generic classes.'u'Wrapper namespace for IO generic classes.'b'IO'u'IO'b'.io'u'.io'b'Wrapper namespace for re type aliases.'u'Wrapper namespace for re type aliases.'b'.re'u'.re'bidirectionalcombiningdecompositioneast_asian_widthis_normalizedmirroredunidata_versionunicodedata.UCDUCDu'This module provides access to the Unicode Character Database which +defines character properties for all Unicode characters. The data in +this database is based on the UnicodeData.txt file version +12.1.0 which is publicly available from ftp://ftp.unicode.org/. + +The module uses the same names and symbols as defined by the +UnicodeData File Format 12.1.0.'u'/Users/pwntester/.pyenv/versions/3.8.13/lib/python3.8/lib-dynload/unicodedata.cpython-38-darwin.so'u'unicodedata'ucd_3_2_0ucnhash_CAPIu'12.1.0'Selector event loop for Unix with signal handling.base_subprocessSelectorEventLoopAbstractChildWatcherSafeChildWatcherFastChildWatcherMultiLoopChildWatcherThreadedChildWatcherSignals are not really supported on Windows_sighandler_noopDummy signal handler._UnixSelectorEventLoopUnix event loop. + + Adds signal handling and UNIX Domain Socket support to SelectorEventLoop. + _signal_handlersClosing the loop on interpreter shutdown stage, skipping signal handlers removal"on interpreter shutdown ""stage, skipping signal handlers removal"_handle_signalAdd a handler for a signal. UNIX only. + + Raise ValueError if the signal number is invalid or uncatchable. + Raise RuntimeError if there is a problem setting up the handler. + coroutines cannot be used with add_signal_handler()"coroutines cannot be used ""with add_signal_handler()"_check_signalnexcset_wakeup_fd(-1) failed: %ssig cannot be caughtInternal helper that is the actual signal handler.Remove a handler for a signal. UNIX only. + + Return True if a signal handler was removed, False if not. + Internal helper to validate a signal. + + Raise ValueError if the signal number is invalid or uncatchable. + Raise RuntimeError if there is a problem setting up the handler. + sig must be an int, not invalid signal number _UnixReadPipeTransport_UnixWritePipeTransportis_activeasyncio.get_child_watcher() is not activated, subprocess support is not installed."asyncio.get_child_watcher() is not activated, ""subprocess support is not installed."_UnixSubprocessTransportadd_child_handler_child_watcher_callbackyou have to pass server_hostname when using sslpath and sock can not be specified at the same timeno path and sock were specifiedA UNIX Domain Stream Socket was expected, got 'Unable to check or remove stale UNIX socket ''%r: %r'Address is already in usepath was not specified, and no sock specifiedos.sendfile() is not available_sock_sendfile_native_implregistered_fd_sock_sendfile_update_filepos_sock_add_cancellation_callbacksocket is not connectedos.sendfile call failed_pipe_filenoPipe transport is for pipes/sockets only.%r was closed by peeris_charis_fifois_socketPipe transport is only for pipes, sockets and character devices"Pipe transport is only for ""pipes, sockets and character devices"bufsize=pipe closed by peer or os.write(pipe, data) raised exception.'pipe closed by peer or ''os.write(pipe, data) raised exception.'stdin_wAbstract base class for monitoring child processes. + + Objects derived from this class monitor a collection of subprocesses and + report their termination or interruption by a signal. + + New callbacks are registered with .add_child_handler(). Starting a new + process must be done within a 'with' block to allow the watcher to suspend + its activity until the new process if fully registered (this is needed to + prevent a race condition in some implementations). + + Example: + with watcher: + proc = subprocess.Popen("sleep 1") + watcher.add_child_handler(proc.pid, callback) + + Notes: + Implementations of this class must be thread-safe. + + Since child watcher objects may catch the SIGCHLD signal and call + waitpid(-1), there should be only one active object per process. + Register a new child handler. + + Arrange for callback(pid, returncode, *args) to be called when + process 'pid' terminates. Specifying another callback for the same + process replaces the previous handler. + + Note: callback() must be thread-safe. + remove_child_handlerRemoves the handler for process 'pid'. + + The function returns True if the handler was successfully removed, + False if there was nothing to remove.attach_loopAttach the watcher to an event loop. + + If the watcher was previously attached to an event loop, then it is + first detached before attaching to the new loop. + + Note: loop may be None. + Close the watcher. + + This must be called to make sure that any underlying resource is freed. + Return ``True`` if the watcher is active and is used by the event loop. + + Return True if the watcher is installed and ready to handle process exit + notifications. + + Enter the watcher's context and allow starting new processes + + This function must return selfExit the watcher's context_compute_returncodeBaseChildWatcher_do_waitpidexpected_pid_do_waitpid_allA loop is being detached from a child watcher with pending handlers'A loop is being detached ''from a child watcher with pending handlers'_sig_chldUnknown exception in SIGCHLD handler'Safe' child watcher implementation. + + This implementation avoids disrupting other code spawning processes by + polling explicitly each process in the SIGCHLD handler instead of calling + os.waitpid(-1). + + This is a safe solution but it has a significant overhead when handling a + big number of children (O(n) each time SIGCHLD is raised) + process %s exited with returncode %sUnknown child process pid %d, will report returncode 255Child watcher got an unexpected pid: %r'Fast' child watcher implementation. + + This implementation reaps every terminated processes by calling + os.waitpid(-1) directly, possibly breaking other code spawning processes + and waiting for their termination. + + There is no noticeable overhead when handling a big number of children + (O(1) each time a child terminates). + _zombies_forkscollateral_victimsCaught subprocesses termination from unknown pids: %sMust use the context managerunknown process %s exited with returncode %s'unknown process %s exited ''with returncode %s'Caught subprocess termination from unknown pid: %d -> %d"Caught subprocess termination from unknown pid: ""%d -> %d"A watcher that doesn't require running loop in the main thread. + + This implementation registers a SIGCHLD signal handler on + instantiation (which may conflict with other code that + install own handler for this signal). + + The solution is safe but it has a significant overhead when + handling a big number of processes (*O(n)* each time a + SIGCHLD is received). + _saved_sighandlerSIGCHLD handler was changed by outside codePrevious SIGCHLD handler was set by non-Python code, restore to default handler on watcher close."Previous SIGCHLD handler was set by non-Python code, ""restore to default handler on watcher close."Loop %r that handles pid %r is closedThreaded child watcher implementation. + + The watcher uses a thread per process + for waiting for the process finish. + + It doesn't require subscription on POSIX signal + but a thread creation is not free. + + The watcher has O(1) complexity, its performance doesn't depend + on amount of spawn processes. + _pid_counter_join_threadsInternal: Join all non-daemon threads has registered but not finished child processeswaitpid-_UnixDefaultEventLoopPolicyUNIX event loop policy with a watcher for child processes._watcher_init_watcherSet the event loop. + + As a side effect, if a child watcher was set before, then calling + .set_event_loop() from the main thread will call .attach_loop(loop) on + the child watcher. + Get the watcher for child processes. + + If not yet set, a ThreadedChildWatcher object is automatically created. + # ignore null bytes written by _write_to_self()# set_wakeup_fd() raises ValueError if this is not the# main thread. By calling it early we ensure that an# event loop running in another thread cannot add a signal# handler.# Register a dummy signal handler to ask Python to write the signal# number in the wakeup file descriptor. _process_self_data() will# read signal numbers from this file descriptor to handle signals.# Set SA_RESTART to limit EINTR occurrences.# Assume it's some race condition.# Remove it properly.# Check early.# Raising exception before process creation# prevents subprocess execution if the watcher# is not ready to handle it.# Check for abstract socket. `str` and `bytes` paths are supported.# Let's improve the error message by adding# with what exact address it occurs.# Remove the callback early. It should be rare that the# selector says the fd is ready but the call still returns# EAGAIN, and I am willing to take a hit in that case in# order to simplify the common case.# If we have an ENOTCONN and this isn't a first call to# sendfile(), i.e. the connection was closed in the middle# of the operation, normalize the error to ConnectionError# to make it consistent across all Posix systems.# max bytes we read in one event loop iteration# should be called by exception handler only# Set when close() or write_eof() called.# On AIX, the reader trick (to be notified when the read end of the# socket is closed) only works for sockets. On other platforms it# works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.)# Pipe was closed by peer.# Remove writer here, _fatal_error() doesn't it# because _buffer is empty.# write_eof is all what we needed to close the write pipe# Use a socket pair for stdin, since not all platforms# support selecting read events on the write end of a# socket (which we use in order to detect closing of the# other end). Notably this is needed on AIX, and works# just fine on other platforms.# The child process died because of a signal.# The child process exited (e.g sys.exit()).# The child exited, but we don't understand its status.# This shouldn't happen, but if it does, let's just# return that status; perhaps that helps debug it.# Prevent a race condition in case a child terminated# during the switch.# self._loop should always be available here# as '_sig_chld' is added as a signal handler# in 'attach_loop'# Prevent a race condition in case the child is already terminated.# The child process is already reaped# (may happen if waitpid() is called elsewhere).# The child process is still alive.# May happen if .remove_child_handler() is called# after os.waitpid() returns.# The child is running.# The child is dead already. We can fire the callback.# Because of signal coalescing, we must keep calling waitpid() as# long as we're able to reap a child.# No more child processes exist.# A child process is still alive.# unknown child# It may not be registered yet.# Implementation note:# The class keeps compatibility with AbstractChildWatcher ABC# To achieve this it has empty attach_loop() method# and doesn't accept explicit loop argument# for add_child_handler()/remove_child_handler()# but retrieves the current loop by get_running_loop()# Don't save the loop but initialize itself if called first time# The reason to do it here is that attach_loop() is called from# unix policy only for the main thread.# Main thread is required for subscription on SIGCHLD signal# asyncio never calls remove_child_handler() !!!# The method is no-op but is implemented because# abstract base classe requires itb'Selector event loop for Unix with signal handling.'u'Selector event loop for Unix with signal handling.'b'SelectorEventLoop'u'SelectorEventLoop'b'AbstractChildWatcher'u'AbstractChildWatcher'b'SafeChildWatcher'u'SafeChildWatcher'b'FastChildWatcher'u'FastChildWatcher'b'MultiLoopChildWatcher'u'MultiLoopChildWatcher'b'ThreadedChildWatcher'u'ThreadedChildWatcher'b'DefaultEventLoopPolicy'u'DefaultEventLoopPolicy'b'Signals are not really supported on Windows'u'Signals are not really supported on Windows'b'Dummy signal handler.'u'Dummy signal handler.'b'Unix event loop. + + Adds signal handling and UNIX Domain Socket support to SelectorEventLoop. + 'u'Unix event loop. + + Adds signal handling and UNIX Domain Socket support to SelectorEventLoop. + 'b'Closing the loop 'u'Closing the loop 'b' on interpreter shutdown stage, skipping signal handlers removal'u' on interpreter shutdown stage, skipping signal handlers removal'b'Add a handler for a signal. UNIX only. + + Raise ValueError if the signal number is invalid or uncatchable. + Raise RuntimeError if there is a problem setting up the handler. + 'u'Add a handler for a signal. UNIX only. + + Raise ValueError if the signal number is invalid or uncatchable. + Raise RuntimeError if there is a problem setting up the handler. + 'b'coroutines cannot be used with add_signal_handler()'u'coroutines cannot be used with add_signal_handler()'b'set_wakeup_fd(-1) failed: %s'u'set_wakeup_fd(-1) failed: %s'b'sig 'u'sig 'b' cannot be caught'u' cannot be caught'b'Internal helper that is the actual signal handler.'u'Internal helper that is the actual signal handler.'b'Remove a handler for a signal. UNIX only. + + Return True if a signal handler was removed, False if not. + 'u'Remove a handler for a signal. UNIX only. + + Return True if a signal handler was removed, False if not. + 'b'Internal helper to validate a signal. + + Raise ValueError if the signal number is invalid or uncatchable. + Raise RuntimeError if there is a problem setting up the handler. + 'u'Internal helper to validate a signal. + + Raise ValueError if the signal number is invalid or uncatchable. + Raise RuntimeError if there is a problem setting up the handler. + 'b'sig must be an int, not 'u'sig must be an int, not 'b'invalid signal number 'u'invalid signal number 'b'asyncio.get_child_watcher() is not activated, subprocess support is not installed.'u'asyncio.get_child_watcher() is not activated, subprocess support is not installed.'b'you have to pass server_hostname when using ssl'u'you have to pass server_hostname when using ssl'b'path and sock can not be specified at the same time'u'path and sock can not be specified at the same time'b'no path and sock were specified'u'no path and sock were specified'b'A UNIX Domain Stream Socket was expected, got 'u'A UNIX Domain Stream Socket was expected, got 'b'Address 'u'Address 'b' is already in use'u' is already in use'b'path was not specified, and no sock specified'u'path was not specified, and no sock specified'b'os.sendfile() is not available'u'os.sendfile() is not available'b'socket is not connected'u'socket is not connected'b'os.sendfile call failed'u'os.sendfile call failed'b'Pipe transport is for pipes/sockets only.'u'Pipe transport is for pipes/sockets only.'b'_selector'u'_selector'b'%r was closed by peer'u'%r was closed by peer'b'Pipe transport is only for pipes, sockets and character devices'u'Pipe transport is only for pipes, sockets and character devices'b'bufsize='u'bufsize='b'pipe closed by peer or os.write(pipe, data) raised exception.'u'pipe closed by peer or os.write(pipe, data) raised exception.'b'Abstract base class for monitoring child processes. + + Objects derived from this class monitor a collection of subprocesses and + report their termination or interruption by a signal. + + New callbacks are registered with .add_child_handler(). Starting a new + process must be done within a 'with' block to allow the watcher to suspend + its activity until the new process if fully registered (this is needed to + prevent a race condition in some implementations). + + Example: + with watcher: + proc = subprocess.Popen("sleep 1") + watcher.add_child_handler(proc.pid, callback) + + Notes: + Implementations of this class must be thread-safe. + + Since child watcher objects may catch the SIGCHLD signal and call + waitpid(-1), there should be only one active object per process. + 'u'Abstract base class for monitoring child processes. + + Objects derived from this class monitor a collection of subprocesses and + report their termination or interruption by a signal. + + New callbacks are registered with .add_child_handler(). Starting a new + process must be done within a 'with' block to allow the watcher to suspend + its activity until the new process if fully registered (this is needed to + prevent a race condition in some implementations). + + Example: + with watcher: + proc = subprocess.Popen("sleep 1") + watcher.add_child_handler(proc.pid, callback) + + Notes: + Implementations of this class must be thread-safe. + + Since child watcher objects may catch the SIGCHLD signal and call + waitpid(-1), there should be only one active object per process. + 'b'Register a new child handler. + + Arrange for callback(pid, returncode, *args) to be called when + process 'pid' terminates. Specifying another callback for the same + process replaces the previous handler. + + Note: callback() must be thread-safe. + 'u'Register a new child handler. + + Arrange for callback(pid, returncode, *args) to be called when + process 'pid' terminates. Specifying another callback for the same + process replaces the previous handler. + + Note: callback() must be thread-safe. + 'b'Removes the handler for process 'pid'. + + The function returns True if the handler was successfully removed, + False if there was nothing to remove.'u'Removes the handler for process 'pid'. + + The function returns True if the handler was successfully removed, + False if there was nothing to remove.'b'Attach the watcher to an event loop. + + If the watcher was previously attached to an event loop, then it is + first detached before attaching to the new loop. + + Note: loop may be None. + 'u'Attach the watcher to an event loop. + + If the watcher was previously attached to an event loop, then it is + first detached before attaching to the new loop. + + Note: loop may be None. + 'b'Close the watcher. + + This must be called to make sure that any underlying resource is freed. + 'u'Close the watcher. + + This must be called to make sure that any underlying resource is freed. + 'b'Return ``True`` if the watcher is active and is used by the event loop. + + Return True if the watcher is installed and ready to handle process exit + notifications. + + 'u'Return ``True`` if the watcher is active and is used by the event loop. + + Return True if the watcher is installed and ready to handle process exit + notifications. + + 'b'Enter the watcher's context and allow starting new processes + + This function must return self'u'Enter the watcher's context and allow starting new processes + + This function must return self'b'Exit the watcher's context'u'Exit the watcher's context'b'A loop is being detached from a child watcher with pending handlers'u'A loop is being detached from a child watcher with pending handlers'b'Unknown exception in SIGCHLD handler'u'Unknown exception in SIGCHLD handler'b''Safe' child watcher implementation. + + This implementation avoids disrupting other code spawning processes by + polling explicitly each process in the SIGCHLD handler instead of calling + os.waitpid(-1). + + This is a safe solution but it has a significant overhead when handling a + big number of children (O(n) each time SIGCHLD is raised) + 'u''Safe' child watcher implementation. + + This implementation avoids disrupting other code spawning processes by + polling explicitly each process in the SIGCHLD handler instead of calling + os.waitpid(-1). + + This is a safe solution but it has a significant overhead when handling a + big number of children (O(n) each time SIGCHLD is raised) + 'b'process %s exited with returncode %s'u'process %s exited with returncode %s'b'Unknown child process pid %d, will report returncode 255'u'Unknown child process pid %d, will report returncode 255'b'Child watcher got an unexpected pid: %r'u'Child watcher got an unexpected pid: %r'b''Fast' child watcher implementation. + + This implementation reaps every terminated processes by calling + os.waitpid(-1) directly, possibly breaking other code spawning processes + and waiting for their termination. + + There is no noticeable overhead when handling a big number of children + (O(1) each time a child terminates). + 'u''Fast' child watcher implementation. + + This implementation reaps every terminated processes by calling + os.waitpid(-1) directly, possibly breaking other code spawning processes + and waiting for their termination. + + There is no noticeable overhead when handling a big number of children + (O(1) each time a child terminates). + 'b'Caught subprocesses termination from unknown pids: %s'u'Caught subprocesses termination from unknown pids: %s'b'Must use the context manager'u'Must use the context manager'b'unknown process %s exited with returncode %s'u'unknown process %s exited with returncode %s'b'Caught subprocess termination from unknown pid: %d -> %d'u'Caught subprocess termination from unknown pid: %d -> %d'b'A watcher that doesn't require running loop in the main thread. + + This implementation registers a SIGCHLD signal handler on + instantiation (which may conflict with other code that + install own handler for this signal). + + The solution is safe but it has a significant overhead when + handling a big number of processes (*O(n)* each time a + SIGCHLD is received). + 'u'A watcher that doesn't require running loop in the main thread. + + This implementation registers a SIGCHLD signal handler on + instantiation (which may conflict with other code that + install own handler for this signal). + + The solution is safe but it has a significant overhead when + handling a big number of processes (*O(n)* each time a + SIGCHLD is received). + 'b'SIGCHLD handler was changed by outside code'u'SIGCHLD handler was changed by outside code'b'Previous SIGCHLD handler was set by non-Python code, restore to default handler on watcher close.'u'Previous SIGCHLD handler was set by non-Python code, restore to default handler on watcher close.'b'Loop %r that handles pid %r is closed'u'Loop %r that handles pid %r is closed'b'Threaded child watcher implementation. + + The watcher uses a thread per process + for waiting for the process finish. + + It doesn't require subscription on POSIX signal + but a thread creation is not free. + + The watcher has O(1) complexity, its performance doesn't depend + on amount of spawn processes. + 'u'Threaded child watcher implementation. + + The watcher uses a thread per process + for waiting for the process finish. + + It doesn't require subscription on POSIX signal + but a thread creation is not free. + + The watcher has O(1) complexity, its performance doesn't depend + on amount of spawn processes. + 'b'Internal: Join all non-daemon threads'u'Internal: Join all non-daemon threads'b' has registered but not finished child processes'u' has registered but not finished child processes'b'waitpid-'u'waitpid-'b'UNIX event loop policy with a watcher for child processes.'u'UNIX event loop policy with a watcher for child processes.'b'Set the event loop. + + As a side effect, if a child watcher was set before, then calling + .set_event_loop() from the main thread will call .attach_loop(loop) on + the child watcher. + 'u'Set the event loop. + + As a side effect, if a child watcher was set before, then calling + .set_event_loop() from the main thread will call .attach_loop(loop) on + the child watcher. + 'b'Get the watcher for child processes. + + If not yet set, a ThreadedChildWatcher object is automatically created. + 'u'Get the watcher for child processes. + + If not yet set, a ThreadedChildWatcher object is automatically created. + 'u'asyncio.unix_events'u'unix_events'_get_build_versionReturn the version of MSVC that was used to build Python. + + For Python 2.3 and up, the version number is included in + sys.version. For earlier versions, assume the compiler is MSVC 6. + MSC v.majorVersion10.0minorVersionfind_msvcrtReturn the name of the VC runtime dllclibnamemsvcr%dctypes.macholib.dyld_dyld_findlib%s.dylib%s.dylib%s.framework/%sctypes._aix_is_elfReturn True if the given file is an ELF fileELFelf_header_findLib_gcc[^\(\)\s]*lib%s\.[^\(\)\s]*c_compilertemp-Wl,-tsunos5_get_soname/usr/ccs/bin/dump-Lpv\[.*\]\sSONAME\s+([^\s]+)objdump-j.dynamic\sSONAME\s+([^\s]+)openbsddragonflyename:-l%s\.\S+ => \S*/(lib%s\.\S+)/sbin/ldconfig_findLib_crleis64/usr/bin/crle-64Default Library Path (ELF):lib%s.solibfile_findSoname_ldconfig-32libc6,x86-64x86_64-64libc6,64bitppc64-64sparc64-64s390x-64libc6,IA-64ia64-64mach_maplibc6abi_type\s+(lib%s\.[^\s]+)\s+\(%s_findLib_ldldlibpath-l%slibm.dyliblibcrypto.dylibUsing CDLL(name, os.RTLD_MEMBER): libc.a(shr.o)Using cdll.LoadLibrary(): rpmlibrpm.solibc.a(shr_64.o)crypt :: cryptcrypto :: cryptolibm.solibcrypt.so# find_library(name) returns the pathname of a library, or None.# This function was copied from Lib/distutils/msvccompiler.py# I don't think paths are affected by minor version in version 6# else we don't know what version of the compiler this is# better be safe than sorry# CRT is no longer directly loadable. See issue23606 for the# discussion about alternative approaches.# If python was built with in debug mode# See MSDN for the REAL search order.# AIX has two styles of storing shared libraries# GNU auto_tools refer to these as svr4 and aix# svr4 (System V Release 4) is a regular file, often with .so as suffix# AIX style uses an archive (suffix .a) with members (e.g., shr.o, libssl.so)# see issue#26439 and _aix.py for more details# Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump# Run GCC's linker with the -t (aka --trace) option and examine the# library name it prints out. The GCC command will fail because we# haven't supplied a proper program with main(), but that does not# matter.# No C compiler available, give up# E.g. bad executable# Raised if the file was already removed, which is the normal# behaviour of GCC if linking fails# Check if the given file is an elf file: gcc can report# some files that are linker scripts and not actual# shared objects. See bpo-41976 for more details# use /usr/ccs/bin/dump on solaris# E.g. command not found# assuming GNU binutils / ELF# objdump is not available, give up# "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]# XXX assuming GLIBC's ldconfig (with option -p)# See issue #9998 for why this is needed# result will be None# See issue #9998# find and load_version# load# issue-26439 - fix broken test call for AIX# librpm.so is only available as 32-bit shared libraryb'Return the version of MSVC that was used to build Python. + + For Python 2.3 and up, the version number is included in + sys.version. For earlier versions, assume the compiler is MSVC 6. + 'u'Return the version of MSVC that was used to build Python. + + For Python 2.3 and up, the version number is included in + sys.version. For earlier versions, assume the compiler is MSVC 6. + 'b'MSC v.'u'MSC v.'b'Return the name of the VC runtime dll'u'Return the name of the VC runtime dll'b'msvcrt'u'msvcrt'b'msvcr%d'u'msvcr%d'b'lib%s.dylib'u'lib%s.dylib'b'%s.dylib'u'%s.dylib'b'%s.framework/%s'u'%s.framework/%s'b'Return True if the given file is an ELF file'u'Return True if the given file is an ELF file'b'ELF'b'[^\(\)\s]*lib%s\.[^\(\)\s]*'u'[^\(\)\s]*lib%s\.[^\(\)\s]*'b'cc'u'cc'b'-Wl,-t'u'-Wl,-t'b'sunos5'u'sunos5'b'/usr/ccs/bin/dump'u'/usr/ccs/bin/dump'b'-Lpv'u'-Lpv'b'\[.*\]\sSONAME\s+([^\s]+)'b'objdump'u'objdump'b'-j'u'-j'b'.dynamic'u'.dynamic'b'\sSONAME\s+([^\s]+)'b'openbsd'u'openbsd'b'dragonfly'u'dragonfly'b':-l%s\.\S+ => \S*/(lib%s\.\S+)'u':-l%s\.\S+ => \S*/(lib%s\.\S+)'b'/sbin/ldconfig'u'/sbin/ldconfig'b'/usr/bin/crle'u'/usr/bin/crle'b'-64'u'-64'b'Default Library Path (ELF):'b'lib%s.so'u'lib%s.so'b'-32'u'-32'b'libc6,x86-64'u'libc6,x86-64'b'x86_64-64'u'x86_64-64'b'libc6,64bit'u'libc6,64bit'b'ppc64-64'u'ppc64-64'b'sparc64-64'u'sparc64-64'b's390x-64'u's390x-64'b'libc6,IA-64'u'libc6,IA-64'b'ia64-64'u'ia64-64'b'libc6'u'libc6'b'\s+(lib%s\.[^\s]+)\s+\(%s'u'\s+(lib%s\.[^\s]+)\s+\(%s'b'ld'u'ld'b'-l%s'u'-l%s'b'libm.dylib'u'libm.dylib'b'libcrypto.dylib'u'libcrypto.dylib'b'Using CDLL(name, os.RTLD_MEMBER): 'u'Using CDLL(name, os.RTLD_MEMBER): 'b'libc.a(shr.o)'u'libc.a(shr.o)'b'Using cdll.LoadLibrary(): 'u'Using cdll.LoadLibrary(): 'b'rpm'u'rpm'b'librpm.so'u'librpm.so'b'libc.a(shr_64.o)'u'libc.a(shr_64.o)'b'crypt :: 'u'crypt :: 'b'crypt'u'crypt'b'crypto :: 'u'crypto :: 'b'crypto'u'crypto'b'libm.so'u'libm.so'b'libcrypt.so'u'libcrypt.so'u'ctypes.util'u'util'Utility code for constructing importers, etc.Return the hash of *source_bytes* as used in hash-based pyc files.resolve_nameno package specified for (required for relative module names)'(required for relative module names)'_find_spec_from_pathReturn the spec for the specified module. + + First, sys.modules is checked to see if the module was already imported. If + so, then sys.modules[name].__spec__ is returned. If that happens to be + set to None, then ValueError is raised. If the module is not in + sys.modules, then sys.meta_path is searched for a suitable spec with the + value of 'path' given to the finders. None is returned if no spec could + be found. + + Dotted names do not have their parent packages implicitly imported. You will + most likely need to explicitly import all parent packages in the proper + order for a submodule to get the correct spec. + + {}.__spec__ is None{}.__spec__ is not setReturn the spec for the specified module. + + First, sys.modules is checked to see if the module was already imported. If + so, then sys.modules[name].__spec__ is returned. If that happens to be + set to None, then ValueError is raised. If the module is not in + sys.modules, then sys.meta_path is searched for a suitable spec with the + value of 'path' given to the finders. None is returned if no spec could + be found. + + If the name is for submodule (contains a dot), the parent module is + automatically imported. + + The name and package arguments work the same as importlib.import_module(). + In other words, relative module names (with leading dots) work. + + __path__ attribute not found on while trying to find "while trying to find "_module_to_load__initializing__set_packageSet __package__ on the returned module. + + This function is deprecated. + + set_package_wrapperThe import system now takes care of this automatically.set_loaderSet __loader__ on the returned module. + + This function is deprecated. + + set_loader_wrappermodule_for_loaderDecorator to handle selecting the proper module for loaders. + + The decorated function is passed the module to use instead of the module + name. The module passed in to the function is either from sys.modules if + it already exists or is a new module. If the module is new, then __name__ + is set the first argument to the method, __loader__ is set to self, and + __package__ is set accordingly (if self.is_package() is defined) will be set + before it is passed to the decorated function (if self.is_package() does + not work for the module it will be set post-load). + + If an exception is raised and the decorator created the module it is + subsequently removed from sys.modules. + + The decorator assumes that the decorated function takes the module name as + the second argument. + + module_for_loader_wrapper_LazyModuleA subclass of the module type which triggers loading upon attribute access.Trigger the load of the module and return the attribute.original_nameattrs_thenoriginal_typeattrs_nowattrs_updatedmodule object for substituted in sys.modules during a lazy load"substituted in sys.modules during a lazy ""load"Trigger the load and then perform the deletion.LazyLoaderA loader that creates a module which defers loading until attribute access.__check_eager_loaderloader must define exec_module()Construct a callable which returns the eager loader made lazy.Make the module load lazily.# This must be done before open() is called as the 'io' module# implicitly imports 'locale' and would otherwise trigger an# infinite loop.# (otherwise an optimization shortcut in import.c becomes wrong)# If __package__ was not set above, __import__() will do it later.# All module metadata must be garnered from __spec__ in order to avoid# using mutated values.# Stop triggering this method.# Get the original name to make sure no object substitution occurred# Figure out exactly what attributes were mutated between the creation# of the module and now.# Code that set the attribute may have kept a reference to the# assigned object, making identity more important than equality.# If exec_module() was used directly there is no guarantee the module# object was put into sys.modules.# Update after loading since that's what would happen in an eager# loading situation.# To trigger the load and raise an exception if the attribute# doesn't exist.# Don't need to worry about deep-copying as trying to set an attribute# on an object would have triggered the load,# e.g. ``module.__spec__.loader = None`` would trigger a load from# trying to access module.__spec__.b'Utility code for constructing importers, etc.'u'Utility code for constructing importers, etc.'b'Return the hash of *source_bytes* as used in hash-based pyc files.'u'Return the hash of *source_bytes* as used in hash-based pyc files.'b'no package specified for 'u'no package specified for 'b' (required for relative module names)'u' (required for relative module names)'b'Return the spec for the specified module. + + First, sys.modules is checked to see if the module was already imported. If + so, then sys.modules[name].__spec__ is returned. If that happens to be + set to None, then ValueError is raised. If the module is not in + sys.modules, then sys.meta_path is searched for a suitable spec with the + value of 'path' given to the finders. None is returned if no spec could + be found. + + Dotted names do not have their parent packages implicitly imported. You will + most likely need to explicitly import all parent packages in the proper + order for a submodule to get the correct spec. + + 'u'Return the spec for the specified module. + + First, sys.modules is checked to see if the module was already imported. If + so, then sys.modules[name].__spec__ is returned. If that happens to be + set to None, then ValueError is raised. If the module is not in + sys.modules, then sys.meta_path is searched for a suitable spec with the + value of 'path' given to the finders. None is returned if no spec could + be found. + + Dotted names do not have their parent packages implicitly imported. You will + most likely need to explicitly import all parent packages in the proper + order for a submodule to get the correct spec. + + 'b'{}.__spec__ is None'u'{}.__spec__ is None'b'{}.__spec__ is not set'u'{}.__spec__ is not set'b'Return the spec for the specified module. + + First, sys.modules is checked to see if the module was already imported. If + so, then sys.modules[name].__spec__ is returned. If that happens to be + set to None, then ValueError is raised. If the module is not in + sys.modules, then sys.meta_path is searched for a suitable spec with the + value of 'path' given to the finders. None is returned if no spec could + be found. + + If the name is for submodule (contains a dot), the parent module is + automatically imported. + + The name and package arguments work the same as importlib.import_module(). + In other words, relative module names (with leading dots) work. + + 'u'Return the spec for the specified module. + + First, sys.modules is checked to see if the module was already imported. If + so, then sys.modules[name].__spec__ is returned. If that happens to be + set to None, then ValueError is raised. If the module is not in + sys.modules, then sys.meta_path is searched for a suitable spec with the + value of 'path' given to the finders. None is returned if no spec could + be found. + + If the name is for submodule (contains a dot), the parent module is + automatically imported. + + The name and package arguments work the same as importlib.import_module(). + In other words, relative module names (with leading dots) work. + + 'b'__path__ attribute not found on 'u'__path__ attribute not found on 'b' while trying to find 'u' while trying to find 'b'Set __package__ on the returned module. + + This function is deprecated. + + 'u'Set __package__ on the returned module. + + This function is deprecated. + + 'b'The import system now takes care of this automatically.'u'The import system now takes care of this automatically.'b'Set __loader__ on the returned module. + + This function is deprecated. + + 'u'Set __loader__ on the returned module. + + This function is deprecated. + + 'b'Decorator to handle selecting the proper module for loaders. + + The decorated function is passed the module to use instead of the module + name. The module passed in to the function is either from sys.modules if + it already exists or is a new module. If the module is new, then __name__ + is set the first argument to the method, __loader__ is set to self, and + __package__ is set accordingly (if self.is_package() is defined) will be set + before it is passed to the decorated function (if self.is_package() does + not work for the module it will be set post-load). + + If an exception is raised and the decorator created the module it is + subsequently removed from sys.modules. + + The decorator assumes that the decorated function takes the module name as + the second argument. + + 'u'Decorator to handle selecting the proper module for loaders. + + The decorated function is passed the module to use instead of the module + name. The module passed in to the function is either from sys.modules if + it already exists or is a new module. If the module is new, then __name__ + is set the first argument to the method, __loader__ is set to self, and + __package__ is set accordingly (if self.is_package() is defined) will be set + before it is passed to the decorated function (if self.is_package() does + not work for the module it will be set post-load). + + If an exception is raised and the decorator created the module it is + subsequently removed from sys.modules. + + The decorator assumes that the decorated function takes the module name as + the second argument. + + 'b'A subclass of the module type which triggers loading upon attribute access.'u'A subclass of the module type which triggers loading upon attribute access.'b'Trigger the load of the module and return the attribute.'u'Trigger the load of the module and return the attribute.'b'module object for 'u'module object for 'b' substituted in sys.modules during a lazy load'u' substituted in sys.modules during a lazy load'b'Trigger the load and then perform the deletion.'u'Trigger the load and then perform the deletion.'b'A loader that creates a module which defers loading until attribute access.'u'A loader that creates a module which defers loading until attribute access.'b'loader must define exec_module()'u'loader must define exec_module()'b'Construct a callable which returns the eager loader made lazy.'u'Construct a callable which returns the eager loader made lazy.'b'Make the module load lazily.'u'Make the module load lazily.'u'importlib.util'Various utility functions._MAX_LENGTH_PLACEHOLDER_LEN_MIN_BEGIN_LEN_MIN_END_LEN_MIN_COMMON_LEN_MIN_DIFF_LEN_shortenprefixlensuffixlen%s[%d chars]%scommon_len [truncated]...sorted_list_differenceFinds elements in only one or the other of two, sorted input lists. + + Returns a two-element tuple of lists. The first list contains those + elements in the "expected" list but not in the "actual" list, and the + second contains those elements in the "actual" list but not in the + "expected" list. Duplicate elements in either input list are ignored. + unexpectedunorderable_list_differenceSame behavior as sorted_list_difference but + for lists of unorderable items (like dicts). + + As it does a linear search per item (remove) it + has O(n*n) performance.Return -1 if x < y, 0 if x == y and 1 if x > yMismatchactual expected value_MismatchReturns list of (cnt_act, cnt_exp, elem) triples where the counts differcnt_scnt_tother_elem# anything left in actual is unexpected# elements need not be hashable# elements must be hashableb'Various utility functions.'u'Various utility functions.'b'%s[%d chars]%s'u'%s[%d chars]%s'b' [truncated]...'u' [truncated]...'b'Finds elements in only one or the other of two, sorted input lists. + + Returns a two-element tuple of lists. The first list contains those + elements in the "expected" list but not in the "actual" list, and the + second contains those elements in the "actual" list but not in the + "expected" list. Duplicate elements in either input list are ignored. + 'u'Finds elements in only one or the other of two, sorted input lists. + + Returns a two-element tuple of lists. The first list contains those + elements in the "expected" list but not in the "actual" list, and the + second contains those elements in the "actual" list but not in the + "expected" list. Duplicate elements in either input list are ignored. + 'b'Same behavior as sorted_list_difference but + for lists of unorderable items (like dicts). + + As it does a linear search per item (remove) it + has O(n*n) performance.'u'Same behavior as sorted_list_difference but + for lists of unorderable items (like dicts). + + As it does a linear search per item (remove) it + has O(n*n) performance.'b'Return -1 if x < y, 0 if x == y and 1 if x > y'u'Return -1 if x < y, 0 if x == y and 1 if x > y'b'Mismatch'u'Mismatch'b'actual expected value'u'actual expected value'b'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ'u'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ'u'unittest.util'ForkAwareThreadLockForkAwareLocalclose_all_fds_exceptLOGGER_NAME[%(levelname)s/%(processName)s] %(message)sDEFAULT_LOGGING_FORMAT + Returns logger used by multiprocessing + _exithandlers + Turn on logging and add a handler which prints to stderr + _platform_supports_abstract_socketsaddress type of {address!r} unrecognizedabstract_sockets_supported_remove_temp_dirpymp-created temp directory %s_afterfork_registry_afterfork_counterafter forker raised exception %s_finalizer_counter + Class which supports object finalization using weakrefs + Exitpriority ({0!r}) must be None or int, not {1!s}Without object, exitpriority cannot be None + Run the callback unless it has already been called or cancelled + finalizer ignored because different processfinalizer calling %s with args %s and kwargs %sfinalizer no longer registered + Cancel finalization of the object + still_active + Return whether this finalizer is still waiting to invoke callback + <%s object, dead><%s object, callback=%s, args=, kwargs=, exitpriority=_run_finalizersminpriority + Run all finalizers whose exit priority is not None and at least minpriority + + Finalizers with highest priority are called first; finalizers with + the same priority will be called in reverse order of creation. + calling %s + Returns true if the process is shutting down + _exitingprocess shutting downrunning all "atexit" finalizers with priority >= 0calling terminate() for daemon %scalling join() for process %srunning the remaining "atexit" finalizers_resetfd too largepassfdsClose each file descriptor given as an argument_cleanup_testsCleanup multiprocessing resources when multiprocessing tests + completed.# Module providing various facilities to other parts of the package# multiprocessing/util.py# we want threading to install it's# cleanup function before multiprocessing does# Logging# XXX multiprocessing should cleanup before logging# Abstract socket support# Function returning a temp directory which will be removed on exit# current_process() can be None if the finalizer is called# late during Python finalization# get name of a temp directory which will be automatically cleaned up# keep a strong reference to shutil.rmtree(), since the finalizer# can be called late during Python shutdown# Support for reinitialization of objects when bootstrapping a child process# Finalization using weakrefs# Need to bind these locally because the globals can have# been cleared at shutdown# This function may be called after this module's globals are# destroyed. See the _exit_function function in this module for more# notes.# Careful: _finalizer_registry may be mutated while this function# is running (either by a GC run or by another thread).# list(_finalizer_registry) should be atomic, while# list(_finalizer_registry.items()) is not.# key may have been removed from the registry# Clean up on exit# We hold on to references to functions in the arglist due to the# situation described below, where this function is called after this# module's globals are destroyed.# We check if the current process is None here because if# it's None, any call to ``active_children()`` will raise# an AttributeError (active_children winds up trying to# get attributes from util._current_process). One# situation where this can happen is if someone has# manipulated sys.modules, causing this module to be# garbage collected. The destructor for the module type# then replaces all values in the module dict with None.# For instance, after setuptools runs a test it replaces# sys.modules with a copy created earlier. See issues# #9775 and #15881. Also related: #4106, #9205, and# #9207.# Some fork aware types# Close fds except those specified# Close sys.stdin and replace stdin with os.devnull# Flush standard streams, if any# Start a program with only specified fds kept open# cleanup multiprocessing# Stop the ForkServer process if it's running# Stop the ResourceTracker process if it's running# bpo-37421: Explicitly call _run_finalizers() to remove immediately# temporary directories created by multiprocessing.util.get_temp_dir().b'sub_debug'u'sub_debug'b'sub_warning'u'sub_warning'b'get_logger'u'get_logger'b'get_temp_dir'u'get_temp_dir'b'register_after_fork'u'register_after_fork'b'is_exiting'u'is_exiting'b'Finalize'u'Finalize'b'ForkAwareThreadLock'u'ForkAwareThreadLock'b'ForkAwareLocal'u'ForkAwareLocal'b'close_all_fds_except'u'close_all_fds_except'b'SUBDEBUG'u'SUBDEBUG'b'SUBWARNING'u'SUBWARNING'b'[%(levelname)s/%(processName)s] %(message)s'u'[%(levelname)s/%(processName)s] %(message)s'b' + Returns logger used by multiprocessing + 'u' + Returns logger used by multiprocessing + 'b' + Turn on logging and add a handler which prints to stderr + 'u' + Turn on logging and add a handler which prints to stderr + 'b'address type of {address!r} unrecognized'u'address type of {address!r} unrecognized'b'pymp-'u'pymp-'b'created temp directory %s'u'created temp directory %s'b'after forker raised exception %s'u'after forker raised exception %s'b' + Class which supports object finalization using weakrefs + 'u' + Class which supports object finalization using weakrefs + 'b'Exitpriority ({0!r}) must be None or int, not {1!s}'u'Exitpriority ({0!r}) must be None or int, not {1!s}'b'Without object, exitpriority cannot be None'u'Without object, exitpriority cannot be None'b' + Run the callback unless it has already been called or cancelled + 'u' + Run the callback unless it has already been called or cancelled + 'b'finalizer ignored because different process'u'finalizer ignored because different process'b'finalizer calling %s with args %s and kwargs %s'u'finalizer calling %s with args %s and kwargs %s'b'finalizer no longer registered'u'finalizer no longer registered'b' + Cancel finalization of the object + 'u' + Cancel finalization of the object + 'b' + Return whether this finalizer is still waiting to invoke callback + 'u' + Return whether this finalizer is still waiting to invoke callback + 'b'<%s object, dead>'u'<%s object, dead>'b'<%s object, callback=%s'u'<%s object, callback=%s'b', args='u', args='b', kwargs='u', kwargs='b', exitpriority='u', exitpriority='b' + Run all finalizers whose exit priority is not None and at least minpriority + + Finalizers with highest priority are called first; finalizers with + the same priority will be called in reverse order of creation. + 'u' + Run all finalizers whose exit priority is not None and at least minpriority + + Finalizers with highest priority are called first; finalizers with + the same priority will be called in reverse order of creation. + 'b'calling %s'u'calling %s'b' + Returns true if the process is shutting down + 'u' + Returns true if the process is shutting down + 'b'process shutting down'u'process shutting down'b'running all "atexit" finalizers with priority >= 0'u'running all "atexit" finalizers with priority >= 0'b'calling terminate() for daemon %s'u'calling terminate() for daemon %s'b'calling join() for process %s'u'calling join() for process %s'b'running the remaining "atexit" finalizers'u'running the remaining "atexit" finalizers'b'fd too large'u'fd too large'b'Close each file descriptor given as an argument'u'Close each file descriptor given as an argument'b'Cleanup multiprocessing resources when multiprocessing tests + completed.'u'Cleanup multiprocessing resources when multiprocessing tests + completed.'u'multiprocessing.util'distutils.util + +Miscellaneous utility functions -- anything that doesn't fit into +one of the other *util.py modules. +Return a string that identifies the current platform. This is used mainly to + distinguish platform-specific build directories and platform-specific built + distributions. Typically includes the OS name and version and the + architecture (as supplied by 'os.uname()'), although the exact information + included depends on the OS; eg. on Linux, the kernel version isn't + particularly important. + + Examples of returned values: + linux-i586 + linux-alpha (?) + solaris-2.6-sun4u + + Windows will return one of: + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) + win32 (all others - specifically, sys.platform is returned) + + For other non-POSIX platforms, currently just returns 'sys.platform'. + + distutils.sysconfigx86x64armTARGET_TO_PLATVSCMD_ARG_TGT_ARCHReturn 'pathname' as a name that will work on the native filesystem, + i.e. split it on '/' and put it back together again using the current + directory separator. Needed because filenames in the setup script are + always supplied in Unix style, and have to be converted to the local + convention before we can actually use them in the filesystem. Raises + ValueError on non-Unix-ish systems if 'pathname' either starts or + ends with a slash. + path '%s' cannot be absolutepath '%s' cannot end with '/'change_rootReturn 'pathname' with 'new_root' prepended. If 'pathname' is + relative, this is equivalent to "os.path.join(new_root,pathname)". + Otherwise, it requires making 'pathname' relative and then joining the + two, which is tricky on DOS/Windows and Mac OS. + nothing known about platform '%s'_environ_checkedcheck_environEnsure that 'os.environ' has all the environment variables we + guarantee that users can use in config files, command-line options, + etc. Currently this includes: + HOME - user's home directory (Unix only) + PLAT - description of the current platform, including hardware + and OS (see 'get_platform()') + PLATsubst_varsPerform shell/Perl-style variable substitution on 'string'. Every + occurrence of '$' followed by a name is considered a variable, and + variable is substituted by the value found in the 'local_vars' + dictionary, or in 'os.environ' if it's not in 'local_vars'. + 'os.environ' is first checked/augmented to guarantee that it contains + certain values: see 'check_environ()'. Raise ValueError for any + variables not found in either 'local_vars' or 'os.environ'. + _substvar_name\$([a-zA-Z_][a-zA-Z_0-9]*)invalid variable '$%s'grok_environment_error_wordchars_re_squote_re_dquote_re_init_regex[^\\\'\"%s ]*'(?:[^'\\]|\\.)*'"(?:[^"\\]|\\.)*"Split a string up according to Unix shell-like rules for quotes and + backslashes. In short: words are delimited by spaces, as long as those + spaces are not escaped by a backslash, or inside a quoted string. + Single and double quotes are equivalent, and the quote characters can + be backslash-escaped. The backslash is stripped from any two-character + escape sequence, leaving only the escaped character. The quote + characters are stripped from any quoted string. Returns a list of + words. + this can't happen (bad char '%c')bad string (mismatched %s quotes?)Perform some action that affects the outside world (eg. by + writing to the filesystem). Such actions are special because they + are disabled by the 'dry_run' flag. This method takes care of all + that bureaucracy for you; all you have to do is supply the + function to call and an argument tuple for it (to embody the + "external action" being performed), and an optional message to + print. + %s%rstrtoboolConvert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + invalid truth value %rbyte_compilepy_filesdirectByte-compile a collection of Python source files to .pyc + files in a __pycache__ subdirectory. 'py_files' is a list + of files to compile; any files that don't end in ".py" are silently + skipped. 'optimize' must be one of the following: + 0 - don't optimize + 1 - normal optimization (like "python -O") + 2 - extra optimization (like "python -OO") + If 'force' is true, all files are recompiled regardless of + timestamps. + + The source filename encoded in each bytecode file defaults to the + filenames listed in 'py_files'; you can modify these with 'prefix' and + 'basedir'. 'prefix' is a string that will be stripped off of each + source filename, and 'base_dir' is a directory name that will be + prepended (after 'prefix' is stripped). You can supply either or both + (or neither) of 'prefix' and 'base_dir', as you wish. + + If 'dry_run' is true, doesn't actually do anything that would + affect the filesystem. + + Byte-compilation is either done directly in this interpreter process + with the standard py_compile module, or indirectly by writing a + temporary script and executing it. Normally, you should let + 'byte_compile()' figure out to use direct compilation or not (see + the source for details). The 'direct' flag is used by the script + generated in indirect mode; unless you know what you're doing, leave + it set to None. + byte-compiling is disabled.script_fdwriting byte-compilation script '%s'from distutils.util import byte_compile +files = [ + +byte_compile(files, optimize=%r, force=%r, + prefix=%r, base_dir=%r, + verbose=%r, dry_run=0, + direct=1) +removing %spy_compileinvalid prefix: filename %r doesn't start with %rcfile_basebyte-compiling %s to %sskipping byte-compilation of %s to %srfc822_escapeReturn a version of the string escaped for inclusion in an + RFC-822 header, by ensuring there are 8 spaces space after each newline. + run_2to3Invoke 2to3 on a list of Python files. + The files should all come from the build area, as the + modification is done in-place. To reduce the build time, + only files modified since the last invocation of this + function should be passed in the files argument.lib2to3.refactorDistutilsRefactoringToollib2to3.fixescopydir_run_2to3Recursively copy a directory, only copying new and changed files, + running run_2to3 over all newly copied Python modules afterward. + + If you give a template string, it's parsed like a MANIFEST.in. + distutils.filelistfilelistcopiedoutnameMixin2to3Mixin class for commands that run 2to3. + To configure 2to3, setup scripts may either change + the class variables, or inherit from individual commands + to override how 2to3 is invoked.# XXX what about the architecture? NT is Intel or Alpha,# Mac OS is M68k or PPC, etc.# convert_path ()# password database, do nothing# subst_vars ()# Function kept for backward compatibility.# Used to try clever things with EnvironmentErrors,# but nowadays str(exception) produces good messages.# Needed by 'split_quoted()'# This is a nice algorithm for splitting up a single string, since it# doesn't require character-by-character examination. It was a little# bit of a brain-bender to get it working right, though...# unescaped, unquoted whitespace: now# we definitely have a word delimiter# preserve whatever is being escaped;# will become part of the current word# slurp singly-quoted string# slurp doubly-quoted string# split_quoted ()# correct for singleton tuple# Late import to fix a bootstrap issue: _posixsubprocess is built by# setup.py, but setup.py uses distutils.# nothing is done if sys.dont_write_bytecode is True# First, if the caller didn't force us into direct or indirect mode,# figure out which mode we should be in. We take a conservative# approach: choose direct mode *only* if the current interpreter is# in debug mode and optimize is 0. If we're not in debug mode (-O# or -OO), we don't know which level of optimization this# interpreter is running with, so we can't do direct# byte-compilation and be certain that it's the right thing. Thus,# always compile indirectly if the current interpreter is in either# optimize mode, or if either optimization level was requested by# the caller.# "Indirect" byte-compilation: write a temporary script and then# run it with the appropriate flags.# XXX would be nice to write absolute filenames, just for# safety's sake (script should be more robust in the face of# chdir'ing before running it). But this requires abspath'ing# 'prefix' as well, and that breaks the hack in build_lib's# 'byte_compile()' method that carefully tacks on a trailing# slash (os.sep really) to make sure the prefix here is "just# right". This whole prefix business is rather delicate -- the# problem is that it's really a directory, but I'm treating it# as a dumb string, so trailing slashes and so forth matter.#py_files = map(os.path.abspath, py_files)#if prefix:# prefix = os.path.abspath(prefix)# "Direct" byte-compilation: use the py_compile module to compile# right here, right now. Note that the script generated in indirect# mode simply calls 'byte_compile()' in direct mode, a weird sort of# cross-process recursion. Hey, it works!# This lets us be lazy and not filter filenames in# the "install_lib" command.# Terminology from the py_compile module:# cfile - byte-compiled file# dfile - purported source filename (same as 'file' by default)# byte_compile ()# 2to3 support# Make this class local, to delay import of 2to3# provide list of fixers to run;# defaults to all from lib2to3.fixers# options dictionary# list of fixers to invoke even though they are marked as explicitb'distutils.util + +Miscellaneous utility functions -- anything that doesn't fit into +one of the other *util.py modules. +'u'distutils.util + +Miscellaneous utility functions -- anything that doesn't fit into +one of the other *util.py modules. +'b'Return a string that identifies the current platform. This is used mainly to + distinguish platform-specific build directories and platform-specific built + distributions. Typically includes the OS name and version and the + architecture (as supplied by 'os.uname()'), although the exact information + included depends on the OS; eg. on Linux, the kernel version isn't + particularly important. + + Examples of returned values: + linux-i586 + linux-alpha (?) + solaris-2.6-sun4u + + Windows will return one of: + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) + win32 (all others - specifically, sys.platform is returned) + + For other non-POSIX platforms, currently just returns 'sys.platform'. + + 'u'Return a string that identifies the current platform. This is used mainly to + distinguish platform-specific build directories and platform-specific built + distributions. Typically includes the OS name and version and the + architecture (as supplied by 'os.uname()'), although the exact information + included depends on the OS; eg. on Linux, the kernel version isn't + particularly important. + + Examples of returned values: + linux-i586 + linux-alpha (?) + solaris-2.6-sun4u + + Windows will return one of: + win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) + win32 (all others - specifically, sys.platform is returned) + + For other non-POSIX platforms, currently just returns 'sys.platform'. + + 'b'x86'u'x86'b'x64'u'x64'b'arm'u'arm'b'VSCMD_ARG_TGT_ARCH'u'VSCMD_ARG_TGT_ARCH'b'Return 'pathname' as a name that will work on the native filesystem, + i.e. split it on '/' and put it back together again using the current + directory separator. Needed because filenames in the setup script are + always supplied in Unix style, and have to be converted to the local + convention before we can actually use them in the filesystem. Raises + ValueError on non-Unix-ish systems if 'pathname' either starts or + ends with a slash. + 'u'Return 'pathname' as a name that will work on the native filesystem, + i.e. split it on '/' and put it back together again using the current + directory separator. Needed because filenames in the setup script are + always supplied in Unix style, and have to be converted to the local + convention before we can actually use them in the filesystem. Raises + ValueError on non-Unix-ish systems if 'pathname' either starts or + ends with a slash. + 'b'path '%s' cannot be absolute'u'path '%s' cannot be absolute'b'path '%s' cannot end with '/''u'path '%s' cannot end with '/''b'Return 'pathname' with 'new_root' prepended. If 'pathname' is + relative, this is equivalent to "os.path.join(new_root,pathname)". + Otherwise, it requires making 'pathname' relative and then joining the + two, which is tricky on DOS/Windows and Mac OS. + 'u'Return 'pathname' with 'new_root' prepended. If 'pathname' is + relative, this is equivalent to "os.path.join(new_root,pathname)". + Otherwise, it requires making 'pathname' relative and then joining the + two, which is tricky on DOS/Windows and Mac OS. + 'b'nothing known about platform '%s''u'nothing known about platform '%s''b'Ensure that 'os.environ' has all the environment variables we + guarantee that users can use in config files, command-line options, + etc. Currently this includes: + HOME - user's home directory (Unix only) + PLAT - description of the current platform, including hardware + and OS (see 'get_platform()') + 'u'Ensure that 'os.environ' has all the environment variables we + guarantee that users can use in config files, command-line options, + etc. Currently this includes: + HOME - user's home directory (Unix only) + PLAT - description of the current platform, including hardware + and OS (see 'get_platform()') + 'b'PLAT'u'PLAT'b'Perform shell/Perl-style variable substitution on 'string'. Every + occurrence of '$' followed by a name is considered a variable, and + variable is substituted by the value found in the 'local_vars' + dictionary, or in 'os.environ' if it's not in 'local_vars'. + 'os.environ' is first checked/augmented to guarantee that it contains + certain values: see 'check_environ()'. Raise ValueError for any + variables not found in either 'local_vars' or 'os.environ'. + 'u'Perform shell/Perl-style variable substitution on 'string'. Every + occurrence of '$' followed by a name is considered a variable, and + variable is substituted by the value found in the 'local_vars' + dictionary, or in 'os.environ' if it's not in 'local_vars'. + 'os.environ' is first checked/augmented to guarantee that it contains + certain values: see 'check_environ()'. Raise ValueError for any + variables not found in either 'local_vars' or 'os.environ'. + 'b'\$([a-zA-Z_][a-zA-Z_0-9]*)'u'\$([a-zA-Z_][a-zA-Z_0-9]*)'b'invalid variable '$%s''u'invalid variable '$%s''b'[^\\\'\"%s ]*'u'[^\\\'\"%s ]*'b''(?:[^'\\]|\\.)*''u''(?:[^'\\]|\\.)*''b'"(?:[^"\\]|\\.)*"'u'"(?:[^"\\]|\\.)*"'b'Split a string up according to Unix shell-like rules for quotes and + backslashes. In short: words are delimited by spaces, as long as those + spaces are not escaped by a backslash, or inside a quoted string. + Single and double quotes are equivalent, and the quote characters can + be backslash-escaped. The backslash is stripped from any two-character + escape sequence, leaving only the escaped character. The quote + characters are stripped from any quoted string. Returns a list of + words. + 'u'Split a string up according to Unix shell-like rules for quotes and + backslashes. In short: words are delimited by spaces, as long as those + spaces are not escaped by a backslash, or inside a quoted string. + Single and double quotes are equivalent, and the quote characters can + be backslash-escaped. The backslash is stripped from any two-character + escape sequence, leaving only the escaped character. The quote + characters are stripped from any quoted string. Returns a list of + words. + 'b'this can't happen (bad char '%c')'u'this can't happen (bad char '%c')'b'bad string (mismatched %s quotes?)'u'bad string (mismatched %s quotes?)'b'Perform some action that affects the outside world (eg. by + writing to the filesystem). Such actions are special because they + are disabled by the 'dry_run' flag. This method takes care of all + that bureaucracy for you; all you have to do is supply the + function to call and an argument tuple for it (to embody the + "external action" being performed), and an optional message to + print. + 'u'Perform some action that affects the outside world (eg. by + writing to the filesystem). Such actions are special because they + are disabled by the 'dry_run' flag. This method takes care of all + that bureaucracy for you; all you have to do is supply the + function to call and an argument tuple for it (to embody the + "external action" being performed), and an optional message to + print. + 'b'%s%r'u'%s%r'b'Convert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + 'u'Convert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + 'b'off'u'off'b'invalid truth value %r'u'invalid truth value %r'b'Byte-compile a collection of Python source files to .pyc + files in a __pycache__ subdirectory. 'py_files' is a list + of files to compile; any files that don't end in ".py" are silently + skipped. 'optimize' must be one of the following: + 0 - don't optimize + 1 - normal optimization (like "python -O") + 2 - extra optimization (like "python -OO") + If 'force' is true, all files are recompiled regardless of + timestamps. + + The source filename encoded in each bytecode file defaults to the + filenames listed in 'py_files'; you can modify these with 'prefix' and + 'basedir'. 'prefix' is a string that will be stripped off of each + source filename, and 'base_dir' is a directory name that will be + prepended (after 'prefix' is stripped). You can supply either or both + (or neither) of 'prefix' and 'base_dir', as you wish. + + If 'dry_run' is true, doesn't actually do anything that would + affect the filesystem. + + Byte-compilation is either done directly in this interpreter process + with the standard py_compile module, or indirectly by writing a + temporary script and executing it. Normally, you should let + 'byte_compile()' figure out to use direct compilation or not (see + the source for details). The 'direct' flag is used by the script + generated in indirect mode; unless you know what you're doing, leave + it set to None. + 'u'Byte-compile a collection of Python source files to .pyc + files in a __pycache__ subdirectory. 'py_files' is a list + of files to compile; any files that don't end in ".py" are silently + skipped. 'optimize' must be one of the following: + 0 - don't optimize + 1 - normal optimization (like "python -O") + 2 - extra optimization (like "python -OO") + If 'force' is true, all files are recompiled regardless of + timestamps. + + The source filename encoded in each bytecode file defaults to the + filenames listed in 'py_files'; you can modify these with 'prefix' and + 'basedir'. 'prefix' is a string that will be stripped off of each + source filename, and 'base_dir' is a directory name that will be + prepended (after 'prefix' is stripped). You can supply either or both + (or neither) of 'prefix' and 'base_dir', as you wish. + + If 'dry_run' is true, doesn't actually do anything that would + affect the filesystem. + + Byte-compilation is either done directly in this interpreter process + with the standard py_compile module, or indirectly by writing a + temporary script and executing it. Normally, you should let + 'byte_compile()' figure out to use direct compilation or not (see + the source for details). The 'direct' flag is used by the script + generated in indirect mode; unless you know what you're doing, leave + it set to None. + 'b'byte-compiling is disabled.'u'byte-compiling is disabled.'b'writing byte-compilation script '%s''u'writing byte-compilation script '%s''b'from distutils.util import byte_compile +files = [ +'u'from distutils.util import byte_compile +files = [ +'b' +byte_compile(files, optimize=%r, force=%r, + prefix=%r, base_dir=%r, + verbose=%r, dry_run=0, + direct=1) +'u' +byte_compile(files, optimize=%r, force=%r, + prefix=%r, base_dir=%r, + verbose=%r, dry_run=0, + direct=1) +'b'removing %s'u'removing %s'b'invalid prefix: filename %r doesn't start with %r'u'invalid prefix: filename %r doesn't start with %r'b'byte-compiling %s to %s'u'byte-compiling %s to %s'b'skipping byte-compilation of %s to %s'u'skipping byte-compilation of %s to %s'b'Return a version of the string escaped for inclusion in an + RFC-822 header, by ensuring there are 8 spaces space after each newline. + 'u'Return a version of the string escaped for inclusion in an + RFC-822 header, by ensuring there are 8 spaces space after each newline. + 'b'Invoke 2to3 on a list of Python files. + The files should all come from the build area, as the + modification is done in-place. To reduce the build time, + only files modified since the last invocation of this + function should be passed in the files argument.'u'Invoke 2to3 on a list of Python files. + The files should all come from the build area, as the + modification is done in-place. To reduce the build time, + only files modified since the last invocation of this + function should be passed in the files argument.'b'lib2to3.fixes'u'lib2to3.fixes'b'Recursively copy a directory, only copying new and changed files, + running run_2to3 over all newly copied Python modules afterward. + + If you give a template string, it's parsed like a MANIFEST.in. + 'u'Recursively copy a directory, only copying new and changed files, + running run_2to3 over all newly copied Python modules afterward. + + If you give a template string, it's parsed like a MANIFEST.in. + 'b'Mixin class for commands that run 2to3. + To configure 2to3, setup scripts may either change + the class variables, or inherit from individual commands + to override how 2to3 is invoked.'u'Mixin class for commands that run 2to3. + To configure 2to3, setup scripts may either change + the class variables, or inherit from individual commands + to override how 2to3 is invoked.'u'distutils.util'Miscellaneous utilities.decode_rfc2231formataddrformat_datetimegetaddressesmake_msgidparseaddremail._parseaddr_AddressListemail.charsetUEMPTYSTRINGTICK[][\\()<>@,:;".]specialsre[\\"]escapesreReturn True if s contains surrogate-escaped binary data._sanitizeThe inverse of parseaddr(), this takes a 2-tuple of the form + (realname, email_address) and returns the string value suitable + for an RFC 2822 From, To or Cc header. + + If the first element of pair is false, then the second element is + returned unmodified. + + The optional charset is the character set that is used to encode + realname in case realname is not ASCII safe. Can be an instance of str or + a Charset-like object which has a header_encode method. Default is + 'utf-8'. + \\\g<0>%s%s%s <%s>encoded_name%s <%s>fieldvaluesReturn a list of (REALNAME, EMAIL) for each fieldvalue._format_timetuple_and_zone%s, %02d %s %04d %02d:%02d:%02d %stimevalReturns a date string as specified by RFC 2822, e.g.: + + Fri, 09 Nov 2001 01:08:47 -0000 + + Optional timeval if given is a floating point time value as accepted by + gmtime() and localtime(), otherwise the current time is used. + + Optional localtime is a flag that when True, interprets timeval, and + returns a date relative to the local timezone instead of UTC, properly + taking daylight savings time into account. + + Optional argument usegmt means that the timezone is written out as + an ascii string, not numeric one (so "GMT" instead of "+0000"). This + is needed for HTTP, and is only used when localtime==False. + Turn a datetime into a date string as specified in RFC 2822. + + If usegmt is True, dt must be an aware datetime with an offset of zero. In + this case 'GMT' will be rendered instead of the normal +0000 required by + RFC2822. This is to support HTTP headers involving date stamps. + usegmt option requires a UTC datetime-0000%zReturns a string suitable for RFC 2822 compliant Message-ID, e.g: + + <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> + + Optional idstring if given is a string used to strengthen the + uniqueness of the message id. Optional domain if given provides the + portion of the message id after the '@'. It defaults to the locally + defined hostname. + <%d.%d.%d%s@%s>msgiddtuple + Parse addr into its constituent realname and email address parts. + + Return a tuple of realname and email address, unless the parse fails, in + which case return a 2-tuple of ('', ''). + addrsRemove quotes from a string.Decode string according to RFC 2231Encode string according to RFC 2231. + + If neither charset nor language is given, then s is returned as-is. If + charset is given but not language, the string is encoded using the empty + string for language. + %s'%s'%s^(?P\w+)\*((?P[0-9]+)\*?)?$rfc2231_continuationDecode parameters list according to RFC 2231. + + params is a sequence of 2-tuples containing (param name, string value). + rfc2231_paramscontinuationsfallback_charsetrawbytesisdstReturn local time as an aware datetime object. + + If called without arguments, return current time. Otherwise *dt* + argument should be a datetime instance, and it is converted to the + local time zone according to the system time zone database. If *dt* is + naive (that is, dt.tzinfo is None), it is assumed to be in local time. + In this case, a positive or zero value for *isdst* causes localtime to + presume initially that summer time (for example, Daylight Saving Time) + is or is not (respectively) in effect for the specified time. A + negative value for *isdst* causes the localtime() function to attempt + to divine whether summer time is in effect for the specified time. + + # Copyright (C) 2001-2010 Python Software Foundation# This check is based on the fact that unless there are surrogates, utf8# (Python's default encoding) can encode any string. This is the fastest# way to check for surrogates, see issue 11454 for timings.# How to deal with a string containing bytes before handing it to the# application through the 'normal' interface.# Turn any escaped bytes into unicode 'unknown' char. If the escaped# bytes happen to be utf-8 they will instead get decoded, even if they# were invalid in the charset the source was supposed to be in. This# seems like it is not a bad thing; a defect was still registered.# The address MUST (per RFC) be ascii, so raise a UnicodeError if it isn't.# Note: we cannot use strftime() because that honors the locale and RFC# 2822 requires that day and month names be the English abbreviations.# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.# RFC2231-related functions - parameter encoding and decoding# Copy params so we don't mess with the original# Map parameter's name to a list of continuations. The values are a# 3-tuple of the continuation number, the string value, and a flag# specifying whether a particular segment is %-encoded.# Sort by number# And now append all values in numerical order, converting# %-encodings for the encoded segments. If any of the# continuation names ends in a *, then the entire string, after# decoding segments and concatenating, must have the charset and# language specifiers at the beginning of the string.# Decode as "latin-1", so the characters in s directly# represent the percent-encoded octet values.# collapse_rfc2231_value treats this as an octet sequence.# While value comes to us as a unicode string, we need it to be a bytes# object. We do not want bytes() normal utf-8 decoder, we want a straight# interpretation of the string as character bytes.# Issue 17369: if charset/lang is None, decode_rfc2231 couldn't parse# the value, so use the fallback_charset.# charset is not a known codec.# datetime doesn't provide a localtime function yet, so provide one. Code# adapted from the patch in issue 9527. This may not be perfect, but it is# better than not having it.# We have a naive datetime. Convert to a (localtime) timetuple and pass to# system mktime together with the isdst hint. System mktime will return# seconds since epoch.# Compute UTC offset and compare with the value implied by tm_isdst.# If the values match, use the zone name implied by tm_isdst.b'Miscellaneous utilities.'u'Miscellaneous utilities.'b'collapse_rfc2231_value'u'collapse_rfc2231_value'b'decode_params'u'decode_params'b'decode_rfc2231'u'decode_rfc2231'b'encode_rfc2231'u'encode_rfc2231'b'formataddr'u'formataddr'b'formatdate'u'formatdate'b'format_datetime'u'format_datetime'b'getaddresses'u'getaddresses'b'make_msgid'u'make_msgid'b'parseaddr'u'parseaddr'b'parsedate_to_datetime'u'parsedate_to_datetime'b'[][\\()<>@,:;".]'u'[][\\()<>@,:;".]'b'[\\"]'u'[\\"]'b'Return True if s contains surrogate-escaped binary data.'u'Return True if s contains surrogate-escaped binary data.'b'The inverse of parseaddr(), this takes a 2-tuple of the form + (realname, email_address) and returns the string value suitable + for an RFC 2822 From, To or Cc header. + + If the first element of pair is false, then the second element is + returned unmodified. + + The optional charset is the character set that is used to encode + realname in case realname is not ASCII safe. Can be an instance of str or + a Charset-like object which has a header_encode method. Default is + 'utf-8'. + 'u'The inverse of parseaddr(), this takes a 2-tuple of the form + (realname, email_address) and returns the string value suitable + for an RFC 2822 From, To or Cc header. + + If the first element of pair is false, then the second element is + returned unmodified. + + The optional charset is the character set that is used to encode + realname in case realname is not ASCII safe. Can be an instance of str or + a Charset-like object which has a header_encode method. Default is + 'utf-8'. + 'b'\\\g<0>'u'\\\g<0>'b'%s%s%s <%s>'u'%s%s%s <%s>'b'%s <%s>'u'%s <%s>'b'Return a list of (REALNAME, EMAIL) for each fieldvalue.'u'Return a list of (REALNAME, EMAIL) for each fieldvalue.'b'%s, %02d %s %04d %02d:%02d:%02d %s'u'%s, %02d %s %04d %02d:%02d:%02d %s'b'Returns a date string as specified by RFC 2822, e.g.: + + Fri, 09 Nov 2001 01:08:47 -0000 + + Optional timeval if given is a floating point time value as accepted by + gmtime() and localtime(), otherwise the current time is used. + + Optional localtime is a flag that when True, interprets timeval, and + returns a date relative to the local timezone instead of UTC, properly + taking daylight savings time into account. + + Optional argument usegmt means that the timezone is written out as + an ascii string, not numeric one (so "GMT" instead of "+0000"). This + is needed for HTTP, and is only used when localtime==False. + 'u'Returns a date string as specified by RFC 2822, e.g.: + + Fri, 09 Nov 2001 01:08:47 -0000 + + Optional timeval if given is a floating point time value as accepted by + gmtime() and localtime(), otherwise the current time is used. + + Optional localtime is a flag that when True, interprets timeval, and + returns a date relative to the local timezone instead of UTC, properly + taking daylight savings time into account. + + Optional argument usegmt means that the timezone is written out as + an ascii string, not numeric one (so "GMT" instead of "+0000"). This + is needed for HTTP, and is only used when localtime==False. + 'b'Turn a datetime into a date string as specified in RFC 2822. + + If usegmt is True, dt must be an aware datetime with an offset of zero. In + this case 'GMT' will be rendered instead of the normal +0000 required by + RFC2822. This is to support HTTP headers involving date stamps. + 'u'Turn a datetime into a date string as specified in RFC 2822. + + If usegmt is True, dt must be an aware datetime with an offset of zero. In + this case 'GMT' will be rendered instead of the normal +0000 required by + RFC2822. This is to support HTTP headers involving date stamps. + 'b'usegmt option requires a UTC datetime'u'usegmt option requires a UTC datetime'b'-0000'u'-0000'b'%z'u'%z'b'Returns a string suitable for RFC 2822 compliant Message-ID, e.g: + + <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> + + Optional idstring if given is a string used to strengthen the + uniqueness of the message id. Optional domain if given provides the + portion of the message id after the '@'. It defaults to the locally + defined hostname. + 'u'Returns a string suitable for RFC 2822 compliant Message-ID, e.g: + + <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> + + Optional idstring if given is a string used to strengthen the + uniqueness of the message id. Optional domain if given provides the + portion of the message id after the '@'. It defaults to the locally + defined hostname. + 'b'<%d.%d.%d%s@%s>'u'<%d.%d.%d%s@%s>'b' + Parse addr into its constituent realname and email address parts. + + Return a tuple of realname and email address, unless the parse fails, in + which case return a 2-tuple of ('', ''). + 'u' + Parse addr into its constituent realname and email address parts. + + Return a tuple of realname and email address, unless the parse fails, in + which case return a 2-tuple of ('', ''). + 'b'Remove quotes from a string.'u'Remove quotes from a string.'b'Decode string according to RFC 2231'u'Decode string according to RFC 2231'b'Encode string according to RFC 2231. + + If neither charset nor language is given, then s is returned as-is. If + charset is given but not language, the string is encoded using the empty + string for language. + 'u'Encode string according to RFC 2231. + + If neither charset nor language is given, then s is returned as-is. If + charset is given but not language, the string is encoded using the empty + string for language. + 'b'%s'%s'%s'u'%s'%s'%s'b'^(?P\w+)\*((?P[0-9]+)\*?)?$'u'^(?P\w+)\*((?P[0-9]+)\*?)?$'b'Decode parameters list according to RFC 2231. + + params is a sequence of 2-tuples containing (param name, string value). + 'u'Decode parameters list according to RFC 2231. + + params is a sequence of 2-tuples containing (param name, string value). + 'b'Return local time as an aware datetime object. + + If called without arguments, return current time. Otherwise *dt* + argument should be a datetime instance, and it is converted to the + local time zone according to the system time zone database. If *dt* is + naive (that is, dt.tzinfo is None), it is assumed to be in local time. + In this case, a positive or zero value for *isdst* causes localtime to + presume initially that summer time (for example, Daylight Saving Time) + is or is not (respectively) in effect for the specified time. A + negative value for *isdst* causes the localtime() function to attempt + to divine whether summer time is in effect for the specified time. + + 'u'Return local time as an aware datetime object. + + If called without arguments, return current time. Otherwise *dt* + argument should be a datetime instance, and it is converted to the + local time zone according to the system time zone database. If *dt* is + naive (that is, dt.tzinfo is None), it is assumed to be in local time. + In this case, a positive or zero value for *isdst* causes localtime to + presume initially that summer time (for example, Daylight Saving Time) + is or is not (respectively) in effect for the specified time. A + negative value for *isdst* causes the localtime() function to attempt + to divine whether summer time is in effect for the specified time. + + 'u'email.utils'Implementation of the UUencode and UUdecode functions. + +encode(in_file, out_file [,name, mode], *, backtick=False) +decode(in_file [, out_file, mode, quiet]) +backtickUuencode fileopened_filesbegin %o %s +` +end + +end +Decode uuencoded fileNo valid begin line found in input filehdrfields + Cannot overwrite existing file: %sWarning: %s +Truncated input fileuuencode/uudecode main programoptparseusage: %prog [-d] [-t] [input [output]]--decodeDecode (instead of encode)?--textdata is text, encoded format unix-compatible text?: cannot do -t to stdout: cannot do -t from stdin# Copyright 1994 by Lance Ellinghouse# Cathedral City, California Republic, United States of America.# All Rights Reserved# supporting documentation, and that the name of Lance Ellinghouse# LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND# FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE# FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT# Modified by Jack Jansen, CWI, July 1995:# - Use binascii module to do the actual line-by-line conversion# between ascii and binary. This results in a 1000-fold speedup. The C# version is still 5 times faster, though.# - Arguments more compliant with python standard# If in_file is a pathname open it and change defaults# Open out_file if it is a pathname# Set defaults for name and mode# Remove newline chars from name# Write the data# Open the input file, if needed.# Read until a begin is encountered or we've exhausted the file# If the filename isn't ASCII, what's up with that?!?# Open the output file# Main decoding loop# Workaround for broken uuencoders by /Fredrik Lundh# Use the binary streams underlying stdin/stdoutb'Implementation of the UUencode and UUdecode functions. + +encode(in_file, out_file [,name, mode], *, backtick=False) +decode(in_file [, out_file, mode, quiet]) +'u'Implementation of the UUencode and UUdecode functions. + +encode(in_file, out_file [,name, mode], *, backtick=False) +decode(in_file [, out_file, mode, quiet]) +'b'Uuencode file'u'Uuencode file'b'begin %o %s +'u'begin %o %s +'b'` +end +'b' +end +'b'Decode uuencoded file'u'Decode uuencoded file'b'No valid begin line found in input file'u'No valid begin line found in input file'b'begin'b' + 'b'Cannot overwrite existing file: %s'u'Cannot overwrite existing file: %s'b'Warning: %s +'u'Warning: %s +'b'Truncated input file'u'Truncated input file'b'uuencode/uudecode main program'u'uuencode/uudecode main program'b'usage: %prog [-d] [-t] [input [output]]'u'usage: %prog [-d] [-t] [input [output]]'b'--decode'u'--decode'b'Decode (instead of encode)?'u'Decode (instead of encode)?'b'--text'u'--text'b'data is text, encoded format unix-compatible text?'u'data is text, encoded format unix-compatible text?'b': cannot do -t to stdout'u': cannot do -t to stdout'b': cannot do -t from stdin'u': cannot do -t from stdin'Python part of the warnings subsystem.resetwarningsHook to write a warning to a file; replace if you like._showwarnmsg_implFunction to format a warning the standard way._formatwarnmsg_impl_formatwarnmsg %s +tracingObject allocated at (most recent call last): + File "%s", lineno %s + %s +: Enable tracemalloc to get the object allocation traceback +': Enable tracemalloc to get the object ''allocation traceback\n'_showwarning_orig_showwarnmsgwarnings.showwarning() must be set to a function or method"warnings.showwarning() must be set to a ""function or method"_formatwarning_origInsert an entry into the list of warnings filters (at the front). + + 'action' -- one of "error", "ignore", "always", "default", "module", + or "once" + 'message' -- a regex that the warning message must match + 'category' -- a class that the warning must be a subclass of + 'module' -- a regex that the module name must match + 'lineno' -- an integer line number, 0 matches all warnings + 'append' -- if true, append to the list of filters + oncemessage must be a stringcategory must be a classcategory must be a Warning subclassmodule must be a stringlineno must be an int >= 0_add_filterInsert a simple entry into the list of warnings filters (at the front). + + A simple filter matches all modules and messages. + 'action' -- one of "error", "ignore", "always", "default", "module", + or "once" + 'category' -- a class that the warning must be a subclass of + 'lineno' -- an integer line number, 0 matches all warnings + 'append' -- if true, append to the list of filters + Clear the list of warning filters, so that no filters are active._OptionErrorException used by option processing helpers._processoptions_setoptionInvalid -W option ignored:too many fields (max 5): %r_getaction_getcategoryinvalid lineno %rinvalid module name: %runknown warning category: %rinvalid warning category: %r_is_internal_frameSignal whether the frame is an internal CPython implementation detail._next_external_frameFind the next frame that doesn't involve CPython internals.Issue a warning, or maybe ignore it or raise an exception.category must be a Warning subclass, not '{:s}'"category must be a Warning subclass, ""not '{:s}'"_filters_versiondefaultactiononcekeyonceregistryaltkeyUnrecognized action (%r) in warnings.filters: + %s_category_name{message : %r, category : %r, filename : %r, lineno : %s, line : %r}"{message : %r, category : %r, filename : %r, lineno : %s, ""line : %r}"A context manager that copies and restores the warnings filter upon + exiting the context. + + The 'record' argument specifies whether warnings should be captured by a + custom implementation of warnings.showwarning() and be appended to a list + returned by the context manager. Otherwise None is returned by the context + manager. The objects appended to the list are arguments whose attributes + mirror the arguments to showwarning(). + + The 'module' argument is to specify an alternative module to the module + named 'warnings' and imported under that name. This argument is only useful + when testing the warnings module itself. + + Specify whether to record warnings and if an alternative module + should be used other than sys.modules['warnings']. + + For compatibility with Python 3.0, please consider all arguments to be + keyword-only. + + _record_module_enteredrecord=Truemodule=%rCannot enter %r twice_filtersCannot exit %r without entering first_warn_unawaited_coroutinecoroutine '' was never awaited +msg_linescr_originCoroutine created at (most recent call last) +_warnings_defaults# sys.stderr is None when run with pythonw.exe:# warnings get lost# the file (probably stderr) is invalid - this warning gets lost.# When a warning is logged during Python shutdown, linecache# and the import machinery don't work anymore# Logging a warning should not raise a new exception:# catch Exception, not only ImportError and RecursionError.# don't suggest to enable tracemalloc if it's not available# When a warning is logged during Python shutdown, tracemalloc# Keep a reference to check if the function was replaced# warnings.showwarning() was replaced# warnings.formatwarning() was replaced# Remove possible duplicate filters, so new one will be placed# in correct place. If append=True and duplicate exists, do nothing.# Helper to process -W options passed via sys.warnoptions# Helper for _processoptions()# Helper for _setoption()# Alias# Code typically replaced by _warnings# Check if message is already a Warning object# Check category argument# Get context information# If frame is too small to care or if the warning originated in# internal code, then do not try to hide any frames.# Look for one frame less since the above line starts us off.# XXX What about leading pathname?# Quick test for common case# Search the filters# Early exit actions# Prime the linecache for formatting, in case the# "file" is actually in a zipfile or something.# Other actions# Unrecognized actions are errors# Print message and context# Reset showwarning() to the default implementation to make sure# that _showwarnmsg() calls _showwarnmsg_impl()# Private utility function called by _PyErr_WarnUnawaitedCoroutine# Passing source= here means that if the user happens to have tracemalloc# enabled and tracking where the coroutine was created, the warning will# contain that traceback. This does mean that if they have *both*# coroutine origin tracking *and* tracemalloc enabled, they'll get two# partially-redundant tracebacks. If we wanted to be clever we could# probably detect this case and avoid it, but for now we don't bother.# filters contains a sequence of filter 5-tuples# The components of the 5-tuple are:# - an action: error, ignore, always, default, module, or once# - a compiled regex that must match the warning message# - a class representing the warning category# - a compiled regex that must match the module that is being warned# - a line number for the line being warning, or 0 to mean any line# If either if the compiled regexs are None, match anything.# Module initialization# Several warning categories are ignored by default in regular buildsb'Python part of the warnings subsystem.'u'Python part of the warnings subsystem.'b'warn_explicit'u'warn_explicit'b'showwarning'u'showwarning'b'formatwarning'u'formatwarning'b'filterwarnings'u'filterwarnings'b'simplefilter'u'simplefilter'b'resetwarnings'u'resetwarnings'b'catch_warnings'u'catch_warnings'b'Hook to write a warning to a file; replace if you like.'u'Hook to write a warning to a file; replace if you like.'b'Function to format a warning the standard way.'u'Function to format a warning the standard way.'b' %s +'u' %s +'b'Object allocated at (most recent call last): +'u'Object allocated at (most recent call last): +'b' File "%s", lineno %s +'u' File "%s", lineno %s +'b' %s +'u' %s +'b': Enable tracemalloc to get the object allocation traceback +'u': Enable tracemalloc to get the object allocation traceback +'b'warnings.showwarning() must be set to a function or method'u'warnings.showwarning() must be set to a function or method'b'Insert an entry into the list of warnings filters (at the front). + + 'action' -- one of "error", "ignore", "always", "default", "module", + or "once" + 'message' -- a regex that the warning message must match + 'category' -- a class that the warning must be a subclass of + 'module' -- a regex that the module name must match + 'lineno' -- an integer line number, 0 matches all warnings + 'append' -- if true, append to the list of filters + 'u'Insert an entry into the list of warnings filters (at the front). + + 'action' -- one of "error", "ignore", "always", "default", "module", + or "once" + 'message' -- a regex that the warning message must match + 'category' -- a class that the warning must be a subclass of + 'module' -- a regex that the module name must match + 'lineno' -- an integer line number, 0 matches all warnings + 'append' -- if true, append to the list of filters + 'b'once'u'once'b'message must be a string'u'message must be a string'b'category must be a class'u'category must be a class'b'category must be a Warning subclass'u'category must be a Warning subclass'b'module must be a string'u'module must be a string'b'lineno must be an int >= 0'u'lineno must be an int >= 0'b'Insert a simple entry into the list of warnings filters (at the front). + + A simple filter matches all modules and messages. + 'action' -- one of "error", "ignore", "always", "default", "module", + or "once" + 'category' -- a class that the warning must be a subclass of + 'lineno' -- an integer line number, 0 matches all warnings + 'append' -- if true, append to the list of filters + 'u'Insert a simple entry into the list of warnings filters (at the front). + + A simple filter matches all modules and messages. + 'action' -- one of "error", "ignore", "always", "default", "module", + or "once" + 'category' -- a class that the warning must be a subclass of + 'lineno' -- an integer line number, 0 matches all warnings + 'append' -- if true, append to the list of filters + 'b'Clear the list of warning filters, so that no filters are active.'u'Clear the list of warning filters, so that no filters are active.'b'Exception used by option processing helpers.'u'Exception used by option processing helpers.'b'Invalid -W option ignored:'u'Invalid -W option ignored:'b'too many fields (max 5): %r'u'too many fields (max 5): %r'b'invalid lineno %r'u'invalid lineno %r'b'invalid module name: %r'u'invalid module name: %r'b'unknown warning category: %r'u'unknown warning category: %r'b'invalid warning category: %r'u'invalid warning category: %r'b'Signal whether the frame is an internal CPython implementation detail.'u'Signal whether the frame is an internal CPython implementation detail.'b'_bootstrap'b'Find the next frame that doesn't involve CPython internals.'u'Find the next frame that doesn't involve CPython internals.'b'Issue a warning, or maybe ignore it or raise an exception.'u'Issue a warning, or maybe ignore it or raise an exception.'b'category must be a Warning subclass, not '{:s}''u'category must be a Warning subclass, not '{:s}''b'Unrecognized action (%r) in warnings.filters: + %s'u'Unrecognized action (%r) in warnings.filters: + %s'b'category'u'category'b'{message : %r, category : %r, filename : %r, lineno : %s, line : %r}'u'{message : %r, category : %r, filename : %r, lineno : %s, line : %r}'b'A context manager that copies and restores the warnings filter upon + exiting the context. + + The 'record' argument specifies whether warnings should be captured by a + custom implementation of warnings.showwarning() and be appended to a list + returned by the context manager. Otherwise None is returned by the context + manager. The objects appended to the list are arguments whose attributes + mirror the arguments to showwarning(). + + The 'module' argument is to specify an alternative module to the module + named 'warnings' and imported under that name. This argument is only useful + when testing the warnings module itself. + + 'u'A context manager that copies and restores the warnings filter upon + exiting the context. + + The 'record' argument specifies whether warnings should be captured by a + custom implementation of warnings.showwarning() and be appended to a list + returned by the context manager. Otherwise None is returned by the context + manager. The objects appended to the list are arguments whose attributes + mirror the arguments to showwarning(). + + The 'module' argument is to specify an alternative module to the module + named 'warnings' and imported under that name. This argument is only useful + when testing the warnings module itself. + + 'b'Specify whether to record warnings and if an alternative module + should be used other than sys.modules['warnings']. + + For compatibility with Python 3.0, please consider all arguments to be + keyword-only. + + 'u'Specify whether to record warnings and if an alternative module + should be used other than sys.modules['warnings']. + + For compatibility with Python 3.0, please consider all arguments to be + keyword-only. + + 'b'record=True'u'record=True'b'module=%r'u'module=%r'b'Cannot enter %r twice'u'Cannot enter %r twice'b'Cannot exit %r without entering first'u'Cannot exit %r without entering first'b'coroutine ''u'coroutine ''b'' was never awaited +'u'' was never awaited +'b'Coroutine created at (most recent call last) +'u'Coroutine created at (most recent call last) +'Weak reference support for Python. + +This module is an implementation of PEP 205: + +http://www.python.org/dev/peps/pep-0205/ +ProxyTypesWeakMethod + A custom `weakref.ref` subclass which simulates a weak reference to + a bound method, working around the lifetime problem of bound methods. + _func_ref_meth_type_aliveargument should be a bound method, not {}_cbself_wrMapping class that references values weakly. + + Entries in the dictionary will be discarded when no strong + reference to the value exists anymore + _atomic_removalKeyedRefitervaluerefsReturn an iterator that yields the weak references to the values. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the values around longer than needed. + + valuerefsReturn a list of weak references to the values. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the values around longer than needed. + + Specialized reference that includes a key corresponding to the value. + + This is used in the WeakValueDictionary to avoid having to create + a function object for each key stored in the mapping. A shared + callback object can use the 'key' attribute of a KeyedRef instead + of getting a reference to the key from an enclosing scope. + + ob Mapping class that references keys weakly. + + Entries in the dictionary will be discarded when there is no + longer a strong reference to the key. This can be used to + associate additional data with an object owned by other parts of + an application without adding attributes to those objects. This + can be especially useful with objects that override attribute + accesses. + _dirty_len_scrub_removalskeyrefsReturn a list of weak references to the keys. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the keys around longer than needed. + + Class for finalization of weakrefable objects + + finalize(obj, func, *args, **kwargs) returns a callable finalizer + object which will be called when obj is garbage collected. The + first time the finalizer is called it evaluates func(*arg, **kwargs) + and returns the result. After this the finalizer is dead, and + calling it just returns None. + + When the program exits any remaining finalizers for which the + atexit attribute is true will be run in reverse order of creation. + By default atexit is true. + _registry_index_iter_dirty_registered_with_atexit_Infodescriptor '__init__' of 'finalize' object needs an argument"descriptor '__init__' of 'finalize' object "finalize expected at least 2 positional arguments, got %d'finalize expected at least 2 positional ''arguments, got %d'Passing 'obj' as keyword argument is deprecated_exitfunc($self, obj, func, /, *args, **kwargs)If alive then mark as dead and return func(*args, **kwargs); + otherwise return NoneIf alive then mark as dead and return (obj, func, args, kwargs); + otherwise return NoneIf alive then return (obj, func, args, kwargs); + otherwise return NonealiveWhether finalizer is aliveWhether finalizer should be called at exit<%s object at %#x; dead><%s object at %#x; for %r at %#x>_select_for_exitreenable_gc# Naming convention: Variables named "wr" are weak reference objects;# they are called this instead of "ref" to avoid name collisions with# the module-global ref() function imported from _weakref.# Import after _weakref to avoid circular import.# The self-weakref trick is needed to avoid creating a reference# cycle.# We inherit the constructor without worrying about the input# dictionary; since it uses our .update() method, we get the right# checks (if the other dictionary is a WeakValueDictionary,# objects are unwrapped on the way out, and we always wrap on the# way in).# Atomic removal is necessary since this function# can be called asynchronously by the GC# We shouldn't encounter any KeyError, because this method should# always be called *before* mutating the dict.# This should only happen# A list of dead weakrefs (keys to be removed)# NOTE: We don't need to call this method before mutating the dict,# because a dead weakref never compares equal to a live weakref,# even if they happened to refer to equal objects.# However, it means keys may already have been removed.# self._pending_removals may still contain keys which were# explicitly removed, we have to scrub them (see issue #21173).# Finalizer objects don't have any state of their own. They are# just used as keys to lookup _Info objects in the registry. This# ensures that they cannot be part of a ref-cycle.# We may register the exit function more than once because# of a thread race, but that is harmless# Return live finalizers marked for exit, oldest first# At shutdown invoke finalizers for which atexit is true.# This is called once all other non-daemonic threads have been# joined.# gc is disabled, so (assuming no daemonic# threads) the following is the only line in# this function which might trigger creation# of a new finalizer# prevent any more finalizers from executing during shutdownb'Weak reference support for Python. + +This module is an implementation of PEP 205: + +http://www.python.org/dev/peps/pep-0205/ +'u'Weak reference support for Python. + +This module is an implementation of PEP 205: + +http://www.python.org/dev/peps/pep-0205/ +'b'ref'u'ref'b'getweakrefcount'u'getweakrefcount'b'getweakrefs'u'getweakrefs'b'WeakKeyDictionary'u'WeakKeyDictionary'b'ReferenceType'u'ReferenceType'b'ProxyType'u'ProxyType'b'CallableProxyType'u'CallableProxyType'b'ProxyTypes'u'ProxyTypes'b'WeakValueDictionary'u'WeakValueDictionary'b'WeakMethod'u'WeakMethod'b'finalize'u'finalize'b' + A custom `weakref.ref` subclass which simulates a weak reference to + a bound method, working around the lifetime problem of bound methods. + 'u' + A custom `weakref.ref` subclass which simulates a weak reference to + a bound method, working around the lifetime problem of bound methods. + 'b'_func_ref'u'_func_ref'b'_meth_type'u'_meth_type'b'_alive'u'_alive'b'argument should be a bound method, not {}'u'argument should be a bound method, not {}'b'Mapping class that references values weakly. + + Entries in the dictionary will be discarded when no strong + reference to the value exists anymore + 'u'Mapping class that references values weakly. + + Entries in the dictionary will be discarded when no strong + reference to the value exists anymore + 'b'Return an iterator that yields the weak references to the values. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the values around longer than needed. + + 'u'Return an iterator that yields the weak references to the values. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the values around longer than needed. + + 'b'Return a list of weak references to the values. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the values around longer than needed. + + 'u'Return a list of weak references to the values. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the values around longer than needed. + + 'b'Specialized reference that includes a key corresponding to the value. + + This is used in the WeakValueDictionary to avoid having to create + a function object for each key stored in the mapping. A shared + callback object can use the 'key' attribute of a KeyedRef instead + of getting a reference to the key from an enclosing scope. + + 'u'Specialized reference that includes a key corresponding to the value. + + This is used in the WeakValueDictionary to avoid having to create + a function object for each key stored in the mapping. A shared + callback object can use the 'key' attribute of a KeyedRef instead + of getting a reference to the key from an enclosing scope. + + 'b' Mapping class that references keys weakly. + + Entries in the dictionary will be discarded when there is no + longer a strong reference to the key. This can be used to + associate additional data with an object owned by other parts of + an application without adding attributes to those objects. This + can be especially useful with objects that override attribute + accesses. + 'u' Mapping class that references keys weakly. + + Entries in the dictionary will be discarded when there is no + longer a strong reference to the key. This can be used to + associate additional data with an object owned by other parts of + an application without adding attributes to those objects. This + can be especially useful with objects that override attribute + accesses. + 'b'Return a list of weak references to the keys. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the keys around longer than needed. + + 'u'Return a list of weak references to the keys. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the keys around longer than needed. + + 'b'Class for finalization of weakrefable objects + + finalize(obj, func, *args, **kwargs) returns a callable finalizer + object which will be called when obj is garbage collected. The + first time the finalizer is called it evaluates func(*arg, **kwargs) + and returns the result. After this the finalizer is dead, and + calling it just returns None. + + When the program exits any remaining finalizers for which the + atexit attribute is true will be run in reverse order of creation. + By default atexit is true. + 'u'Class for finalization of weakrefable objects + + finalize(obj, func, *args, **kwargs) returns a callable finalizer + object which will be called when obj is garbage collected. The + first time the finalizer is called it evaluates func(*arg, **kwargs) + and returns the result. After this the finalizer is dead, and + calling it just returns None. + + When the program exits any remaining finalizers for which the + atexit attribute is true will be run in reverse order of creation. + By default atexit is true. + 'b'weakref'u'weakref'b'kwargs'u'kwargs'b'atexit'b'descriptor '__init__' of 'finalize' object needs an argument'u'descriptor '__init__' of 'finalize' object needs an argument'b'finalize expected at least 2 positional arguments, got %d'u'finalize expected at least 2 positional arguments, got %d'b'Passing 'obj' as keyword argument is deprecated'u'Passing 'obj' as keyword argument is deprecated'b'($self, obj, func, /, *args, **kwargs)'u'($self, obj, func, /, *args, **kwargs)'b'If alive then mark as dead and return func(*args, **kwargs); + otherwise return None'u'If alive then mark as dead and return func(*args, **kwargs); + otherwise return None'b'If alive then mark as dead and return (obj, func, args, kwargs); + otherwise return None'u'If alive then mark as dead and return (obj, func, args, kwargs); + otherwise return None'b'If alive then return (obj, func, args, kwargs); + otherwise return None'u'If alive then return (obj, func, args, kwargs); + otherwise return None'b'Whether finalizer is alive'u'Whether finalizer is alive'b'Whether finalizer should be called at exit'u'Whether finalizer should be called at exit'b'<%s object at %#x; dead>'u'<%s object at %#x; dead>'b'<%s object at %#x; for %r at %#x>'u'<%s object at %#x; for %r at %#x>'Interfaces for launching and remotely controlling Web browsers.open_newopen_new_tab_browsers_tryorder_os_preferred_browserpreferredRegister a browser connector.register_standard_browsersusingReturn a browser launcher instance appropriate for the environment.browserBackgroundBrowserGenericBrowser_synthesizecould not locate runnable browserautoraiseDisplay url using the default browser. + + If possible, open url in a location determined by new. + - 0: the same browser window (the default). + - 1: a new browser window. + - 2: a new browser page ("tab"). + If possible, autoraise raises the window (the default) or not. + Open url in a new window of the default browser. + + If not possible, then open url in the only browser window. + Open url in a new page ("tab") of the default browser. + + If not possible, then the behavior becomes equivalent to open_new(). + Attempt to synthesize a controller based on existing controllers. + + This is useful to create a controller when a user specifies a path to + an entry in the BROWSER environment variable -- we can copy a general + controller to operate using a specific installation of the desired + browser in this way. + + If we can't create a controller in this way, or if there is no + executable for the requested browser, return [None, None]. + + controllerBaseBrowserParent class for all browsers. Do not use directly.Class for all browsers started with a command + and without remote functionality.webbrowser.openClass for all browsers which are to be started in the + background.UnixBrowserParent class for all Unix browsers with remote functionality.raise_optsbackground%actionremote_argsremote_actionremote_action_newwinremote_action_newtab_invokeremoteraise_optinoutBad 'new' parameter to open(); expected 0, 1, or 2, got %sMozillaLauncher class for Mozilla browsers.-new-window-new-tabNetscapeLauncher class for Netscape browser.-noraise-raise-remoteopenURL(%s%action),new-window,new-tabGaleonLauncher class for Galeon/Epiphany browsers.ChromeLauncher class for Google Chrome browser.--new-windowChromiumOperaLauncher class for Opera browser.ElinksLauncher class for Elinks browsers.KonquerorController for the KDE File Manager (kfm, or Konqueror). + + See the output of ``kfmclient --commands`` + for more information on the Konqueror remote-control interface. + newTabopenURLkfmclientkonqueror--silentkfmGrail_find_grail_rc.grail-unixmaybes_remoteLOADNEW LOAD register_X_browsersxdg-openGNOME_DESKTOP_SESSION_IDgvfs-opengnome-openKDE_FULL_SESSIONx-www-browserfirefoxiceweaseliceapeseamonkeymozilla-firefoxmozilla-firebirdfirebirdmozillanetscapegaleonepiphanyskipstonegoogle-chromechromechromiumchromium-browseroperamosaicgrailMacOSXMacOSXOSAScriptsafariwindows-defaultWindowsDefaultPROGRAMFILESC:\Program FilesInternet Explorer\IEXPLORE.EXEiexploreDISPLAYWAYLAND_DISPLAYxdg-settings get default-web-browserraw_resultwww-browserelinkslynxw3mBROWSERuserchoicesstartfileLauncher class for Aqua browsers on Mac OS X + + Optionally specify a browser name on instantiation. Note that this + will not work for Aqua browsers if the user has moved the application + package after installation. + + If no browser is specified, the default browser, as specified in the + Internet System Preferences panel, will be used. + file:open location "%s"%22OmniWebtoWindowtoWindow %dOpenURL "%s"tell application "%s" + activate + %s %s + end tellosascriptosapipe + tell application "%s" + activate + open location "%s" + end + Usage: %s [-n | -t] url + -n: open new window + -t: open new tabntdnew_win# Maintained by Georg Brandl.# Dictionary of available browser controllers# Preference order of available browsers# The preferred browser# Preferred browsers go to the front of the list.# Need to match to the default browser returned by xdg-settings, which# may be of the form e.g. "firefox.desktop".# User gave us a command line, split it into name and args# User gave us a browser name or path.# Please note: the following definition hides a builtin function.# It is recommended one does "import webbrowser" and uses webbrowser.open(url)# instead of "from webbrowser import *".# now attempt to clone to fit the new name:# General parent classes# name should be a list with arguments# In remote_args, %s will be replaced with the requested URL. %action will# be replaced depending on the value of 'new' passed to open.# remote_action is used for new=0 (open). If newwin is not None, it is# used for new=1 (open_new). If newtab is not None, it is used for# new=3 (open_new_tab). After both substitutions are made, any empty# strings in the transformed remote_args list will be removed.# use autoraise argument only for remote invocation# for TTY browsers, we need stdin/out# wait at most five seconds. If the subprocess is not finished, the# remote invocation has (hopefully) started a new instance.# if remote call failed, open() will try direct invocation# remote invocation failed, try straight way# elinks doesn't like its stdout to be redirected -# it uses redirected stdout as a signal to do -dump# XXX Currently I know no way to prevent KFM from opening a new win.# fall through to next variant# kfmclient's return code unfortunately has no meaning as it seems# Should be running now.# There should be a way to maintain a connection to Grail, but the# Grail remote control protocol doesn't really allow that at this# point. It probably never will!# need to PING each one until we find one that's live# no good; attempt to clean it out, but don't fail:# Platform support for Unix# These are the right tests because all these Unix browsers require either# a console terminal or an X display to run.# use xdg-open if around# The default GNOME3 browser# The default GNOME browser# The default KDE browser# The Mozilla browsers# The Netscape and old Mozilla browsers# Konqueror/kfm, the KDE browser.# Gnome's Galeon and Epiphany# Skipstone, another Gtk/Mozilla based browser# Google Chrome/Chromium browsers# Opera, quite popular# Next, Mosaic -- old but still in use.# Grail, the Python browser. Does anybody still use it?# OS X can use below Unix support (but we prefer using the OS X# specific stuff)# First try to use the default Windows browser# Detect some common Windows browsers, fallback to IE# Prefer X browsers if present# Also try console browsers# The Links/elinks browsers # The Lynx browser , # The w3m browser # OK, now that we know what the default preference orders for each# platform are, allow user to override them with the BROWSER variable.# Treat choices in same way as if passed into get() but do register# and prepend to _tryorder# what to do if _tryorder is now empty?# Platform support for Windows# [Error 22] No application is associated with the specified# file for this operation: ''# Platform support for MacOS# Adapted from patch submitted to SourceForge by Steven J. Burr# hack for local urls# new must be 0 or 1# User called open, open_new or get without a browser parameter# opens in default browser# User called get and chose a browser# Include toWindow parameter of OpenURL command for browsers# that support it. 0 == new window; -1 == existing# Open pipe to AppleScript through osascript command# Write script to osascript's stdinb'Interfaces for launching and remotely controlling Web browsers.'u'Interfaces for launching and remotely controlling Web browsers.'b'open_new'u'open_new'b'open_new_tab'u'open_new_tab'b'Register a browser connector.'u'Register a browser connector.'b'Return a browser launcher instance appropriate for the environment.'u'Return a browser launcher instance appropriate for the environment.'b'could not locate runnable browser'u'could not locate runnable browser'b'Display url using the default browser. + + If possible, open url in a location determined by new. + - 0: the same browser window (the default). + - 1: a new browser window. + - 2: a new browser page ("tab"). + If possible, autoraise raises the window (the default) or not. + 'u'Display url using the default browser. + + If possible, open url in a location determined by new. + - 0: the same browser window (the default). + - 1: a new browser window. + - 2: a new browser page ("tab"). + If possible, autoraise raises the window (the default) or not. + 'b'Open url in a new window of the default browser. + + If not possible, then open url in the only browser window. + 'u'Open url in a new window of the default browser. + + If not possible, then open url in the only browser window. + 'b'Open url in a new page ("tab") of the default browser. + + If not possible, then the behavior becomes equivalent to open_new(). + 'u'Open url in a new page ("tab") of the default browser. + + If not possible, then the behavior becomes equivalent to open_new(). + 'b'Attempt to synthesize a controller based on existing controllers. + + This is useful to create a controller when a user specifies a path to + an entry in the BROWSER environment variable -- we can copy a general + controller to operate using a specific installation of the desired + browser in this way. + + If we can't create a controller in this way, or if there is no + executable for the requested browser, return [None, None]. + + 'u'Attempt to synthesize a controller based on existing controllers. + + This is useful to create a controller when a user specifies a path to + an entry in the BROWSER environment variable -- we can copy a general + controller to operate using a specific installation of the desired + browser in this way. + + If we can't create a controller in this way, or if there is no + executable for the requested browser, return [None, None]. + + 'b'Parent class for all browsers. Do not use directly.'u'Parent class for all browsers. Do not use directly.'b'Class for all browsers started with a command + and without remote functionality.'u'Class for all browsers started with a command + and without remote functionality.'b'webbrowser.open'u'webbrowser.open'b'Class for all browsers which are to be started in the + background.'u'Class for all browsers which are to be started in the + background.'b'Parent class for all Unix browsers with remote functionality.'u'Parent class for all Unix browsers with remote functionality.'b'%action'u'%action'b'Bad 'new' parameter to open(); 'u'Bad 'new' parameter to open(); 'b'expected 0, 1, or 2, got %s'u'expected 0, 1, or 2, got %s'b'Launcher class for Mozilla browsers.'u'Launcher class for Mozilla browsers.'b'-new-window'u'-new-window'b'-new-tab'u'-new-tab'b'Launcher class for Netscape browser.'u'Launcher class for Netscape browser.'b'-noraise'u'-noraise'b'-raise'u'-raise'b'-remote'u'-remote'b'openURL(%s%action)'u'openURL(%s%action)'b',new-window'u',new-window'b',new-tab'u',new-tab'b'Launcher class for Galeon/Epiphany browsers.'u'Launcher class for Galeon/Epiphany browsers.'b'Launcher class for Google Chrome browser.'u'Launcher class for Google Chrome browser.'b'--new-window'u'--new-window'b'Launcher class for Opera browser.'u'Launcher class for Opera browser.'b'Launcher class for Elinks browsers.'u'Launcher class for Elinks browsers.'b'Controller for the KDE File Manager (kfm, or Konqueror). + + See the output of ``kfmclient --commands`` + for more information on the Konqueror remote-control interface. + 'u'Controller for the KDE File Manager (kfm, or Konqueror). + + See the output of ``kfmclient --commands`` + for more information on the Konqueror remote-control interface. + 'b'newTab'u'newTab'b'openURL'u'openURL'b'kfmclient'u'kfmclient'b'konqueror'u'konqueror'b'--silent'u'--silent'b'kfm'u'kfm'b'.grail-unix'u'.grail-unix'b'LOADNEW 'u'LOADNEW 'b'LOAD 'u'LOAD 'b'xdg-open'u'xdg-open'b'GNOME_DESKTOP_SESSION_ID'u'GNOME_DESKTOP_SESSION_ID'b'gvfs-open'u'gvfs-open'b'gnome-open'u'gnome-open'b'KDE_FULL_SESSION'u'KDE_FULL_SESSION'b'x-www-browser'u'x-www-browser'b'firefox'u'firefox'b'iceweasel'u'iceweasel'b'iceape'u'iceape'b'seamonkey'u'seamonkey'b'mozilla-firefox'u'mozilla-firefox'b'mozilla-firebird'u'mozilla-firebird'b'firebird'u'firebird'b'mozilla'u'mozilla'b'netscape'u'netscape'b'galeon'u'galeon'b'epiphany'u'epiphany'b'skipstone'u'skipstone'b'google-chrome'u'google-chrome'b'chrome'u'chrome'b'chromium'u'chromium'b'chromium-browser'u'chromium-browser'b'opera'u'opera'b'mosaic'u'mosaic'b'grail'u'grail'b'MacOSX'u'MacOSX'b'safari'u'safari'b'windows-default'u'windows-default'b'PROGRAMFILES'u'PROGRAMFILES'b'C:\Program Files'u'C:\Program Files'b'Internet Explorer\IEXPLORE.EXE'u'Internet Explorer\IEXPLORE.EXE'b'DISPLAY'u'DISPLAY'b'WAYLAND_DISPLAY'u'WAYLAND_DISPLAY'b'xdg-settings get default-web-browser'u'xdg-settings get default-web-browser'b'www-browser'u'www-browser'b'links'u'links'b'elinks'u'elinks'b'lynx'u'lynx'b'w3m'u'w3m'b'BROWSER'u'BROWSER'b'Launcher class for Aqua browsers on Mac OS X + + Optionally specify a browser name on instantiation. Note that this + will not work for Aqua browsers if the user has moved the application + package after installation. + + If no browser is specified, the default browser, as specified in the + Internet System Preferences panel, will be used. + 'u'Launcher class for Aqua browsers on Mac OS X + + Optionally specify a browser name on instantiation. Note that this + will not work for Aqua browsers if the user has moved the application + package after installation. + + If no browser is specified, the default browser, as specified in the + Internet System Preferences panel, will be used. + 'b'file:'u'file:'b'open location "%s"'u'open location "%s"'b'%22'u'%22'b'OmniWeb'u'OmniWeb'b'toWindow %d'u'toWindow %d'b'OpenURL "%s"'u'OpenURL "%s"'b'tell application "%s" + activate + %s %s + end tell'u'tell application "%s" + activate + %s %s + end tell'b'osascript'u'osascript'b' + tell application "%s" + activate + open location "%s" + end + 'u' + tell application "%s" + activate + open location "%s" + end + 'b'Usage: %s [-n | -t] url + -n: open new window + -t: open new tab'u'Usage: %s [-n | -t] url + -n: open new window + -t: open new tab'b'ntd'u'ntd'u'webbrowser'Selector and proactor event loops for Windows._overlappedproactor_eventswindows_utilsProactorEventLoopIocpProactorWindowsSelectorEventLoopPolicyWindowsProactorEventLoopPolicy1225ERROR_CONNECTION_REFUSED1236ERROR_CONNECTION_ABORTEDCONNECT_PIPE_INIT_DELAY0.100CONNECT_PIPE_MAX_DELAY_OverlappedFutureSubclass of Future which represents an overlapped operation. + + Cancelling it will immediately cancel the overlapped operation. + _ovoverlapped=<_cancel_overlappedCancelling an overlapped future failed_BaseWaitHandleFutureSubclass of Future which represents a wait handle.wait_handle_wait_handle_registeredhandle=waitingwait_handle=_unregister_wait_cb_unregister_waitUnregisterWaitFailed to unregister the wait handle_WaitCancelFutureSubclass of Future which represents a wait for the cancellation of a + _WaitHandleFuture using an event. + _WaitCancelFuture must not be cancelled_WaitHandleFuture_unregister_proactorCreateEvent_event_event_fut_unregisterUnregisterWaitEx_wait_cancelPipeServerClass representing a pipe server. + + This is much like a bound, listening socket. + _free_instances_accept_pipe_future_server_pipe_handle_get_unconnected_pipePipeHandle_WindowsSelectorEventLoopWindows version of selector event loop.Windows version of proactor event loop using IOCP.create_pipe_connectionconnect_pipestart_serving_pipeloop_accept_pipeaccept_pipePipe accept failedAccept pipe failed on pipe %r_WindowsSubprocessTransportProactor implementation using IOCP.concurrencyCreateIoCompletionPortINVALID_HANDLE_VALUE_iocp_unregistered_stopped_servingIocpProactor is closedoverlapped#=%sresult#=%s<%s %s>_register_with_iocpOverlappedWSARecvfinish_recvgetresultWSARecvIntoReadFileIntoWSARecvFromWSASendTofinish_sendWSASend_get_accept_socketAcceptExfinish_accept@PSO_UPDATE_ACCEPT_CONTEXTaccept_coroWSAConnectBindLocalWSAEINVALConnectExfinish_connectSO_UPDATE_CONNECT_CONTEXToffset_lowoffset_highTransmitFilefinish_sendfilefinish_accept_pipeConnectPipewait_for_handleWait for a handle. + + Return a Future object. The result of the future is True if the wait + completed, or False if the wait did not complete (on timeout). + _wait_for_handledone_callback_is_cancelRegisterWaitWithQueuefinish_wait_for_handleUnregister an overlapped object. + + Call this method when its future has been cancelled. The event can + already be signalled (pending in the proactor event queue). It is also + safe if the event is never signalled (because it was cancelled). + negative timeouttimeout too bigGetQueuedCompletionStatustransferredGetQueuedCompletionStatus() returned an unexpected event'GetQueuedCompletionStatus() returned an ''unexpected event'err=%s transferred=%s key=%#x address=%#xCancelling a future failedmsg_updatenext_msg%r is running after closing for %.1f seconds# Initial delay in seconds for connect_pipe() before retrying to connect# Maximum delay in seconds for connect_pipe() before retrying to connect# Keep a reference to the Overlapped object to keep it alive until the# wait is unregistered# Should we call UnregisterWaitEx() if the wait completes# or is cancelled?# non-blocking wait: use a timeout of 0 millisecond# The wait was unregistered: it's not safe to destroy the Overlapped# object# ERROR_IO_PENDING means that the unregister is pending# If the wait was cancelled, the wait may never be signalled, so# it's required to unregister it. Otherwise, IocpProactor.close() will# wait forever for an event which will never come.# If the IocpProactor already received the event, it's safe to call# _unregister() because we kept a reference to the Overlapped object# which is used as a unique key.# ERROR_IO_PENDING is not an error, the wait was unregistered# initialize the pipe attribute before calling _server_pipe_handle()# because this function can raise an exception and the destructor calls# the close() method# Create new instance and return previous one. This ensures# that (until the server is closed) there is always at least# one pipe handle for address. Therefore if a client attempt# to connect it will not fail with FileNotFoundError.# Return a wrapper for a new pipe handle.# Close all instances which have not been connected to by a client.# self_reading_future was just cancelled so if it hasn't been# finished yet, it never will be (it's possible that it has# already finished and its callback is waiting in the queue,# where it could still happen if the event loop is restarted).# Unregister it otherwise IocpProactor.close will wait for it# forever# A client connected before the server was closed:# drop the client (close the pipe) and exit# Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.# Coroutine closing the accept socket if the future is cancelled# WSAConnect will complete immediately for UDP sockets so we don't# need to register any IOCP operation# The socket needs to be locally bound before we call ConnectEx().# Probably already locally bound; check using getsockname().# Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.# ConnectNamePipe() failed with ERROR_PIPE_CONNECTED which means# that the pipe is connected. There is no need to wait for the# completion of the connection.# Unfortunately there is no way to do an overlapped connect to# a pipe. Call CreateFile() in a loop until it doesn't fail with# ERROR_PIPE_BUSY.# ConnectPipe() failed with ERROR_PIPE_BUSY: retry later# add_done_callback() cannot be used because the wait may only complete# in IocpProactor.close(), while the event loop is not running.# RegisterWaitForSingleObject() has a resolution of 1 millisecond,# round away from zero to wait *at least* timeout seconds.# We only create ov so we can use ov.address as a key for the cache.# Note that this second wait means that we should only use# this with handles types where a successful wait has no# effect. So events or processes are all right, but locks# or semaphores are not. Also note if the handle is# signalled and then quickly reset, then we may return# False even though we have not timed out.# To get notifications of finished ops on this objects sent to the# completion port, were must register the handle.# XXX We could also use SetFileCompletionNotificationModes()# to avoid sending notifications to completion port of ops# that succeed immediately.# Return a future which will be set with the result of the# operation when it completes. The future's value is actually# the value returned by callback().# The operation has completed, so no need to postpone the# work. We cannot take this short cut if we need the# NumberOfBytes, CompletionKey values returned by# PostQueuedCompletionStatus().# Even if GetOverlappedResult() was called, we have to wait for the# notification of the completion in GetQueuedCompletionStatus().# Register the overlapped operation to keep a reference to the# OVERLAPPED object, otherwise the memory is freed and Windows may# read uninitialized memory.# Register the overlapped operation for later. Note that# we only store obj to prevent it from being garbage# collected too early.# GetQueuedCompletionStatus() has a resolution of 1 millisecond,# key is either zero, or it is used to return a pipe# handle which should be closed to avoid a leak.# Don't call the callback if _register() already read the result or# if the overlapped has been cancelled# Remove unregistered futures# obj is a socket or pipe handle. It will be closed in# BaseProactorEventLoop._stop_serving() which will make any# pending operations fail quickly.# already closed# Cancel remaining registered operations.# Nothing to do with cancelled futures# _WaitCancelFuture must not be cancelled# Wait until all cancelled overlapped complete: don't exit with running# overlapped to prevent a crash. Display progress every second if the# loop is still running.# handle a few events, or timeoutb'Selector and proactor event loops for Windows.'u'Selector and proactor event loops for Windows.'b'ProactorEventLoop'u'ProactorEventLoop'b'IocpProactor'u'IocpProactor'b'WindowsSelectorEventLoopPolicy'u'WindowsSelectorEventLoopPolicy'b'WindowsProactorEventLoopPolicy'u'WindowsProactorEventLoopPolicy'b'Subclass of Future which represents an overlapped operation. + + Cancelling it will immediately cancel the overlapped operation. + 'u'Subclass of Future which represents an overlapped operation. + + Cancelling it will immediately cancel the overlapped operation. + 'b'overlapped=<'u'overlapped=<'b'Cancelling an overlapped future failed'u'Cancelling an overlapped future failed'b'Subclass of Future which represents a wait handle.'u'Subclass of Future which represents a wait handle.'b'handle='u'handle='b'signaled'u'signaled'b'waiting'u'waiting'b'wait_handle='u'wait_handle='b'Failed to unregister the wait handle'u'Failed to unregister the wait handle'b'Subclass of Future which represents a wait for the cancellation of a + _WaitHandleFuture using an event. + 'u'Subclass of Future which represents a wait for the cancellation of a + _WaitHandleFuture using an event. + 'b'_WaitCancelFuture must not be cancelled'u'_WaitCancelFuture must not be cancelled'b'Class representing a pipe server. + + This is much like a bound, listening socket. + 'u'Class representing a pipe server. + + This is much like a bound, listening socket. + 'b'Windows version of selector event loop.'u'Windows version of selector event loop.'b'Windows version of proactor event loop using IOCP.'u'Windows version of proactor event loop using IOCP.'b'addr'u'addr'b'Pipe accept failed'u'Pipe accept failed'b'Accept pipe failed on pipe %r'u'Accept pipe failed on pipe %r'b'Proactor implementation using IOCP.'u'Proactor implementation using IOCP.'b'IocpProactor is closed'u'IocpProactor is closed'b'overlapped#=%s'u'overlapped#=%s'b'result#=%s'u'result#=%s'b'<%s %s>'u'<%s %s>'b'@P'u'@P'b'Wait for a handle. + + Return a Future object. The result of the future is True if the wait + completed, or False if the wait did not complete (on timeout). + 'u'Wait for a handle. + + Return a Future object. The result of the future is True if the wait + completed, or False if the wait did not complete (on timeout). + 'b'Unregister an overlapped object. + + Call this method when its future has been cancelled. The event can + already be signalled (pending in the proactor event queue). It is also + safe if the event is never signalled (because it was cancelled). + 'u'Unregister an overlapped object. + + Call this method when its future has been cancelled. The event can + already be signalled (pending in the proactor event queue). It is also + safe if the event is never signalled (because it was cancelled). + 'b'negative timeout'u'negative timeout'b'timeout too big'u'timeout too big'b'GetQueuedCompletionStatus() returned an unexpected event'u'GetQueuedCompletionStatus() returned an unexpected event'b'err=%s transferred=%s key=%#x address=%#x'u'err=%s transferred=%s key=%#x address=%#x'b'Cancelling a future failed'u'Cancelling a future failed'b'%r is running after closing for %.1f seconds'u'%r is running after closing for %.1f seconds'u'asyncio.windows_events'u'windows_events'Various Windows specific bits and pieces.win32 onlyLike os.pipe() but with overlapped support and using handles not fds.\\.\pipe\python-pipe-{:d}-{:d}-flags_and_attribsWrapper for an overlapped pipe handle which is vaguely file-object like. + + The IOCP event loop can use these instead of socket objects. + I/O operation on closed pipeunclosed Replacement for subprocess.Popen using overlapped pipe handles. + + The stdin, stdout, stderr are None or instances of PipeHandle. + stdin_rfdstdout_wfdstderr_wfdstdin_whstdout_rhstderr_rhstdin_rhstdout_whstderr_wh# Constants/globals# Replacement for os.pipe() using handles instead of fds# Wrapper for a pipe handle# Replacement for subprocess.Popen using overlapped pipe handlesb'Various Windows specific bits and pieces.'u'Various Windows specific bits and pieces.'b'win32 only'u'win32 only'b'PipeHandle'u'PipeHandle'b'Like os.pipe() but with overlapped support and using handles not fds.'u'Like os.pipe() but with overlapped support and using handles not fds.'b'\\.\pipe\python-pipe-{:d}-{:d}-'u'\\.\pipe\python-pipe-{:d}-{:d}-'b'Wrapper for an overlapped pipe handle which is vaguely file-object like. + + The IOCP event loop can use these instead of socket objects. + 'u'Wrapper for an overlapped pipe handle which is vaguely file-object like. + + The IOCP event loop can use these instead of socket objects. + 'b'I/O operation on closed pipe'u'I/O operation on closed pipe'b'unclosed 'u'unclosed 'b'Replacement for subprocess.Popen using overlapped pipe handles. + + The stdin, stdout, stderr are None or instances of PipeHandle. + 'u'Replacement for subprocess.Popen using overlapped pipe handles. + + The stdin, stdout, stderr are None or instances of PipeHandle. + 'b'bufsize'u'bufsize'u'asyncio.windows_utils'u'windows_utils'BYTEWCHARUINTDOUBLEVARIANT_BOOLULONGUSHORTSHORT_LARGE_INTEGERLARGE_INTEGER_ULARGE_INTEGERULARGE_INTEGERLPCOLESTRLPOLESTROLESTRLPCWSTRLPWSTRLPCSTRLPSTRLPCVOIDLPVOIDWPARAMLPARAMATOMLANGIDCOLORREFLGRPIDLCTYPELCIDHANDLEHACCELHBITMAPHBRUSHHCOLORSPACEHDCHDESKHDWPHENHMETAFILEHFONTHGDIOBJHGLOBALHHOOKHICONHINSTANCEHKEYHKLHLOCALHMENUHMETAFILEHMODULEHMONITORHPALETTEHPENHRGNHRSRCHSTRHTASKHWINSTAHWNDSC_HANDLESERVICE_STATUS_HANDLERECTtagRECT_RECTLRECTL_SMALL_RECTLeftTopRightBottomSMALL_RECT_COORDPOINTtagPOINT_POINTLPOINTLSIZEcxtagSIZESIZELRGBredgreenblueFILETIMEdwLowDateTimedwHighDateTime_FILETIMEMSGhWndwParamlParamtagMSG260MAX_PATHWIN32_FIND_DATAAdwFileAttributesftCreationTimeftLastAccessTimeftLastWriteTimenFileSizeHighnFileSizeLowdwReserved0dwReserved1cFileNamecAlternateFileNameWIN32_FIND_DATAWLPBOOLPBOOLPBOOLEANLPBYTEPBYTEPCHARLPCOLORREFLPDWORDPDWORDLPFILETIMEPFILETIMEPFLOATLPHANDLEPHANDLEPHKEYLPHKLLPINTPINTPLARGE_INTEGERPLCIDLPLONGPLONGLPMSGPMSGLPPOINTPPOINTPPOINTLLPRECTPRECTLPRECTLPRECTLLPSC_HANDLEPSHORTLPSIZEPSIZELPSIZELPSIZELPSMALL_RECTLPUINTPUINTPULARGE_INTEGERPULONGPUSHORTPWCHARLPWIN32_FIND_DATAAPWIN32_FIND_DATAALPWIN32_FIND_DATAWPWIN32_FIND_DATAWLPWORDPWORD# The most useful windows datatypes#UCHAR = ctypes.c_uchar# in the windows header files, these are structures.# WPARAM is defined as UINT_PTR (unsigned type)# LPARAM is defined as LONG_PTR (signed type)# HANDLE types# in the header files: void *# Some important structure definitions# Pointer typesb'Left'u'Left'b'Top'u'Top'b'Right'u'Right'b'Bottom'u'Bottom'b'Y'u'Y'b'cx'u'cx'b'dwLowDateTime'u'dwLowDateTime'b'dwHighDateTime'u'dwHighDateTime'b'hWnd'u'hWnd'b'wParam'u'wParam'b'lParam'u'lParam'b'dwFileAttributes'u'dwFileAttributes'b'ftCreationTime'u'ftCreationTime'b'ftLastAccessTime'u'ftLastAccessTime'b'ftLastWriteTime'u'ftLastWriteTime'b'nFileSizeHigh'u'nFileSizeHigh'b'nFileSizeLow'u'nFileSizeLow'b'dwReserved0'u'dwReserved0'b'dwReserved1'u'dwReserved1'b'cFileName'u'cFileName'b'cAlternateFileName'u'cAlternateFileName'u'ctypes.wintypes'u'wintypes' +Read and write ZIP files. + +XXX references to utf-8 need further investigation. +BadZipFileBadZipfileZIP_STOREDZIP_BZIP2ZIP_LZMAZipInfoPyZipFileLargeZipFilePath + Raised when writing a zipfile, the zipfile requires ZIP64 extensions + and those extensions are disabled. + ZIP64_LIMITZIP_FILECOUNT_LIMITZIP_MAX_COMMENTDEFAULT_VERSIONZIP64_VERSIONBZIP2_VERSIONLZMA_VERSIONMAX_EXTRACT_VERSION<4s4H2LHstructEndArchivePKstringEndArchivesizeEndCentDir_ECD_SIGNATURE_ECD_DISK_NUMBER_ECD_DISK_START_ECD_ENTRIES_THIS_DISK_ECD_ENTRIES_TOTAL_ECD_SIZE_ECD_OFFSET_ECD_COMMENT_SIZE_ECD_COMMENT_ECD_LOCATION<4s4B4HL2L5H2LstructCentralDirPKstringCentralDirsizeCentralDir_CD_SIGNATURE_CD_CREATE_VERSION_CD_CREATE_SYSTEM_CD_EXTRACT_VERSION_CD_EXTRACT_SYSTEM_CD_FLAG_BITS_CD_COMPRESS_TYPE_CD_TIME_CD_DATE_CD_CRC_CD_COMPRESSED_SIZE_CD_UNCOMPRESSED_SIZE_CD_FILENAME_LENGTH_CD_EXTRA_FIELD_LENGTH_CD_COMMENT_LENGTH_CD_DISK_NUMBER_START_CD_INTERNAL_FILE_ATTRIBUTES_CD_EXTERNAL_FILE_ATTRIBUTES_CD_LOCAL_HEADER_OFFSET<4s2B4HL2L2HstructFileHeaderPKstringFileHeadersizeFileHeader_FH_SIGNATURE_FH_EXTRACT_VERSION_FH_EXTRACT_SYSTEM_FH_GENERAL_PURPOSE_FLAG_BITS_FH_COMPRESSION_METHOD_FH_LAST_MOD_TIME_FH_LAST_MOD_DATE_FH_CRC_FH_COMPRESSED_SIZE_FH_UNCOMPRESSED_SIZE_FH_FILENAME_LENGTH_FH_EXTRA_FIELD_LENGTH<4sLQLstructEndArchive64LocatorPKstringEndArchive64LocatorsizeEndCentDir64Locator<4sQ2H2L4QstructEndArchive64PKstringEndArchive64sizeEndCentDir64_CD64_SIGNATURE_CD64_DIRECTORY_RECSIZE_CD64_CREATE_VERSION_CD64_EXTRACT_VERSION_CD64_DISK_NUMBER_CD64_DISK_NUMBER_START_CD64_NUMBER_ENTRIES_THIS_DISK_CD64_NUMBER_ENTRIES_TOTAL_CD64_DIRECTORY_SIZE_CD64_OFFSET_START_CENTDIR1346957600x08074b50_DD_SIGNATURE|"?*illegalExtract the ZipInfo object 'member' to a physical + file on the path targetpath. + invalid_path_partsCheck for errors before writing a file to the archive.Duplicate name: %rwrite() requires mode 'w', 'x', or 'a'Attempt to write ZIP archive that was already closedrequires_zip64Files countFilesizeZipfile size would require ZIP64 extensionsPut the bytes from filename into the archive under the name + arcname.Attempt to write to ZIP archive that was already closedCan't write to ZIP archive while an open writing handle existswritestrzinfo_or_arcnameWrite a file into the archive. The contents is 'data', which + may be either a 'str' or a 'bytes' instance; if it is a 'str', + it is encoded as UTF-8 first. + 'zinfo_or_arcname' is either a ZipInfo instance or + the name of the file in the archive.168930o40775Can't write to ZIP archive while an open writing handle exists.Call the "close()" method in case the user forgot.Close the file, and for mode 'w', 'x' and 'a' write the ending + records.Can't close the ZIP file while there is an open writing handle on it. Close the writing handle before closing the zip."Can't close the ZIP file while there is ""an open writing handle on it. ""Close the writing handle before closing the zip."_write_end_recordextra_datapos2centDirCountcentDirSizecentDirOffsetCentral directory offsetCentral directory sizezip64endreczip64locrecClass to create ZIP archives with Python library files and packages.writepyfilterfuncAdd all files from "pathname" to the ZIP archive. + + If pathname is a package directory, search the directory and + all package subdirectories recursively for all *.py and enter + the modules into the archive. If pathname is a plain + directory, listdir *.py and enter all modules. Else, pathname + must be a Python *.py file and the module will be put into the + archive. Added modules are always module.pyc. + This method will compile the module.py into module.pyc if + necessary. + If filterfunc(pathname) is given, it is called with every argument. + When it is False, the file or directory is skipped. + %s %r skipped by filterfuncinitnameAdding package in_get_codenameAddingfile %r skipped by filterfuncAdding files from directoryFiles added with writepy() must end with ".py"Adding fileReturn (filename, archivename) for the path. + + Given a module name path, return the correct file path and + archive name, compiling if necessary. For example, given + /python/lib/string, return (/python/lib/string.pyc, string). + Compilingfile_pyfile_pycpycache_opt0pycache_opt1pycache_opt2invalid value for 'optimize': {!r}archivename_parents + Given a path with elements separated by + posixpath.sep, generate all parents of that path. + + >>> list(_parents('b/d')) + ['b'] + >>> list(_parents('/b/d/')) + ['/b'] + >>> list(_parents('b/d/f/')) + ['b/d', 'b'] + >>> list(_parents('b')) + [] + >>> list(_parents('')) + [] + _ancestry + Given a path with elements separated by + posixpath.sep, generate all elements of that path + + >>> list(_ancestry('b/d')) + ['b/d', 'b'] + >>> list(_ancestry('/b/d/')) + ['/b/d', '/b'] + >>> list(_ancestry('b/d/f/')) + ['b/d/f', 'b/d', 'b'] + >>> list(_ancestry('b')) + ['b'] + >>> list(_ancestry('')) + [] + _dedupeDeduplicate an iterable in original order_differenceminuendsubtrahend + Return items in minuend not in subtrahend, retaining order + with O(1) lookup. + CompleteDirs + A ZipFile subclass that ensures that implied directories + are always included in the namelist. + _implied_dirsas_dirs_name_setresolve_dir + If the name represents a directory, return that name + as a directory (with the trailing slash). + dir_matchmake + Given a source (filename or zipfile), return an + appropriate CompleteDirs subclass. + FastLookup + ZipFile subclass to ensure implicit + dirs exist and are resolved rapidly. + __names__lookup + A pathlib-compatible interface for zip files. + + Consider a zip file with this structure:: + + . + ├── a.txt + └── b + ├── c.txt + └── d + └── e.txt + + >>> data = io.BytesIO() + >>> zf = ZipFile(data, 'w') + >>> zf.writestr('a.txt', 'content of a') + >>> zf.writestr('b/c.txt', 'content of c') + >>> zf.writestr('b/d/e.txt', 'content of e') + >>> zf.filename = 'abcde.zip' + + Path accepts the zipfile object itself or a filename + + >>> root = Path(zf) + + From there, several path operations are available. + + Directory iteration (including the zip file itself): + + >>> a, b = root.iterdir() + >>> a + Path('abcde.zip', 'a.txt') + >>> b + Path('abcde.zip', 'b/') + + name property: + + >>> b.name + 'b' + + join with divide operator: + + >>> c = b / 'c.txt' + >>> c + Path('abcde.zip', 'b/c.txt') + >>> c.name + 'c.txt' + + Read text: + + >>> c.read_text() + 'content of c' + + existence: + + >>> c.exists() + True + >>> (b / 'missing.txt').exists() + False + + Coercion to string: + + >>> str(c) + 'abcde.zip/b/c.txt' + {self.__class__.__name__}({self.root.filename!r}, {self.at!r})__repratread_textstrmread_bytes_is_child_nextiterdirCan't listdir a filejoinpathparent_atA simple command-line interface for zipfile module.Show listing of a zipfileExtract zipfile into target dirCreate zipfile from sourcesTest if a zipfile is validbadfileThe following enclosed file is corrupted: {!r}Done testingzip_nameaddToZipzippathnm# We may need its compression method# Pre-3.2 compatibility names# constants for Zip file compression methods# Other ZIP compression methods not supported# we recognize (but not necessarily support) all features up to that version# Below are some formats and associated data for reading/writing headers using# the struct module. The names and structures of headers/records are those used# in the PKWARE description of the ZIP file format:# http://www.pkware.com/documents/casestudies/APPNOTE.TXT# (URL valid as of January 2008)# The "end of central directory" structure, magic number, size, and indices# (section V.I in the format document)# These last two indices are not part of the structure as defined in the# spec, but they are used internally by this module as a convenience# The "central directory" structure, magic number, size, and indices# of entries in the structure (section V.F in the format document)# indexes of entries in the central directory structure# The "local file header" structure, magic number, size, and indices# (section V.A in the format document)# The "Zip64 end of central directory locator" structure, magic number, and size# The "Zip64 end of central directory" record, magic number, size, and indices# (section V.G in the format document)# Remove Extra Fields with specified IDs.# file has correct magic number# If the seek fails, the file is not large enough to contain a ZIP64# end-of-archive record, so just return the end record we were given.# Assume no 'zip64 extensible data'# Update the original endrec using data from the ZIP64 record# Determine file size# Check to see if this is ZIP file with no archive comment (the# "end of central directory" structure should be the last item in the# file if this is the case).# the signature is correct and there's no comment, unpack structure# Append a blank comment and record start offset# Try to read the "Zip64 end of central directory" structure# Either this is not a ZIP file, or it is a ZIP file with an archive# comment. Search the end of the file for the "end of central directory"# record signature. The comment is the last item in the ZIP file and may be# up to 64K long. It is assumed that the "end of central directory" magic# number does not appear in the comment.# found the magic number; attempt to unpack and interpret# Zip file is corrupted.#as claimed by the zip file# Unable to find a valid end of central directory structure# Original file name in archive# Terminate the file name at the first null byte. Null bytes in file# names are used as tricks by viruses in archives.# This is used to ensure paths in generated ZIP files always use# forward slashes as the directory separator, as required by the# ZIP format specification.# Normalized file name# year, month, day, hour, min, sec# Standard values:# Type of compression for the file# Level for the compressor# Comment for each file# ZIP extra data# System which created ZIP archive# Assume everything else is unix-y# Version which created ZIP archive# Version needed to extract archive# Must be zero# ZIP flag bits# Volume number of file header# Internal attributes# External file attributes# Other attributes are set by class ZipFile:# header_offset Byte offset to the file header# CRC CRC-32 of the uncompressed file# compress_size Size of the compressed file# file_size Size of the uncompressed file# Set these to zero because we write them after the file data# File is larger than what fits into a 4 byte integer,# fall back to the ZIP64 extension# Try to decode the extra field.# ZIP64 extension (large files and/or large archives)# Create ZipInfo instance to store file information# Unix attributes# MS-DOS directory flag# ZIP encryption uses the CRC32 one-byte primitive for scrambling some# internal keys. We noticed that a direct implementation is faster than# relying on binascii.crc32().# ZIP supports a password-based form of encryption. Even though known# plaintext attacks have been found against it, it is still useful# to be able to get data out of such a file.# Usage:# zd = _ZipDecrypter(mypwd)# plain_bytes = zd(cypher_bytes)# compresslevel is ignored for ZIP_LZMA# Provide the tell method for unseekable stream# Max size supported by decompressor.# Read from compressed files in 4k blocks.# Chunk size to read during seek# compare against the file type from extended local headers# compare against the CRC otherwise# The first 12 bytes in the cypher stream is an encryption header# used to strengthen the algorithm. The first 11 bytes are# completely random, while the 12th contains the MSB of the CRC,# or the MSB of the file time depending on the header type# and is used to check the correctness of the password.# Shortcut common case - newline found in buffer.# Return up to 512 bytes to reduce allocation overhead for tight loops.# Update the CRC using the given data.# No need to compute the CRC if we don't have a reference value# Check the CRC if we're at the end of the file# Read up to n compressed bytes with at most one read() system call,# decrypt and decompress them.# Read from file.## Handle unconsumed data.# Seek from start of file# Seek from current position# Seek from EOF# Just move the _offset index if the new position is in the _readbuffer# Position is before the current position. Reset the ZipExtFile# Flush any data from the compressor, and update header info# Write updated header info# Write CRC and file sizes after the file data# Seek backwards and write file header (which will now include# correct CRC and file sizes)# Preserve current position in file# Successfully written: Add file to our caches# Level of printing: 0 through 3# Find file info given name# List of ZipInfo instances for archive# Method of compression# Check if we were passed a file-like object# No, it's a filename# set the modified flag so central directory gets written# even if no files are added to the archive# Some file-like objects can provide tell() but not seek()# See if file is a zip file# seek to start of directory and overwrite# file is not a zip file, just append# bytes in central directory# offset of central directory# archive comment# "concat" is zero, unless zip was concatenated to another file# If Zip64 extension structures are present, account for them# self.start_dir: Position of start of central directory# UTF-8 file names extension# Historical ZIP filename encoding# Convert date/time code to (year, month, day, hour, min, sec)# update total bytes read from central directory# Read by chunks, to avoid an OverflowError or a# MemoryError with very large embedded files.# Check CRC-32# check for valid comment length# Make sure we have an info object# 'name' is already an info object# Get info object for name# Open for reading:# Skip the file header:# Zip 2.7: compressed patched data# strong encryption# UTF-8 filename# check for encrypted flag & handle password# Sizes and CRC are overwritten with correct data after processing the file# Compressed data includes an end-of-stream (EOS) marker# permissions: ?rw-------# Compressed size can be larger than uncompressed size# remove trailing dots# rejoin, removing empty parts.# build the destination pathname, replacing# interpret absolute pathname as relative, remove drive letter or# UNC path, redundant separators, "." and ".." components.# filter illegal characters on Windows# Create all upper directories if necessary.# Start of header bytes# drwxrwxr-x# ?rw-------# Uncompressed size# write ending records# write central directory# Append a ZIP64 field to the extra's# Write end-of-zip-archive record# Need to write the ZIP64 end-of-archive records# This is a package directory, add it# Add all *.py files and package subdirectories# Recursive call# This is NOT a package directory, add its files at top level# legacy mode: use whatever file is present# Use .pyc file.# Use the __pycache__/*.pyc file, but write it to the legacy pyc# file name in the archive.# Compile py into PEP 3147 pyc file.# new mode: use given optimization level# Only allow for FastPath when supplied zipfile is read-only# else: ignoreb' +Read and write ZIP files. + +XXX references to utf-8 need further investigation. +'u' +Read and write ZIP files. + +XXX references to utf-8 need further investigation. +'b'BadZipFile'u'BadZipFile'b'BadZipfile'u'BadZipfile'b'ZIP_STORED'u'ZIP_STORED'b'ZIP_DEFLATED'u'ZIP_DEFLATED'b'ZIP_BZIP2'u'ZIP_BZIP2'b'ZIP_LZMA'u'ZIP_LZMA'b'is_zipfile'u'is_zipfile'b'ZipInfo'u'ZipInfo'b'ZipFile'u'ZipFile'b'PyZipFile'u'PyZipFile'b'LargeZipFile'u'LargeZipFile'b'Path'u'Path'b' + Raised when writing a zipfile, the zipfile requires ZIP64 extensions + and those extensions are disabled. + 'u' + Raised when writing a zipfile, the zipfile requires ZIP64 extensions + and those extensions are disabled. + 'b'<4s4H2LH'b'PK'b'<4s4B4HL2L5H2L'u'<4s4B4HL2L5H2L'b'PK'b'<4s2B4HL2L2H'u'<4s2B4HL2L2H'b'PK'b'<4sLQL'u'<4sLQL'b'PK'b'<4sQ2H2L4Q'u'<4sQ2H2L4Q'b'PK'b'|"?*'u':<>|"?*'b'Extract the ZipInfo object 'member' to a physical + file on the path targetpath. + 'u'Extract the ZipInfo object 'member' to a physical + file on the path targetpath. + 'b'Check for errors before writing a file to the archive.'u'Check for errors before writing a file to the archive.'b'Duplicate name: %r'u'Duplicate name: %r'b'write() requires mode 'w', 'x', or 'a''u'write() requires mode 'w', 'x', or 'a''b'Attempt to write ZIP archive that was already closed'u'Attempt to write ZIP archive that was already closed'b'Files count'u'Files count'b'Filesize'u'Filesize'b'Zipfile size'u'Zipfile size'b' would require ZIP64 extensions'u' would require ZIP64 extensions'b'Put the bytes from filename into the archive under the name + arcname.'u'Put the bytes from filename into the archive under the name + arcname.'b'Attempt to write to ZIP archive that was already closed'u'Attempt to write to ZIP archive that was already closed'b'Can't write to ZIP archive while an open writing handle exists'u'Can't write to ZIP archive while an open writing handle exists'b'Write a file into the archive. The contents is 'data', which + may be either a 'str' or a 'bytes' instance; if it is a 'str', + it is encoded as UTF-8 first. + 'zinfo_or_arcname' is either a ZipInfo instance or + the name of the file in the archive.'u'Write a file into the archive. The contents is 'data', which + may be either a 'str' or a 'bytes' instance; if it is a 'str', + it is encoded as UTF-8 first. + 'zinfo_or_arcname' is either a ZipInfo instance or + the name of the file in the archive.'b'Can't write to ZIP archive while an open writing handle exists.'u'Can't write to ZIP archive while an open writing handle exists.'b'Call the "close()" method in case the user forgot.'u'Call the "close()" method in case the user forgot.'b'Close the file, and for mode 'w', 'x' and 'a' write the ending + records.'u'Close the file, and for mode 'w', 'x' and 'a' write the ending + records.'b'Can't close the ZIP file while there is an open writing handle on it. Close the writing handle before closing the zip.'u'Can't close the ZIP file while there is an open writing handle on it. Close the writing handle before closing the zip.'b'Central directory offset'u'Central directory offset'b'Central directory size'u'Central directory size'b'Class to create ZIP archives with Python library files and packages.'u'Class to create ZIP archives with Python library files and packages.'b'Add all files from "pathname" to the ZIP archive. + + If pathname is a package directory, search the directory and + all package subdirectories recursively for all *.py and enter + the modules into the archive. If pathname is a plain + directory, listdir *.py and enter all modules. Else, pathname + must be a Python *.py file and the module will be put into the + archive. Added modules are always module.pyc. + This method will compile the module.py into module.pyc if + necessary. + If filterfunc(pathname) is given, it is called with every argument. + When it is False, the file or directory is skipped. + 'u'Add all files from "pathname" to the ZIP archive. + + If pathname is a package directory, search the directory and + all package subdirectories recursively for all *.py and enter + the modules into the archive. If pathname is a plain + directory, listdir *.py and enter all modules. Else, pathname + must be a Python *.py file and the module will be put into the + archive. Added modules are always module.pyc. + This method will compile the module.py into module.pyc if + necessary. + If filterfunc(pathname) is given, it is called with every argument. + When it is False, the file or directory is skipped. + 'b'%s %r skipped by filterfunc'u'%s %r skipped by filterfunc'b'Adding package in'u'Adding package in'b'Adding'u'Adding'b'file %r skipped by filterfunc'u'file %r skipped by filterfunc'b'Adding files from directory'u'Adding files from directory'b'Files added with writepy() must end with ".py"'u'Files added with writepy() must end with ".py"'b'Adding file'u'Adding file'b'Return (filename, archivename) for the path. + + Given a module name path, return the correct file path and + archive name, compiling if necessary. For example, given + /python/lib/string, return (/python/lib/string.pyc, string). + 'u'Return (filename, archivename) for the path. + + Given a module name path, return the correct file path and + archive name, compiling if necessary. For example, given + /python/lib/string, return (/python/lib/string.pyc, string). + 'b'Compiling'u'Compiling'b'invalid value for 'optimize': {!r}'u'invalid value for 'optimize': {!r}'b' + Given a path with elements separated by + posixpath.sep, generate all parents of that path. + + >>> list(_parents('b/d')) + ['b'] + >>> list(_parents('/b/d/')) + ['/b'] + >>> list(_parents('b/d/f/')) + ['b/d', 'b'] + >>> list(_parents('b')) + [] + >>> list(_parents('')) + [] + 'u' + Given a path with elements separated by + posixpath.sep, generate all parents of that path. + + >>> list(_parents('b/d')) + ['b'] + >>> list(_parents('/b/d/')) + ['/b'] + >>> list(_parents('b/d/f/')) + ['b/d', 'b'] + >>> list(_parents('b')) + [] + >>> list(_parents('')) + [] + 'b' + Given a path with elements separated by + posixpath.sep, generate all elements of that path + + >>> list(_ancestry('b/d')) + ['b/d', 'b'] + >>> list(_ancestry('/b/d/')) + ['/b/d', '/b'] + >>> list(_ancestry('b/d/f/')) + ['b/d/f', 'b/d', 'b'] + >>> list(_ancestry('b')) + ['b'] + >>> list(_ancestry('')) + [] + 'u' + Given a path with elements separated by + posixpath.sep, generate all elements of that path + + >>> list(_ancestry('b/d')) + ['b/d', 'b'] + >>> list(_ancestry('/b/d/')) + ['/b/d', '/b'] + >>> list(_ancestry('b/d/f/')) + ['b/d/f', 'b/d', 'b'] + >>> list(_ancestry('b')) + ['b'] + >>> list(_ancestry('')) + [] + 'b'Deduplicate an iterable in original order'u'Deduplicate an iterable in original order'b' + Return items in minuend not in subtrahend, retaining order + with O(1) lookup. + 'u' + Return items in minuend not in subtrahend, retaining order + with O(1) lookup. + 'b' + A ZipFile subclass that ensures that implied directories + are always included in the namelist. + 'u' + A ZipFile subclass that ensures that implied directories + are always included in the namelist. + 'b' + If the name represents a directory, return that name + as a directory (with the trailing slash). + 'u' + If the name represents a directory, return that name + as a directory (with the trailing slash). + 'b' + Given a source (filename or zipfile), return an + appropriate CompleteDirs subclass. + 'u' + Given a source (filename or zipfile), return an + appropriate CompleteDirs subclass. + 'b' + ZipFile subclass to ensure implicit + dirs exist and are resolved rapidly. + 'u' + ZipFile subclass to ensure implicit + dirs exist and are resolved rapidly. + 'u' + A pathlib-compatible interface for zip files. + + Consider a zip file with this structure:: + + . + ├── a.txt + └── b + ├── c.txt + └── d + └── e.txt + + >>> data = io.BytesIO() + >>> zf = ZipFile(data, 'w') + >>> zf.writestr('a.txt', 'content of a') + >>> zf.writestr('b/c.txt', 'content of c') + >>> zf.writestr('b/d/e.txt', 'content of e') + >>> zf.filename = 'abcde.zip' + + Path accepts the zipfile object itself or a filename + + >>> root = Path(zf) + + From there, several path operations are available. + + Directory iteration (including the zip file itself): + + >>> a, b = root.iterdir() + >>> a + Path('abcde.zip', 'a.txt') + >>> b + Path('abcde.zip', 'b/') + + name property: + + >>> b.name + 'b' + + join with divide operator: + + >>> c = b / 'c.txt' + >>> c + Path('abcde.zip', 'b/c.txt') + >>> c.name + 'c.txt' + + Read text: + + >>> c.read_text() + 'content of c' + + existence: + + >>> c.exists() + True + >>> (b / 'missing.txt').exists() + False + + Coercion to string: + + >>> str(c) + 'abcde.zip/b/c.txt' + 'b'{self.__class__.__name__}({self.root.filename!r}, {self.at!r})'u'{self.__class__.__name__}({self.root.filename!r}, {self.at!r})'b'Can't listdir a file'u'Can't listdir a file'b'A simple command-line interface for zipfile module.'u'A simple command-line interface for zipfile module.'b''u''b'Show listing of a zipfile'u'Show listing of a zipfile'b'Extract zipfile into target dir'u'Extract zipfile into target dir'b'Create zipfile from sources'u'Create zipfile from sources'b'Test if a zipfile is valid'u'Test if a zipfile is valid'b'The following enclosed file is corrupted: {!r}'u'The following enclosed file is corrupted: {!r}'b'Done testing'u'Done testing'u'zipfile'zipimport provides support for importing Python modules from Zip archives. + +This module exports three objects: +- zipimporter: a class; its constructor takes a path to a Zip archive. +- ZipImportError: exception raised by zipimporter objects. It's a + subclass of ImportError, so it can be caught as ImportError, too. +- _zip_directory_cache: a dict, mapping archive paths to zip directory + info dicts, as used in zipimporter._files. + +It is usually not needed to use the zipimport module explicitly; it is +used by the builtin import mechanism for sys.path items that are paths +to Zip archives. +ZipImportErroralt_path_sep_module_typeEND_CENTRAL_DIR_SIZESTRING_END_ARCHIVEMAX_COMMENT_LENzipimporter(archivepath) -> zipimporter object + + Create a new zipimporter instance. 'archivepath' must be a path to + a zipfile, or to a specific path inside a zipfile. For example, it can be + '/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a + valid directory inside the archive. + + 'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip + archive. + + The 'archive' attribute of zipimporter objects contains the name of the + zipfile targeted. + archive path is emptynot a Zip file_read_directory_filesfind_loader(fullname, path=None) -> self, str or None. + + Search for a module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the zipimporter + instance itself if the module was found, a string containing the + full path name if it's possibly a portion of a namespace package, + or None otherwise. The optional 'path' argument is ignored -- it's + there for compatibility with the importer protocol. + _get_module_info_get_module_pathmodpath_is_dirfind_module(fullname, path=None) -> self or None. + + Search for a module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the zipimporter + instance itself if the module was found, or None if it wasn't. + The optional 'path' argument is ignored -- it's there for compatibility + with the importer protocol. + get_code(fullname) -> code object. + + Return the code object for the specified module. Raise ZipImportError + if the module couldn't be found. + _get_module_codeget_data(pathname) -> string with file data. + + Return the data associated with 'pathname'. Raise OSError if + the file wasn't found. + toc_entry_get_dataget_filename(fullname) -> filename string. + + Return the filename for the specified module. + get_source(fullname) -> source string. + + Return the source code for the specified module. Raise ZipImportError + if the module couldn't be found, return None if the archive does + contain the module, but has no source for it. + can't find module is_package(fullname) -> bool. + + Return True if the module specified by fullname is a package. + Raise ZipImportError if the module couldn't be found. + load_module(fullname) -> module. + + Load the module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the imported + module, or raises ZipImportError if it wasn't found. + Loaded module not found in sys.modulesimport {} # loaded from Zip {}Return the ResourceReader for a package in a zip file. + + If 'fullname' is a package within the zip file, return the + 'ResourceReader' object for the package. Otherwise return None. + _ZipImportResourceReaderimportlib.abc__init__.pyc_zip_searchorderisbytecodecan't open Zip file: header_positioncan't read Zip file: max_comment_startnot a Zip file: corrupt Zip file: header_sizebad central directory size: bad central directory offset: arc_offsetbad central directory size or offset: EOF read where not expecteddata_sizename_sizeextra_sizecomment_sizefile_offsetbad local header offset: cp437_tablezipimport: found {} names in {!r} +  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f''\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'' !"#$%&\'()*+,-./''0123456789:;<=>?''@ABCDEFGHIJKLMNO''PQRSTUVWXYZ[\\]^_''`abcdefghijklmno''pqrstuvwxyz{|}~\x7f''\xc7\xfc\xe9\xe2\xe4\xe0\xe5\xe7''\xea\xeb\xe8\xef\xee\xec\xc4\xc5''\xc9\xe6\xc6\xf4\xf6\xf2\xfb\xf9''\xff\xd6\xdc\xa2\xa3\xa5\u20a7\u0192''\xe1\xed\xf3\xfa\xf1\xd1\xaa\xba''\xbf\u2310\xac\xbd\xbc\xa1\xab\xbb''\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556''\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510''\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f''\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567''\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b''\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580''\u03b1\xdf\u0393\u03c0\u03a3\u03c3\xb5\u03c4''\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229''\u2261\xb1\u2265\u2264\u2320\u2321\xf7\u2248''\xb0\u2219\xb7\u221a\u207f\xb2\u25a0\xa0'_importing_zlib_get_decompress_funczipimport: zlib UNAVAILABLEcan't decompress data; zlib not availablezipimport: zlib availabledatapathnegative data sizebad local file header: raw_datazipimport: can't read data_eq_mtime_unmarshal_code_get_pyc_source_get_mtime_and_size_of_sourcecompiled module is not a code object_normalize_line_endings_compile_source_parse_dostimeuncompressed_sizetrying {}{}{}Private class used to support ZipImport.get_resource_reader(). + + This class is allowed to reference all the innards and private parts of + the zipimporter. + fullname_as_pathpathlibfullname_pathrelative_torelative_pathpackage_pathsubdirs_seenrelative#from importlib import _bootstrap_external#from importlib import _bootstrap # for _verbose_message# for _verbose_message# for check_hash_based_pycs# for open# for loads# for modules# for mktime# _read_directory() cache# Split the "subdirectory" from the Zip archive path, lookup a matching# entry in sys.path_importer_cache, fetch the file directory from there# if found, or else read it from the archive.# On Windows a ValueError is raised for too long paths.# Back up one path element.# it exists# stat.S_ISREG# it's a not file# a prefix directory following the ZIP file path.# Check whether we can satisfy the import of the module named by# 'fullname', or whether it could be a portion of a namespace# package. Return self if we can load it, a string containing the# full path if it's a possible namespace portion, None if we# can't load it.# This is a module or package.# Not a module or regular package. See if this is a directory, and# therefore possibly a portion of a namespace package.# We're only interested in the last path component of fullname# earlier components are recorded in self.prefix.# This is possibly a portion of a namespace# package. Return the string representing its path,# without a trailing separator.# 'fullname'. Return self if we can, None if we can't.# Return a string matching __file__ for the named module# Deciding the filename requires working out where the code# would come from if the module was actually loaded# we have the module, but no source# Return a bool signifying whether the module is a package or not.# Load and return the module named by 'fullname'.# add __path__ to the module *before* the code gets# executed# _zip_searchorder defines how we search for a module in the Zip# archive: we first search for a package __init__, then for# non-package .pyc, and .py entries. The .pyc entries# are swapped by initzipimport() if we run in optimized mode. Also,# '/' is replaced by path_sep there.# Given a module name, return the potential file path in the# archive (without extension).# Does this path represent a directory?# See if this is a "directory". If so, it's eligible to be part# of a namespace package. We test by seeing if the name, with an# appended path separator, exists.# If dirpath is present in self._files, we have a directory.# Return some information about a module.# implementation# _read_directory(archive) -> files dict (new reference)# Given a path to a Zip archive, build a dict, mapping file names# (local to the archive, using SEP as a separator) to toc entries.# A toc_entry is a tuple:# (__file__, # value to use for __file__, available for all files,# # encoded to the filesystem encoding# compress, # compression kind; 0 for uncompressed# data_size, # size of compressed data on disk# file_size, # size of decompressed data# file_offset, # offset of file header from start of archive# time, # mod time of file (in dos format)# date, # mod data of file (in dos format)# crc, # crc checksum of the data# )# Directories can be recognized by the trailing path_sep in the name,# data_size and file_offset are 0.# Bad: End of Central Dir signature# Check if there's a comment.# Start of Central Directory# Start of file header# Bad: Central Dir File Header# On Windows, calling fseek to skip over the fields we don't use is# slower than reading the data because fseek flushes stdio's# internal buffers. See issue #8745.# During bootstrap, we may need to load the encodings# package from a ZIP file. But the cp437 encoding is implemented# in Python in the encodings package.# Break out of this dependency by using the translation table for# the cp437 encoding.# ASCII part, 8 rows x 16 chars# non-ASCII part, 16 rows x 8 chars# Return the zlib.decompress function object, or NULL if zlib couldn't# be imported. The function is cached when found, so subsequent calls# don't import zlib again.# Someone has a zlib.py[co] in their Zip file# let's avoid a stack overflow.# Given a path to a Zip file and a toc_entry, return the (uncompressed) data.# Check to make sure the local file header is correct# Bad: Local File Header# Start of file data# data is not compressed# Decompress with zlib# Lenient date/time comparison function. The precision of the mtime# in the archive is lower than the mtime stored in a .pyc: we# must allow a difference of at most one second.# dostime only stores even seconds, so be lenient# Given the contents of a .py[co] file, unmarshal the data# and return the code object. Return None if it the magic word doesn't# match, or if the recorded .py[co] metadata does not match the source,# (we do this instead of raising an exception as we fall back# to .py if available and we don't want to mask other errors).# We don't use _bootstrap_external._validate_timestamp_pyc# to allow for a more lenient timestamp check.# Replace any occurrences of '\r\n?' in the input string with '\n'.# This converts DOS and Mac line endings to Unix line endings.# Given a string buffer containing Python source code, compile it# and return a code object.# Convert the date/time values found in the Zip archive to a value# that's compatible with the time stamp stored in .pyc files.# bits 9..15: year# bits 5..8: month# bits 0..4: day# bits 11..15: hours# bits 8..10: minutes# bits 0..7: seconds / 2# Given a path to a .pyc file in the archive, return the# modification time of the matching .py file and its size,# or (0, 0) if no source is available.# strip 'c' or 'o' from *.py[co]# fetch the time stamp of the .py file for comparison# with an embedded pyc time stamp# contents of the matching .py file, or None if no source# is available.# Get the code object associated with the module specified by# 'fullname'.# bad magic number or non-matching mtime# in byte code, try next# All resources are in the zip file, so there is no path to the file.# Raising FileNotFoundError tells the higher level API to extract the# binary data and create a temporary file.# Maybe we could do better, but if we can get the data, it's a# resource. Otherwise it isn't.# This is a bit convoluted, because fullname will be a module path,# but _files is a list of file names relative to the top of the# archive's namespace. We want to compare file paths to find all the# names of things inside the module represented by fullname. So we# turn the module path of fullname into a file path relative to the# top of the archive, and then we iterate through _files looking for# names inside that "directory".# Don't forget that fullname names a package, so its path will include# __init__.py, which we want to ignore.# If the path of the file (which is relative to the top of the zip# namespace), relative to the package given when the resource# reader was created, has a parent, then it's a name in a# subdirectory and thus we skip it.b'zipimport provides support for importing Python modules from Zip archives. + +This module exports three objects: +- zipimporter: a class; its constructor takes a path to a Zip archive. +- ZipImportError: exception raised by zipimporter objects. It's a + subclass of ImportError, so it can be caught as ImportError, too. +- _zip_directory_cache: a dict, mapping archive paths to zip directory + info dicts, as used in zipimporter._files. + +It is usually not needed to use the zipimport module explicitly; it is +used by the builtin import mechanism for sys.path items that are paths +to Zip archives. +'u'zipimport provides support for importing Python modules from Zip archives. + +This module exports three objects: +- zipimporter: a class; its constructor takes a path to a Zip archive. +- ZipImportError: exception raised by zipimporter objects. It's a + subclass of ImportError, so it can be caught as ImportError, too. +- _zip_directory_cache: a dict, mapping archive paths to zip directory + info dicts, as used in zipimporter._files. + +It is usually not needed to use the zipimport module explicitly; it is +used by the builtin import mechanism for sys.path items that are paths +to Zip archives. +'b'ZipImportError'u'ZipImportError'b'zipimporter'u'zipimporter'b'zipimporter(archivepath) -> zipimporter object + + Create a new zipimporter instance. 'archivepath' must be a path to + a zipfile, or to a specific path inside a zipfile. For example, it can be + '/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a + valid directory inside the archive. + + 'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip + archive. + + The 'archive' attribute of zipimporter objects contains the name of the + zipfile targeted. + 'b'archive path is empty'u'archive path is empty'b'not a Zip file'u'not a Zip file'b'find_loader(fullname, path=None) -> self, str or None. + + Search for a module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the zipimporter + instance itself if the module was found, a string containing the + full path name if it's possibly a portion of a namespace package, + or None otherwise. The optional 'path' argument is ignored -- it's + there for compatibility with the importer protocol. + 'u'find_loader(fullname, path=None) -> self, str or None. + + Search for a module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the zipimporter + instance itself if the module was found, a string containing the + full path name if it's possibly a portion of a namespace package, + or None otherwise. The optional 'path' argument is ignored -- it's + there for compatibility with the importer protocol. + 'b'find_module(fullname, path=None) -> self or None. + + Search for a module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the zipimporter + instance itself if the module was found, or None if it wasn't. + The optional 'path' argument is ignored -- it's there for compatibility + with the importer protocol. + 'u'find_module(fullname, path=None) -> self or None. + + Search for a module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the zipimporter + instance itself if the module was found, or None if it wasn't. + The optional 'path' argument is ignored -- it's there for compatibility + with the importer protocol. + 'b'get_code(fullname) -> code object. + + Return the code object for the specified module. Raise ZipImportError + if the module couldn't be found. + 'u'get_code(fullname) -> code object. + + Return the code object for the specified module. Raise ZipImportError + if the module couldn't be found. + 'b'get_data(pathname) -> string with file data. + + Return the data associated with 'pathname'. Raise OSError if + the file wasn't found. + 'u'get_data(pathname) -> string with file data. + + Return the data associated with 'pathname'. Raise OSError if + the file wasn't found. + 'b'get_filename(fullname) -> filename string. + + Return the filename for the specified module. + 'u'get_filename(fullname) -> filename string. + + Return the filename for the specified module. + 'b'get_source(fullname) -> source string. + + Return the source code for the specified module. Raise ZipImportError + if the module couldn't be found, return None if the archive does + contain the module, but has no source for it. + 'u'get_source(fullname) -> source string. + + Return the source code for the specified module. Raise ZipImportError + if the module couldn't be found, return None if the archive does + contain the module, but has no source for it. + 'b'can't find module 'u'can't find module 'b'is_package(fullname) -> bool. + + Return True if the module specified by fullname is a package. + Raise ZipImportError if the module couldn't be found. + 'u'is_package(fullname) -> bool. + + Return True if the module specified by fullname is a package. + Raise ZipImportError if the module couldn't be found. + 'b'load_module(fullname) -> module. + + Load the module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the imported + module, or raises ZipImportError if it wasn't found. + 'u'load_module(fullname) -> module. + + Load the module specified by 'fullname'. 'fullname' must be the + fully qualified (dotted) module name. It returns the imported + module, or raises ZipImportError if it wasn't found. + 'b'Loaded module 'u'Loaded module 'b' not found in sys.modules'u' not found in sys.modules'b'import {} # loaded from Zip {}'u'import {} # loaded from Zip {}'b'Return the ResourceReader for a package in a zip file. + + If 'fullname' is a package within the zip file, return the + 'ResourceReader' object for the package. Otherwise return None. + 'u'Return the ResourceReader for a package in a zip file. + + If 'fullname' is a package within the zip file, return the + 'ResourceReader' object for the package. Otherwise return None. + 'b''u'">'b'__init__.pyc'u'__init__.pyc'b'can't open Zip file: 'u'can't open Zip file: 'b'can't read Zip file: 'u'can't read Zip file: 'b'not a Zip file: 'u'not a Zip file: 'b'corrupt Zip file: 'u'corrupt Zip file: 'b'bad central directory size: 'u'bad central directory size: 'b'bad central directory offset: 'u'bad central directory offset: 'b'bad central directory size or offset: 'u'bad central directory size or offset: 'b'EOF read where not expected'u'EOF read where not expected'b'bad local header offset: 'u'bad local header offset: 'b'zipimport: found {} names in {!r}'u'zipimport: found {} names in {!r}'u' +  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ 'b'zipimport: zlib UNAVAILABLE'u'zipimport: zlib UNAVAILABLE'b'can't decompress data; zlib not available'u'can't decompress data; zlib not available'b'zipimport: zlib available'u'zipimport: zlib available'b'negative data size'u'negative data size'b'bad local file header: 'u'bad local file header: 'b'zipimport: can't read data'u'zipimport: can't read data'b'compiled module 'u'compiled module 'b' is not a code object'u' is not a code object'u'o'b'trying {}{}{}'u'trying {}{}{}'b'Private class used to support ZipImport.get_resource_reader(). + + This class is allowed to reference all the innards and private parts of + the zipimporter. + 'u'Private class used to support ZipImport.get_resource_reader(). + + This class is allowed to reference all the innards and private parts of + the zipimporter. + 'DEF_BUF_SIZEu'1.2.11'ZLIB_RUNTIME_VERSIONZLIB_VERSIONZ_BEST_COMPRESSIONZ_BEST_SPEEDZ_BLOCKZ_DEFAULT_STRATEGYZ_FILTEREDZ_FINISHZ_FIXEDZ_FULL_FLUSHZ_HUFFMAN_ONLYZ_NO_COMPRESSIONZ_NO_FLUSHZ_PARTIAL_FLUSHZ_RLEZ_TREESu'The functions in this module allow compression and decompression using the +zlib library, which is based on GNU zip. + +adler32(string[, start]) -- Compute an Adler-32 checksum. +compress(data[, level]) -- Compress data, with compression level 0-9 or -1. +compressobj([level[, ...]]) -- Return a compressor object. +crc32(string[, start]) -- Compute a CRC-32 checksum. +decompress(string,[wbits],[bufsize]) -- Decompresses a compressed string. +decompressobj([wbits[, zdict]]]) -- Return a decompressor object. + +'wbits' is window buffer size and container format. +Compressor objects support compress() and flush() methods; decompressor +objects support decompress() and flush().'u'/Users/pwntester/.pyenv/versions/3.8.13/lib/python3.8/lib-dynload/zlib.cpython-38-darwin.so'adler32zlib.error�q��Fe$ \ No newline at end of file