bytes.count(sub[, start[, end]])
bytearray.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.decode(encoding="utf-8", errors="strict")
bytearray.decode(encoding="utf-8", errors="strict")
Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings. By default, the errors argument is not checked for best performances, but only used at the first decoding error. Enable the Python Development Mode, or use a debug build to check errors.  Note Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.   Changed in version 3.1: Added support for keyword arguments.   Changed in version 3.9: The errors is now checked in development mode and in debug mode.


bytes.endswith(suffix[, start[, end]])
bytearray.endswith(suffix[, start[, end]])
Return True if the binary data ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. The suffix(es) to search for may be any bytes-like object.


bytes.expandtabs(tabsize=8)
bytearray.expandtabs(tabsize=8)
Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (b'\t'), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (b'\n') or carriage return (b'\r'), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed: >>> b'01\t012\t0123\t01234'.expandtabs()
b'01      012     0123    01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01  012 0123    01234'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.find(sub[, start[, end]])
bytearray.find(sub[, start[, end]])
Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Note The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator: >>> b'Py' in b'Python'
True
   Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


classmethod fromhex(string)
This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytes.fromhex('2Ef0 F1f2  ')
b'.\xf0\xf1\xf2'
  Changed in version 3.7: bytes.fromhex() now skips all ASCII whitespace in the string, not just spaces.


hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
 If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left. >>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
  New in version 3.5.   Changed in version 3.8: bytes.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


bytes.index(sub[, start[, end]])
bytearray.index(sub[, start[, end]])
Like find(), but raise ValueError when the subsequence is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.isalnum()
bytearray.isalnum()
Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimal digits are those byte values in the sequence b'0123456789'. For example: >>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False


bytes.isalpha()
bytearray.isalpha()
Return True if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. For example: >>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False


bytes.isascii()
bytearray.isascii()
Return True if the sequence is empty or all bytes in the sequence are ASCII, False otherwise. ASCII bytes are in the range 0-0x7F.  New in version 3.7.


bytes.isdigit()
bytearray.isdigit()
Return True if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, False otherwise. ASCII decimal digits are those byte values in the sequence b'0123456789'. For example: >>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False


bytes.islower()
bytearray.islower()
Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise. For example: >>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


bytes.isspace()
bytearray.isspace()
Return True if all bytes in the sequence are ASCII whitespace and the sequence is not empty, False otherwise. ASCII whitespace characters are those byte values in the sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form feed).


bytes.istitle()
bytearray.istitle()
Return True if the sequence is ASCII titlecase and the sequence is not empty, False otherwise. See bytes.title() for more details on the definition of “titlecase”. For example: >>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False


bytes.isupper()
bytearray.isupper()
Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise. For example: >>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


bytes.join(iterable)
bytearray.join(iterable)
Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A TypeError will be raised if there are any values in iterable that are not bytes-like objects, including str objects. The separator between elements is the contents of the bytes or bytearray object providing this method.


bytes.ljust(width[, fillbyte])
bytearray.ljust(width[, fillbyte])
Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.lower()
bytearray.lower()
Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart. For example: >>> b'Hello World'.lower()
b'hello world'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.lstrip([chars])
bytearray.lstrip([chars])
Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped: >>> b'   spacious   '.lstrip()
b'spacious   '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'
 The binary sequence of byte values to remove may be any bytes-like object. See removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example: >>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


static bytes.maketrans(from, to)
static bytearray.maketrans(from, to)
This static method returns a translation table usable for bytes.translate() that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length.  New in version 3.1.


bytes.partition(sep)
bytearray.partition(sep)
Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects. The separator to search for may be any bytes-like object.


bytes.removeprefix(prefix, /)
bytearray.removeprefix(prefix, /)
If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data: >>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'
 The prefix may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.   New in version 3.9.


bytes.removesuffix(suffix, /)
bytearray.removesuffix(suffix, /)
If the binary data ends with the suffix string and that suffix is not empty, return bytes[:-len(suffix)]. Otherwise, return a copy of the original binary data: >>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'
 The suffix may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.   New in version 3.9.


bytes.replace(old, new[, count])
bytearray.replace(old, new[, count])
Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. The subsequence to search for and its replacement may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.rfind(sub[, start[, end]])
bytearray.rfind(sub[, start[, end]])
Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.rindex(sub[, start[, end]])
bytearray.rindex(sub[, start[, end]])
Like rfind() but raises ValueError when the subsequence sub is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.rjust(width[, fillbyte])
bytearray.rjust(width[, fillbyte])
Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.rpartition(sep)
bytearray.rpartition(sep)
Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence. The separator to search for may be any bytes-like object.


bytes.rsplit(sep=None, maxsplit=-1)
bytearray.rsplit(sep=None, maxsplit=-1)
Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.


bytes.rstrip([chars])
bytearray.rstrip([chars])
Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped: >>> b'   spacious   '.rstrip()
b'   spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'
 The binary sequence of byte values to remove may be any bytes-like object. See removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example: >>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.split(sep=None, maxsplit=-1)
bytearray.split(sep=None, maxsplit=-1)
Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, b'1,,2'.split(b',') returns [b'1', b'', b'2']). The sep argument may consist of a multibyte sequence (for example, b'1<>2<>3'.split(b'<>') returns [b'1', b'2', b'3']). Splitting an empty sequence with a specified separator returns [b''] or [bytearray(b'')] depending on the type of object being split. The sep argument may be any bytes-like object. For example: >>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
 If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns []. For example: >>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b'   1   2   3   '.split()
[b'1', b'2', b'3']


bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)
Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true. For example: >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
 Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line: >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])


bytes.startswith(prefix[, start[, end]])
bytearray.startswith(prefix[, start[, end]])
Return True if the binary data starts with the specified prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. The prefix(es) to search for may be any bytes-like object.


bytes.strip([chars])
bytearray.strip([chars])
Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> b'   spacious   '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'
 The binary sequence of byte values to remove may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.swapcase()
bytearray.swapcase()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa. For example: >>> b'Hello World'.swapcase()
b'hELLO wORLD'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Unlike str.swapcase(), it is always the case that bin.swapcase().swapcase() == bin for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.title()
bytearray.title()
Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified. For example: >>> b'Hello world'.title()
b'Hello World'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. All other byte values are uncased. The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result: >>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"
 A workaround for apostrophes can be constructed using regular expressions: >>> import re
>>> def titlecase(s):
...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0:1].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.translate(table, /, delete=b'')
bytearray.translate(table, /, delete=b'')
Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256. You can use the bytes.maketrans() method to create a translation table. Set the table argument to None for translations that only delete characters: >>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
  Changed in version 3.6: delete is now supported as a keyword argument.


bytes.upper()
bytearray.upper()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart. For example: >>> b'Hello World'.upper()
b'HELLO WORLD'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.zfill(width)
bytearray.zfill(width)
Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-') is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq). For example: >>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


exception BytesWarning
Base class for warnings related to bytes and bytearray.


bz2 — Support for bzip2 compression Source code: Lib/bz2.py This module provides a comprehensive interface for compressing and decompressing data using the bzip2 compression algorithm. The bz2 module contains:  The open() function and BZ2File class for reading and writing compressed files. The BZ2Compressor and BZ2Decompressor classes for incremental (de)compression. The compress() and decompress() functions for one-shot (de)compression.  All of the classes in this module may safely be accessed from multiple threads. (De)compression of files
bz2.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
Open a bzip2-compressed file in binary or text mode, returning a file object. As with the constructor for BZ2File, the filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to. The mode argument can be any of 'r', 'rb', 'w', 'wb', 'x', 'xb', 'a' or 'ab' for binary mode, or 'rt', 'wt', 'xt', or 'at' for text mode. The default is 'rb'. The compresslevel argument is an integer from 1 to 9, as for the BZ2File constructor. For binary mode, this function is equivalent to the BZ2File constructor: BZ2File(filename, mode, compresslevel=compresslevel). In this case, the encoding, errors and newline arguments must not be provided. For text mode, a BZ2File object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).  New in version 3.3.   Changed in version 3.4: The 'x' (exclusive creation) mode was added.   Changed in version 3.6: Accepts a path-like object.

class bz2.BZ2File(filename, mode='r', *, compresslevel=9)
Open a bzip2-compressed file in binary mode. If filename is a str or bytes object, open the named file directly. Otherwise, filename should be a file object, which will be used to read or write the compressed data. The mode argument can be either 'r' for reading (default), 'w' for overwriting, 'x' for exclusive creation, or 'a' for appending. These can equivalently be given as 'rb', 'wb', 'xb' and 'ab' respectively. If filename is a file object (rather than an actual file name), a mode of 'w' does not truncate the file, and is instead equivalent to 'a'. If mode is 'w' or 'a', compresslevel can be an integer between 1 and 9 specifying the level of compression: 1 produces the least compression, and 9 (default) produces the most compression. If mode is 'r', the input file may be the concatenation of multiple compressed streams. BZ2File provides all of the members specified by the io.BufferedIOBase, except for detach() and truncate(). Iteration and the with statement are supported. BZ2File also provides the following method:
peek([n])
Return buffered data without advancing the file position. At least one byte of data will be returned (unless at EOF). The exact number of bytes returned is unspecified.  Note While calling peek() does not change the file position of the BZ2File, it may change the position of the underlying file object (e.g. if the BZ2File was constructed by passing a file object for filename).   New in version 3.3.
  Changed in version 3.1: Support for the with statement was added.   Changed in version 3.3: The fileno(), readable(), seekable(), writable(), read1() and readinto() methods were added.   Changed in version 3.3: Support was added for filename being a file object instead of an actual filename.   Changed in version 3.3: The 'a' (append) mode was added, along with support for reading multi-stream files.   Changed in version 3.4: The 'x' (exclusive creation) mode was added.   Changed in version 3.5: The read() method now accepts an argument of None.   Changed in version 3.6: Accepts a path-like object.   Changed in version 3.9: The buffering parameter has been removed. It was ignored and deprecated since Python 3.0. Pass an open file object to control how the file is opened. The compresslevel parameter became keyword-only.
 Incremental (de)compression
class bz2.BZ2Compressor(compresslevel=9)
Create a new compressor object. This object may be used to compress data incrementally. For one-shot compression, use the compress() function instead. compresslevel, if given, must be an integer between 1 and 9. The default is 9.
compress(data)
Provide data to the compressor object. Returns a chunk of compressed data if possible, or an empty byte string otherwise. When you have finished providing data to the compressor, call the flush() method to finish the compression process.

flush()
Finish the compression process. Returns the compressed data left in internal buffers. The compressor object may not be used after this method has been called.

class bz2.BZ2Decompressor
Create a new decompressor object. This object may be used to decompress data incrementally. For one-shot compression, use the decompress() function instead.  Note This class does not transparently handle inputs containing multiple compressed streams, unlike decompress() and BZ2File. If you need to decompress a multi-stream input with BZ2Decompressor, you must use a new decompressor for each stream.
decompress(data, max_length=-1)
Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress(). If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output. If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True. Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute.  Changed in version 3.5: Added the max_length parameter.

eof
True if the end-of-stream marker has been reached.  New in version 3.3.

unused_data
Data found after the end of the compressed stream. If this attribute is accessed before the end of the stream has been reached, its value will be b''.

needs_input
False if the decompress() method can provide more decompressed data before requiring new uncompressed input.  New in version 3.5.

 One-shot (de)compression
bz2.compress(data, compresslevel=9)
Compress data, a bytes-like object. compresslevel, if given, must be an integer between 1 and 9. The default is 9. For incremental compression, use a BZ2Compressor instead.

bz2.decompress(data)
Decompress data, a bytes-like object. If data is the concatenation of multiple compressed streams, decompress all of the streams. For incremental decompression, use a BZ2Decompressor instead.  Changed in version 3.3: Support for multi-stream inputs was added.
 Examples of usage Below are some examples of typical usage of the bz2 module. Using compress() and decompress() to demonstrate round-trip compression: >>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> c = bz2.compress(data)
>>> len(data) / len(c)  # Data compression ratio
1.513595166163142
>>> d = bz2.decompress(c)
>>> data == d  # Check equality to original object after round-trip
True
 Using BZ2Compressor for incremental compression: >>> import bz2
>>> def gen_data(chunks=10, chunksize=1000):
...     """Yield incremental blocks of chunksize bytes."""
...     for _ in range(chunks):
...         yield b"z" * chunksize
...
>>> comp = bz2.BZ2Compressor()
>>> out = b""
>>> for chunk in gen_data():
...     # Provide data to the compressor object
...     out = out + comp.compress(chunk)
...
>>> # Finish the compression process.  Call this once you have
>>> # finished providing data to the compressor.
>>> out = out + comp.flush()
 The example above uses a very “nonrandom” stream of data (a stream of b”z” chunks). Random data tends to compress poorly, while ordered, repetitive data usually yields a high compression ratio. Writing and reading a bzip2-compressed file in binary mode: >>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> with bz2.open("myfile.bz2", "wb") as f:
...     # Write compressed data to file
...     unused = f.write(data)
>>> with bz2.open("myfile.bz2", "rb") as f:
...     # Decompress data from file
...     content = f.read()
>>> content == data  # Check equality to original object after round-trip
True


class bz2.BZ2Compressor(compresslevel=9)
Create a new compressor object. This object may be used to compress data incrementally. For one-shot compression, use the compress() function instead. compresslevel, if given, must be an integer between 1 and 9. The default is 9.
compress(data)
Provide data to the compressor object. Returns a chunk of compressed data if possible, or an empty byte string otherwise. When you have finished providing data to the compressor, call the flush() method to finish the compression process.

flush()
Finish the compression process. Returns the compressed data left in internal buffers. The compressor object may not be used after this method has been called.


compress(data)
Provide data to the compressor object. Returns a chunk of compressed data if possible, or an empty byte string otherwise. When you have finished providing data to the compressor, call the flush() method to finish the compression process.


flush()
Finish the compression process. Returns the compressed data left in internal buffers. The compressor object may not be used after this method has been called.


class bz2.BZ2Decompressor
Create a new decompressor object. This object may be used to decompress data incrementally. For one-shot compression, use the decompress() function instead.  Note This class does not transparently handle inputs containing multiple compressed streams, unlike decompress() and BZ2File. If you need to decompress a multi-stream input with BZ2Decompressor, you must use a new decompressor for each stream.
decompress(data, max_length=-1)
Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress(). If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output. If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True. Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute.  Changed in version 3.5: Added the max_length parameter.

eof
True if the end-of-stream marker has been reached.  New in version 3.3.

unused_data
Data found after the end of the compressed stream. If this attribute is accessed before the end of the stream has been reached, its value will be b''.

needs_input
False if the decompress() method can provide more decompressed data before requiring new uncompressed input.  New in version 3.5.


decompress(data, max_length=-1)
Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress(). If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output. If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True. Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute.  Changed in version 3.5: Added the max_length parameter.


eof
True if the end-of-stream marker has been reached.  New in version 3.3.


needs_input
False if the decompress() method can provide more decompressed data before requiring new uncompressed input.  New in version 3.5.


unused_data
Data found after the end of the compressed stream. If this attribute is accessed before the end of the stream has been reached, its value will be b''.


class bz2.BZ2File(filename, mode='r', *, compresslevel=9)
Open a bzip2-compressed file in binary mode. If filename is a str or bytes object, open the named file directly. Otherwise, filename should be a file object, which will be used to read or write the compressed data. The mode argument can be either 'r' for reading (default), 'w' for overwriting, 'x' for exclusive creation, or 'a' for appending. These can equivalently be given as 'rb', 'wb', 'xb' and 'ab' respectively. If filename is a file object (rather than an actual file name), a mode of 'w' does not truncate the file, and is instead equivalent to 'a'. If mode is 'w' or 'a', compresslevel can be an integer between 1 and 9 specifying the level of compression: 1 produces the least compression, and 9 (default) produces the most compression. If mode is 'r', the input file may be the concatenation of multiple compressed streams. BZ2File provides all of the members specified by the io.BufferedIOBase, except for detach() and truncate(). Iteration and the with statement are supported. BZ2File also provides the following method:
peek([n])
Return buffered data without advancing the file position. At least one byte of data will be returned (unless at EOF). The exact number of bytes returned is unspecified.  Note While calling peek() does not change the file position of the BZ2File, it may change the position of the underlying file object (e.g. if the BZ2File was constructed by passing a file object for filename).   New in version 3.3.
  Changed in version 3.1: Support for the with statement was added.   Changed in version 3.3: The fileno(), readable(), seekable(), writable(), read1() and readinto() methods were added.   Changed in version 3.3: Support was added for filename being a file object instead of an actual filename.   Changed in version 3.3: The 'a' (append) mode was added, along with support for reading multi-stream files.   Changed in version 3.4: The 'x' (exclusive creation) mode was added.   Changed in version 3.5: The read() method now accepts an argument of None.   Changed in version 3.6: Accepts a path-like object.   Changed in version 3.9: The buffering parameter has been removed. It was ignored and deprecated since Python 3.0. Pass an open file object to control how the file is opened. The compresslevel parameter became keyword-only.


peek([n])
Return buffered data without advancing the file position. At least one byte of data will be returned (unless at EOF). The exact number of bytes returned is unspecified.  Note While calling peek() does not change the file position of the BZ2File, it may change the position of the underlying file object (e.g. if the BZ2File was constructed by passing a file object for filename).   New in version 3.3.


bz2.compress(data, compresslevel=9)
Compress data, a bytes-like object. compresslevel, if given, must be an integer between 1 and 9. The default is 9. For incremental compression, use a BZ2Compressor instead.


bz2.decompress(data)
Decompress data, a bytes-like object. If data is the concatenation of multiple compressed streams, decompress all of the streams. For incremental decompression, use a BZ2Decompressor instead.  Changed in version 3.3: Support for multi-stream inputs was added.


bz2.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
Open a bzip2-compressed file in binary or text mode, returning a file object. As with the constructor for BZ2File, the filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to. The mode argument can be any of 'r', 'rb', 'w', 'wb', 'x', 'xb', 'a' or 'ab' for binary mode, or 'rt', 'wt', 'xt', or 'at' for text mode. The default is 'rb'. The compresslevel argument is an integer from 1 to 9, as for the BZ2File constructor. For binary mode, this function is equivalent to the BZ2File constructor: BZ2File(filename, mode, compresslevel=compresslevel). In this case, the encoding, errors and newline arguments must not be provided. For text mode, a BZ2File object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).  New in version 3.3.   Changed in version 3.4: The 'x' (exclusive creation) mode was added.   Changed in version 3.6: Accepts a path-like object.


calendar — General calendar-related functions Source code: Lib/calendar.py This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. Parameters that specify dates are given as integers. For related functionality, see also the datetime and time modules. The functions and classes defined in this module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. This matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book “Calendrical Calculations”, where it’s the base calendar for all computations. Zero and negative years are interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is 2 BC, and so on.
class calendar.Calendar(firstweekday=0)
Creates a Calendar object. firstweekday is an integer specifying the first day of the week. 0 is Monday (the default), 6 is Sunday. A Calendar object provides several methods that can be used for preparing the calendar data for formatting. This class doesn’t do any formatting itself. This is the job of subclasses. Calendar instances have the following methods:
iterweekdays()
Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the firstweekday property.

itermonthdates(year, month)
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.

itermonthdays(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.

itermonthdays2(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.

itermonthdays3(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.  New in version 3.7.

itermonthdays4(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.  New in version 3.7.

monthdatescalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.

monthdays2calendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.

monthdayscalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.

yeardatescalendar(year, width=3)
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.

yeardays2calendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.

yeardayscalendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.

class calendar.TextCalendar(firstweekday=0)
This class can be used to generate plain text calendars. TextCalendar instances have the following methods:
formatmonth(theyear, themonth, w=0, l=0)
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.

prmonth(theyear, themonth, w=0, l=0)
Print a month’s calendar as returned by formatmonth().

formatyear(theyear, w=2, l=1, c=6, m=3)
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.

pryear(theyear, w=2, l=1, c=6, m=3)
Print the calendar for an entire year as returned by formatyear().

class calendar.HTMLCalendar(firstweekday=0)
This class can be used to generate HTML calendars. HTMLCalendar instances have the following methods:
formatmonth(theyear, themonth, withyear=True)
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.

formatyear(theyear, width=3)
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.

formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).
 HTMLCalendar has the following attributes you can override to customize the CSS classes used by the calendar:
cssclasses
A list of CSS classes used for each weekday. The default class list is: cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
 more styles can be added for each day: cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
 Note that the length of this list must be seven items.

cssclass_noday
The CSS class for a weekday occurring in the previous or coming month.  New in version 3.7.

cssclasses_weekday_head
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses.  New in version 3.7.

cssclass_month_head
The month’s head CSS class (used by formatmonthname()). The default value is "month".  New in version 3.7.

cssclass_month
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month".  New in version 3.7.

cssclass_year
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year".  New in version 3.7.

cssclass_year_head
The CSS class for the table head for the whole year (used by formatyear()). The default value is "year".  New in version 3.7.
 Note that although the naming for the above described class attributes is singular (e.g. cssclass_month cssclass_noday), one can replace the single CSS class with a space separated list of CSS classes, for example: "text-bold text-red"
 Here is an example how HTMLCalendar can be customized: class CustomHTMLCal(calendar.HTMLCalendar):
    cssclasses = [style + " text-nowrap" for style in
                  calendar.HTMLCalendar.cssclasses]
    cssclass_month_head = "text-center month-head"
    cssclass_month = "text-center month"
    cssclass_year = "text-italic lead"

class calendar.LocaleTextCalendar(firstweekday=0, locale=None)
This subclass of TextCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.

class calendar.LocaleHTMLCalendar(firstweekday=0, locale=None)
This subclass of HTMLCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.
  Note The formatweekday() and formatmonthname() methods of these two classes temporarily change the current locale to the given locale. Because the current locale is a process-wide setting, they are not thread-safe.  For simple text calendars this module provides the following functions.
calendar.setfirstweekday(weekday)
Sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience. For example, to set the first weekday to Sunday: import calendar
calendar.setfirstweekday(calendar.SUNDAY)

calendar.firstweekday()
Returns the current setting for the weekday to start each week.

calendar.isleap(year)
Returns True if year is a leap year, otherwise False.

calendar.leapdays(y1, y2)
Returns the number of leap years in the range from y1 to y2 (exclusive), where y1 and y2 are years. This function works for ranges spanning a century change.

calendar.weekday(year, month, day)
Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31).

calendar.weekheader(n)
Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.

calendar.monthrange(year, month)
Returns weekday of first day of the month and number of days in month, for the specified year and month.

calendar.monthcalendar(year, month)
Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month are represented by zeros. Each week begins with Monday unless set by setfirstweekday().

calendar.prmonth(theyear, themonth, w=0, l=0)
Prints a month’s calendar as returned by month().

calendar.month(theyear, themonth, w=0, l=0)
Returns a month’s calendar in a multi-line string using the formatmonth() of the TextCalendar class.

calendar.prcal(year, w=0, l=0, c=6, m=3)
Prints the calendar for an entire year as returned by calendar().

calendar.calendar(year, w=2, l=1, c=6, m=3)
Returns a 3-column calendar for an entire year as a multi-line string using the formatyear() of the TextCalendar class.

calendar.timegm(tuple)
An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.
 The calendar module exports the following data attributes:
calendar.day_name
An array that represents the days of the week in the current locale.

calendar.day_abbr
An array that represents the abbreviated days of the week in the current locale.

calendar.month_name
An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_name[0] is the empty string.

calendar.month_abbr
An array that represents the abbreviated months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_abbr[0] is the empty string.
  See also
Module datetime

Object-oriented interface to dates and times with similar functionality to the time module.
Module time

Low-level time related functions.


class calendar.Calendar(firstweekday=0)
Creates a Calendar object. firstweekday is an integer specifying the first day of the week. 0 is Monday (the default), 6 is Sunday. A Calendar object provides several methods that can be used for preparing the calendar data for formatting. This class doesn’t do any formatting itself. This is the job of subclasses. Calendar instances have the following methods:
iterweekdays()
Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the firstweekday property.

itermonthdates(year, month)
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.

itermonthdays(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.

itermonthdays2(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.

itermonthdays3(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.  New in version 3.7.

itermonthdays4(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.  New in version 3.7.

monthdatescalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.

monthdays2calendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.

monthdayscalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.

yeardatescalendar(year, width=3)
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.

yeardays2calendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.

yeardayscalendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.


calendar.calendar(year, w=2, l=1, c=6, m=3)
Returns a 3-column calendar for an entire year as a multi-line string using the formatyear() of the TextCalendar class.


itermonthdates(year, month)
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.


itermonthdays(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.


itermonthdays2(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.


itermonthdays3(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.  New in version 3.7.


itermonthdays4(year, month)
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.  New in version 3.7.


iterweekdays()
Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the firstweekday property.


monthdatescalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.


monthdays2calendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.


monthdayscalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.


yeardatescalendar(year, width=3)
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.


yeardays2calendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.


yeardayscalendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.


calendar.day_abbr
An array that represents the abbreviated days of the week in the current locale.


calendar.day_name
An array that represents the days of the week in the current locale.


calendar.firstweekday()
Returns the current setting for the weekday to start each week.


class calendar.HTMLCalendar(firstweekday=0)
This class can be used to generate HTML calendars. HTMLCalendar instances have the following methods:
formatmonth(theyear, themonth, withyear=True)
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.

formatyear(theyear, width=3)
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.

formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).
 HTMLCalendar has the following attributes you can override to customize the CSS classes used by the calendar:
cssclasses
A list of CSS classes used for each weekday. The default class list is: cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
 more styles can be added for each day: cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
 Note that the length of this list must be seven items.

cssclass_noday
The CSS class for a weekday occurring in the previous or coming month.  New in version 3.7.

cssclasses_weekday_head
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses.  New in version 3.7.

cssclass_month_head
The month’s head CSS class (used by formatmonthname()). The default value is "month".  New in version 3.7.

cssclass_month
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month".  New in version 3.7.

cssclass_year
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year".  New in version 3.7.

cssclass_year_head
The CSS class for the table head for the whole year (used by formatyear()). The default value is "year".  New in version 3.7.
 Note that although the naming for the above described class attributes is singular (e.g. cssclass_month cssclass_noday), one can replace the single CSS class with a space separated list of CSS classes, for example: "text-bold text-red"
 Here is an example how HTMLCalendar can be customized: class CustomHTMLCal(calendar.HTMLCalendar):
    cssclasses = [style + " text-nowrap" for style in
                  calendar.HTMLCalendar.cssclasses]
    cssclass_month_head = "text-center month-head"
    cssclass_month = "text-center month"
    cssclass_year = "text-italic lead"


cssclasses
A list of CSS classes used for each weekday. The default class list is: cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
 more styles can be added for each day: cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
 Note that the length of this list must be seven items.


cssclasses_weekday_head
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses.  New in version 3.7.


cssclass_month
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month".  New in version 3.7.


cssclass_month_head
The month’s head CSS class (used by formatmonthname()). The default value is "month".  New in version 3.7.


cssclass_noday
The CSS class for a weekday occurring in the previous or coming month.  New in version 3.7.


cssclass_year
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year".  New in version 3.7.


cssclass_year_head
The CSS class for the table head for the whole year (used by formatyear()). The default value is "year".  New in version 3.7.


formatmonth(theyear, themonth, withyear=True)
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.


formatyear(theyear, width=3)
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.


formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).


calendar.isleap(year)
Returns True if year is a leap year, otherwise False.


calendar.leapdays(y1, y2)
Returns the number of leap years in the range from y1 to y2 (exclusive), where y1 and y2 are years. This function works for ranges spanning a century change.


class calendar.LocaleHTMLCalendar(firstweekday=0, locale=None)
This subclass of HTMLCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.


class calendar.LocaleTextCalendar(firstweekday=0, locale=None)
This subclass of TextCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.


calendar.month(theyear, themonth, w=0, l=0)
Returns a month’s calendar in a multi-line string using the formatmonth() of the TextCalendar class.


calendar.monthcalendar(year, month)
Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month are represented by zeros. Each week begins with Monday unless set by setfirstweekday().


calendar.monthrange(year, month)
Returns weekday of first day of the month and number of days in month, for the specified year and month.


calendar.month_abbr
An array that represents the abbreviated months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_abbr[0] is the empty string.


calendar.month_name
An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_name[0] is the empty string.


calendar.prcal(year, w=0, l=0, c=6, m=3)
Prints the calendar for an entire year as returned by calendar().


calendar.prmonth(theyear, themonth, w=0, l=0)
Prints a month’s calendar as returned by month().


calendar.setfirstweekday(weekday)
Sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience. For example, to set the first weekday to Sunday: import calendar
calendar.setfirstweekday(calendar.SUNDAY)


class calendar.TextCalendar(firstweekday=0)
This class can be used to generate plain text calendars. TextCalendar instances have the following methods:
formatmonth(theyear, themonth, w=0, l=0)
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.

prmonth(theyear, themonth, w=0, l=0)
Print a month’s calendar as returned by formatmonth().

formatyear(theyear, w=2, l=1, c=6, m=3)
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.

pryear(theyear, w=2, l=1, c=6, m=3)
Print the calendar for an entire year as returned by formatyear().


formatmonth(theyear, themonth, w=0, l=0)
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.


formatyear(theyear, w=2, l=1, c=6, m=3)
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.


prmonth(theyear, themonth, w=0, l=0)
Print a month’s calendar as returned by formatmonth().


pryear(theyear, w=2, l=1, c=6, m=3)
Print the calendar for an entire year as returned by formatyear().


calendar.timegm(tuple)
An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.


calendar.weekday(year, month, day)
Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31).


calendar.weekheader(n)
Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.


callable(object)
Return True if the object argument appears callable, False if not. If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.  New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.


cgi — Common Gateway Interface support Source code: Lib/cgi.py Support module for Common Gateway Interface (CGI) scripts. This module defines a number of utilities for use by CGI scripts written in Python. Introduction A CGI script is invoked by an HTTP server, usually to process user input submitted through an HTML <FORM> or <ISINDEX> element. Most often, CGI scripts live in the server’s special cgi-bin directory. The HTTP server places all sorts of information about the request (such as the client’s hostname, the requested URL, the query string, and lots of other goodies) in the script’s shell environment, executes the script, and sends the script’s output back to the client. The script’s input is connected to the client too, and sometimes the form data is read this way; at other times the form data is passed via the “query string” part of the URL. This module is intended to take care of the different cases and provide a simpler interface to the Python script. It also provides a number of utilities that help in debugging scripts, and the latest addition is support for file uploads from a form (if your browser supports it). The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is following. Python code to generate a minimal header section looks like this: print("Content-Type: text/html")    # HTML is following
print()                             # blank line, end of headers
 The second section is usually HTML, which allows the client software to display nicely formatted text with header, in-line images, etc. Here’s Python code that prints a simple piece of HTML: print("<TITLE>CGI script output</TITLE>")
print("
This is my first CGI script
")
print("Hello, world!")
 Using the cgi module Begin by writing import cgi. When you write a new script, consider adding these lines: import cgitb
cgitb.enable()
 This activates a special exception handler that will display detailed reports in the Web browser if any errors occur. If you’d rather not show the guts of your program to users of your script, you can have the reports saved to files instead, with code like this: import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")
 It’s very helpful to use this feature during script development. The reports produced by cgitb provide information that can save you a lot of time in tracking down bugs. You can always remove the cgitb line later when you have tested your script and are confident that it works correctly. To get at submitted form data, use the FieldStorage class. If the form contains non-ASCII characters, use the encoding keyword parameter set to the value of the encoding defined for the document. It is usually contained in the META tag in the HEAD section of the HTML document or by the Content-Type header). This reads the form contents from the standard input or the environment (depending on the value of various environment variables set according to the CGI standard). Since it may consume standard input, it should be instantiated only once. The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator, and also supports the standard dictionary method keys() and the built-in function len(). Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep_blank_values keyword parameter when creating the FieldStorage instance. For instance, the following code (which assumes that the Content-Type header and blank line have already been printed) checks that the fields name and addr are both set to a non-empty string: form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
    print("
Error
")
    print("Please fill in the name and addr fields.")
    return
print("
name:", form["name"].value)
print("
addr:", form["addr"].value)
...further form processing here...
 Here the fields, accessed through form[key], are themselves instances of FieldStorage (or MiniFieldStorage, depending on the form encoding). The value attribute of the instance yields the string value of the field. The getvalue() method returns this string value directly; it also accepts an optional second argument as a default to return if the requested key is not present. If the submitted form data contains more than one field with the same name, the object retrieved by form[key] is not a FieldStorage or MiniFieldStorage instance but a list of such instances. Similarly, in this situation, form.getvalue(key) would return a list of strings. If you expect this possibility (when your HTML form contains multiple fields with the same name), use the getlist() method, which always returns a list of values (so that you do not need to special-case the single item case). For example, this code concatenates any number of username fields, separated by commas: value = form.getlist("username")
usernames = ",".join(value)
 If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as bytes. This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute. You can then read the data from the file attribute before it is automatically closed as part of the garbage collection of the FieldStorage instance (the read() and readline() methods will return bytes): fileitem = form["userfile"]
if fileitem.file:
    # It's an uploaded file; count lines
    linecount = 0
    while True:
        line = fileitem.file.readline()
        if not line: break
        linecount = linecount + 1
 FieldStorage objects also support being used in a with statement, which will automatically close them when done. If an error is encountered when obtaining the contents of an uploaded file (for example, when the user interrupts the form submission by clicking on a Back or Cancel button) the done attribute of the object for the field will be set to the value -1. The file upload draft standard entertains the possibility of uploading multiple files from one field (using a recursive multipart/* encoding). When this occurs, the item will be a dictionary-like FieldStorage item. This can be determined by testing its type attribute, which should be multipart/form-data (or perhaps another MIME type matching multipart/*). In this case, it can be iterated over recursively just like the top-level form object. When a form is submitted in the “old” format (as the query string or as a single data part of type application/x-www-form-urlencoded), the items will actually be instances of the class MiniFieldStorage. In this case, the list, file, and filename attributes are always None. A form submitted via POST that also has a query string will contain both FieldStorage and MiniFieldStorage items.  Changed in version 3.4: The file attribute is automatically closed upon the garbage collection of the creating FieldStorage instance.   Changed in version 3.5: Added support for the context management protocol to the FieldStorage class.  Higher Level Interface The previous section explains how to read CGI form data using the FieldStorage class. This section describes a higher level interface which was added to this class to allow one to do it in a more readable and intuitive way. The interface doesn’t make the techniques described in previous sections obsolete — they are still useful to process file uploads efficiently, for example. The interface consists of two simple methods. Using the methods you can process form data in a generic way, without the need to worry whether only one or more values were posted under one name. In the previous section, you learned to write following code anytime you expected a user to post more than one value under one name: item = form.getvalue("item")
if isinstance(item, list):
    # The user is requesting more than one item.
else:
    # The user is requesting only one item.
 This situation is common for example when a form contains a group of multiple checkboxes with the same name: <input type="checkbox" name="item" value="1" />
<input type="checkbox" name="item" value="2" />
 In most situations, however, there’s only one form control with a particular name in a form and then you expect and need only one value associated with this name. So you write a script containing for example this code: user = form.getvalue("user").upper()
 The problem with the code is that you should never expect that a client will provide valid input to your scripts. For example, if a curious user appends another user=foo pair to the query string, then the script would crash, because in this situation the getvalue("user") method call returns a list instead of a string. Calling the upper() method on a list is not valid (since lists do not have a method of this name) and results in an AttributeError exception. Therefore, the appropriate way to read form data values was to always use the code which checks whether the obtained value is a single value or a list of values. That’s annoying and leads to less readable scripts. A more convenient approach is to use the methods getfirst() and getlist() provided by this higher level interface.
FieldStorage.getfirst(name, default=None)
This method always returns only one value associated with form field name. The method returns only the first value in case that more values were posted under such name. Please note that the order in which the values are received may vary from browser to browser and should not be counted on. 1 If no such form field or value exists then the method returns the value specified by the optional parameter default. This parameter defaults to None if not specified.

FieldStorage.getlist(name)
This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists.
 Using these methods you can write nice compact code: import cgi
form = cgi.FieldStorage()
user = form.getfirst("user", "").upper()    # This way it's safe.
for item in form.getlist("item"):
    do_something(item)
 Functions These are useful if you want more control, or if you want to employ some of the algorithms implemented in this module in other circumstances.
cgi.parse(fp=None, environ=os.environ, keep_blank_values=False, strict_parsing=False, separator="&")
Parse a query in the environment or from a file (the file defaults to sys.stdin). The keep_blank_values, strict_parsing and separator parameters are passed to urllib.parse.parse_qs() unchanged.

cgi.parse_multipart(fp, pdict, encoding="utf-8", errors="replace", separator="&")
Parse input of type multipart/form-data (for file uploads). Arguments are fp for the input file, pdict for a dictionary containing other parameters in the Content-Type header, and encoding, the request encoding. Returns a dictionary just like urllib.parse.parse_qs(): keys are the field names, each value is a list of values for that field. For non-file fields, the value is a list of strings. This is easy to use but not much good if you are expecting megabytes to be uploaded — in that case, use the FieldStorage class instead which is much more flexible.  Changed in version 3.7: Added the encoding and errors parameters. For non-file fields, the value is now a list of strings, not bytes.   Changed in version 3.9.2: Added the separator parameter.

cgi.parse_header(string)
Parse a MIME header (such as Content-Type) into a main value and a dictionary of parameters.

cgi.test()
Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.

cgi.print_environ()
Format the shell environment in HTML.

cgi.print_form(form)
Format a form in HTML.

cgi.print_directory()
Format the current directory in HTML.

cgi.print_environ_usage()
Print a list of useful (used by CGI) environment variables in HTML.
 Caring about security There’s one important rule: if you invoke an external program (via the os.system() or os.popen() functions. or others with similar functionality), make very sure you don’t pass arbitrary strings received from the client to the shell. This is a well-known security hole whereby clever hackers anywhere on the Web can exploit a gullible CGI script to invoke arbitrary shell commands. Even parts of the URL or field names cannot be trusted, since the request doesn’t have to come from your form! To be on the safe side, if you must pass a string gotten from a form to a shell command, you should make sure the string contains only alphanumeric characters, dashes, underscores, and periods. Installing your CGI script on a Unix system Read the documentation for your HTTP server and check with your local system administrator to find the directory where CGI scripts should be installed; usually this is in a directory cgi-bin in the server tree. Make sure that your script is readable and executable by “others”; the Unix file mode should be 0o755 octal (use chmod 0755 filename). Make sure that the first line of the script contains #! starting in column 1 followed by the pathname of the Python interpreter, for instance: #!/usr/local/bin/python
 Make sure the Python interpreter exists and is executable by “others”. Make sure that any files your script needs to read or write are readable or writable, respectively, by “others” — their mode should be 0o644 for readable and 0o666 for writable. This is because, for security reasons, the HTTP server executes your script as user “nobody”, without any special privileges. It can only read (write, execute) files that everybody can read (write, execute). The current directory at execution time is also different (it is usually the server’s cgi-bin directory) and the set of environment variables is also different from what you get when you log in. In particular, don’t count on the shell’s search path for executables (PATH) or the Python module search path (PYTHONPATH) to be set to anything interesting. If you need to load modules from a directory which is not on Python’s default module search path, you can change the path in your script, before importing other modules. For example: import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
sys.path.insert(0, "/usr/local/lib/python")
 (This way, the directory inserted last will be searched first!) Instructions for non-Unix systems will vary; check your HTTP server’s documentation (it will usually have a section on CGI scripts). Testing your CGI script Unfortunately, a CGI script will generally not run when you try it from the command line, and a script that works perfectly from the command line may fail mysteriously when run from the server. There’s one reason why you should still test your script from the command line: if it contains a syntax error, the Python interpreter won’t execute it at all, and the HTTP server will most likely send a cryptic error to the client. Assuming your script has no syntax errors, yet it does not work, you have no choice but to read the next section. Debugging CGI scripts First of all, check for trivial installation errors — reading the section above on installing your CGI script carefully can save you a lot of time. If you wonder whether you have understood the installation procedure correctly, try installing a copy of this module file (cgi.py) as a CGI script. When invoked as a script, the file will dump its environment and the contents of the form in HTML form. Give it the right mode etc, and send it a request. If it’s installed in the standard cgi-bin directory, it should be possible to send it a request by entering a URL into your browser of the form: http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
 If this gives an error of type 404, the server cannot find the script – perhaps you need to install it in a different directory. If it gives another error, there’s an installation problem that you should fix before trying to go any further. If you get a nicely formatted listing of the environment and form content (in this example, the fields should be listed as “addr” with value “At Home” and “name” with value “Joe Blow”), the cgi.py script has been installed correctly. If you follow the same procedure for your own script, you should now be able to debug it. The next step could be to call the cgi module’s test() function from your script: replace its main code with the single statement cgi.test()
 This should produce the same results as those gotten from installing the cgi.py file itself. When an ordinary Python script raises an unhandled exception (for whatever reason: of a typo in a module name, a file that can’t be opened, etc.), the Python interpreter prints a nice traceback and exits. While the Python interpreter will still do this when your CGI script raises an exception, most likely the traceback will end up in one of the HTTP server’s log files, or be discarded altogether. Fortunately, once you have managed to get your script to execute some code, you can easily send tracebacks to the Web browser using the cgitb module. If you haven’t done so already, just add the lines: import cgitb
cgitb.enable()
 to the top of your script. Then try running it again; when a problem occurs, you should see a detailed report that will likely make apparent the cause of the crash. If you suspect that there may be a problem in importing the cgitb module, you can use an even more robust approach (which only uses built-in modules): import sys
sys.stderr = sys.stdout
print("Content-Type: text/plain")
print()
...your code here...
 This relies on the Python interpreter to print the traceback. The content type of the output is set to plain text, which disables all HTML processing. If your script works, the raw HTML will be displayed by your client. If it raises an exception, most likely after the first two lines have been printed, a traceback will be displayed. Because no HTML interpretation is going on, the traceback will be readable. Common problems and solutions  Most HTTP servers buffer the output from CGI scripts until the script is completed. This means that it is not possible to display a progress report on the client’s display while the script is running. Check the installation instructions above. Check the HTTP server’s log files. (tail -f logfile in a separate window may be useful!) Always check a script for syntax errors first, by doing something like python script.py. If your script does not have any syntax errors, try adding import cgitb;
cgitb.enable() to the top of the script. When invoking external programs, make sure they can be found. Usually, this means using absolute path names — PATH is usually not set to a very useful value in a CGI script. When reading or writing external files, make sure they can be read or written by the userid under which your CGI script will be running: this is typically the userid under which the web server is running, or some explicitly specified userid for a web server’s suexec feature. Don’t try to give a CGI script a set-uid mode. This doesn’t work on most systems, and is a security liability as well.  Footnotes
1
Note that some recent versions of the HTML specification do state what order the field values should be supplied in, but knowing whether a request was received from a conforming browser, or even from a browser at all, is tedious and error-prone.


FieldStorage.getfirst(name, default=None)
This method always returns only one value associated with form field name. The method returns only the first value in case that more values were posted under such name. Please note that the order in which the values are received may vary from browser to browser and should not be counted on. 1 If no such form field or value exists then the method returns the value specified by the optional parameter default. This parameter defaults to None if not specified.


FieldStorage.getlist(name)
This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists.


cgi.parse(fp=None, environ=os.environ, keep_blank_values=False, strict_parsing=False, separator="&")
Parse a query in the environment or from a file (the file defaults to sys.stdin). The keep_blank_values, strict_parsing and separator parameters are passed to urllib.parse.parse_qs() unchanged.


cgi.parse_header(string)
Parse a MIME header (such as Content-Type) into a main value and a dictionary of parameters.


cgi.parse_multipart(fp, pdict, encoding="utf-8", errors="replace", separator="&")
Parse input of type multipart/form-data (for file uploads). Arguments are fp for the input file, pdict for a dictionary containing other parameters in the Content-Type header, and encoding, the request encoding. Returns a dictionary just like urllib.parse.parse_qs(): keys are the field names, each value is a list of values for that field. For non-file fields, the value is a list of strings. This is easy to use but not much good if you are expecting megabytes to be uploaded — in that case, use the FieldStorage class instead which is much more flexible.  Changed in version 3.7: Added the encoding and errors parameters. For non-file fields, the value is now a list of strings, not bytes.   Changed in version 3.9.2: Added the separator parameter.


cgi.print_directory()
Format the current directory in HTML.


cgi.print_environ()
Format the shell environment in HTML.


cgi.print_environ_usage()
Print a list of useful (used by CGI) environment variables in HTML.


cgi.print_form(form)
Format a form in HTML.


cgi.test()
Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.


cgitb — Traceback manager for CGI scripts Source code: Lib/cgitb.py The cgitb module provides a special exception handler for Python scripts. (Its name is a bit misleading. It was originally designed to display extensive traceback information in HTML for CGI scripts. It was later generalized to also display this information in plain text.) After this module is activated, if an uncaught exception occurs, a detailed, formatted report will be displayed. The report includes a traceback showing excerpts of the source code for each level, as well as the values of the arguments and local variables to currently running functions, to help you debug the problem. Optionally, you can save this information to a file instead of sending it to the browser. To enable this feature, simply add this to the top of your CGI script: import cgitb
cgitb.enable()
 The options to the enable() function control whether the report is displayed in the browser and whether the report is logged to a file for later analysis.
cgitb.enable(display=1, logdir=None, context=5, format="html")
This function causes the cgitb module to take over the interpreter’s default handling for exceptions by setting the value of sys.excepthook. The optional argument display defaults to 1 and can be set to 0 to suppress sending the traceback to the browser. If the argument logdir is present, the traceback reports are written to files. The value of logdir should be a directory where these files will be placed. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5. If the optional argument format is "html", the output is formatted as HTML. Any other value forces plain text output. The default value is "html".

cgitb.text(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as text and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5.

cgitb.html(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as HTML and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5.

cgitb.handler(info=None)
This function handles an exception using the default settings (that is, show a report in the browser, but don’t log to a file). This can be used when you’ve caught an exception and want to report it using cgitb. The optional info argument should be a 3-tuple containing an exception type, exception value, and traceback object, exactly like the tuple returned by sys.exc_info(). If the info argument is not supplied, the current exception is obtained from sys.exc_info().


cgitb.enable(display=1, logdir=None, context=5, format="html")
This function causes the cgitb module to take over the interpreter’s default handling for exceptions by setting the value of sys.excepthook. The optional argument display defaults to 1 and can be set to 0 to suppress sending the traceback to the browser. If the argument logdir is present, the traceback reports are written to files. The value of logdir should be a directory where these files will be placed. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5. If the optional argument format is "html", the output is formatted as HTML. Any other value forces plain text output. The default value is "html".


cgitb.handler(info=None)
This function handles an exception using the default settings (that is, show a report in the browser, but don’t log to a file). This can be used when you’ve caught an exception and want to report it using cgitb. The optional info argument should be a 3-tuple containing an exception type, exception value, and traceback object, exactly like the tuple returned by sys.exc_info(). If the info argument is not supplied, the current exception is obtained from sys.exc_info().


cgitb.html(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as HTML and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5.


cgitb.text(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as text and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5.


exception ChildProcessError
Raised when an operation on a child process failed. Corresponds to errno ECHILD.


chr(i)
Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord(). The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.