doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
class bdb.Bdb(skip=None) The Bdb class acts as a generic Python debugger base class. This class takes care of the details of the trace facility; a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example. The skip argument, if given, must be an iterable of glob-style module name patterns. The debugger will not step into frames that originate in a module that matches one of these patterns. Whether a frame is considered to originate in a certain module is determined by the __name__ in the frame globals. New in version 3.1: The skip argument. The following methods of Bdb normally don’t need to be overridden. canonic(filename) Auxiliary method for getting a filename in a canonical form, that is, as a case-normalized (on case-insensitive filesystems) absolute path, stripped of surrounding angle brackets. reset() Set the botframe, stopframe, returnframe and quitting attributes with values ready to start debugging. trace_dispatch(frame, event, arg) This function is installed as the trace function of debugged frames. Its return value is the new trace function (in most cases, that is, itself). The default implementation decides how to dispatch a frame, depending on the type of event (passed as a string) that is about to be executed. event can be one of the following: "line": A new line of code is going to be executed. "call": A function is about to be called, or another code block entered. "return": A function or other code block is about to return. "exception": An exception has occurred. "c_call": A C function is about to be called. "c_return": A C function has returned. "c_exception": A C function has raised an exception. For the Python events, specialized functions (see below) are called. For the C events, no action is taken. The arg parameter depends on the previous event. See the documentation for sys.settrace() for more information on the trace function. For more information on code and frame objects, refer to The standard type hierarchy. dispatch_line(frame) If the debugger should stop on the current line, invoke the user_line() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_line()). Return a reference to the trace_dispatch() method for further tracing in that scope. dispatch_call(frame, arg) If the debugger should stop on this function call, invoke the user_call() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_call()). Return a reference to the trace_dispatch() method for further tracing in that scope. dispatch_return(frame, arg) If the debugger should stop on this function return, invoke the user_return() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_return()). Return a reference to the trace_dispatch() method for further tracing in that scope. dispatch_exception(frame, arg) If the debugger should stop at this exception, invokes the user_exception() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_exception()). Return a reference to the trace_dispatch() method for further tracing in that scope. Normally derived classes don’t override the following methods, but they may if they want to redefine the definition of stopping and breakpoints. stop_here(frame) This method checks if the frame is somewhere below botframe in the call stack. botframe is the frame in which debugging started. break_here(frame) This method checks if there is a breakpoint in the filename and line belonging to frame or, at least, in the current function. If the breakpoint is a temporary one, this method deletes it. break_anywhere(frame) This method checks if there is a breakpoint in the filename of the current frame. Derived classes should override these methods to gain control over debugger operation. user_call(frame, argument_list) This method is called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function. user_line(frame) This method is called from dispatch_line() when either stop_here() or break_here() yields True. user_return(frame, return_value) This method is called from dispatch_return() when stop_here() yields True. user_exception(frame, exc_info) This method is called from dispatch_exception() when stop_here() yields True. do_clear(arg) Handle how a breakpoint must be removed when it is a temporary one. This method must be implemented by derived classes. Derived classes and clients can call the following methods to affect the stepping state. set_step() Stop after one line of code. set_next(frame) Stop on the next line in or below the given frame. set_return(frame) Stop when returning from the given frame. set_until(frame) Stop when the line with the line no greater than the current one is reached or when returning from current frame. set_trace([frame]) Start debugging from frame. If frame is not specified, debugging starts from caller’s frame. set_continue() Stop only at breakpoints or when finished. If there are no breakpoints, set the system trace function to None. set_quit() Set the quitting attribute to True. This raises BdbQuit in the next call to one of the dispatch_*() methods. Derived classes and clients can call the following methods to manipulate breakpoints. These methods return a string containing an error message if something went wrong, or None if all is well. set_break(filename, lineno, temporary=0, cond, funcname) Set a new breakpoint. If the lineno line doesn’t exist for the filename passed as argument, return an error message. The filename should be in canonical form, as described in the canonic() method. clear_break(filename, lineno) Delete the breakpoints in filename and lineno. If none were set, an error message is returned. clear_bpbynumber(arg) Delete the breakpoint which has the index arg in the Breakpoint.bpbynumber. If arg is not numeric or out of range, return an error message. clear_all_file_breaks(filename) Delete all breakpoints in filename. If none were set, an error message is returned. clear_all_breaks() Delete all existing breakpoints. get_bpbynumber(arg) Return a breakpoint specified by the given number. If arg is a string, it will be converted to a number. If arg is a non-numeric string, if the given breakpoint never existed or has been deleted, a ValueError is raised. New in version 3.2. get_break(filename, lineno) Check if there is a breakpoint for lineno of filename. get_breaks(filename, lineno) Return all breakpoints for lineno in filename, or an empty list if none are set. get_file_breaks(filename) Return all breakpoints in filename, or an empty list if none are set. get_all_breaks() Return all breakpoints that are set. Derived classes and clients can call the following methods to get a data structure representing a stack trace. get_stack(f, t) Get a list of records for a frame and all higher (calling) and lower frames, and the size of the higher part. format_stack_entry(frame_lineno, lprefix=': ') Return a string with information about a stack entry, identified by a (frame, lineno) tuple: The canonical form of the filename which contains the frame. The function name, or "<lambda>". The input arguments. The return value. The line of code (if it exists). The following two methods can be called by clients to use a debugger to debug a statement, given as a string. run(cmd, globals=None, locals=None) Debug a statement executed via the exec() function. globals defaults to __main__.__dict__, locals defaults to globals. runeval(expr, globals=None, locals=None) Debug an expression executed via the eval() function. globals and locals have the same meaning as in run(). runctx(cmd, globals, locals) For backwards compatibility. Calls the run() method. runcall(func, /, *args, **kwds) Debug a single function call, and return its result.
python.library.bdb#bdb.Bdb
break_anywhere(frame) This method checks if there is a breakpoint in the filename of the current frame.
python.library.bdb#bdb.Bdb.break_anywhere
break_here(frame) This method checks if there is a breakpoint in the filename and line belonging to frame or, at least, in the current function. If the breakpoint is a temporary one, this method deletes it.
python.library.bdb#bdb.Bdb.break_here
canonic(filename) Auxiliary method for getting a filename in a canonical form, that is, as a case-normalized (on case-insensitive filesystems) absolute path, stripped of surrounding angle brackets.
python.library.bdb#bdb.Bdb.canonic
clear_all_breaks() Delete all existing breakpoints.
python.library.bdb#bdb.Bdb.clear_all_breaks
clear_all_file_breaks(filename) Delete all breakpoints in filename. If none were set, an error message is returned.
python.library.bdb#bdb.Bdb.clear_all_file_breaks
clear_bpbynumber(arg) Delete the breakpoint which has the index arg in the Breakpoint.bpbynumber. If arg is not numeric or out of range, return an error message.
python.library.bdb#bdb.Bdb.clear_bpbynumber
clear_break(filename, lineno) Delete the breakpoints in filename and lineno. If none were set, an error message is returned.
python.library.bdb#bdb.Bdb.clear_break
dispatch_call(frame, arg) If the debugger should stop on this function call, invoke the user_call() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_call()). Return a reference to the trace_dispatch() method for further tracing in that scope.
python.library.bdb#bdb.Bdb.dispatch_call
dispatch_exception(frame, arg) If the debugger should stop at this exception, invokes the user_exception() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_exception()). Return a reference to the trace_dispatch() method for further tracing in that scope.
python.library.bdb#bdb.Bdb.dispatch_exception
dispatch_line(frame) If the debugger should stop on the current line, invoke the user_line() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_line()). Return a reference to the trace_dispatch() method for further tracing in that scope.
python.library.bdb#bdb.Bdb.dispatch_line
dispatch_return(frame, arg) If the debugger should stop on this function return, invoke the user_return() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_return()). Return a reference to the trace_dispatch() method for further tracing in that scope.
python.library.bdb#bdb.Bdb.dispatch_return
do_clear(arg) Handle how a breakpoint must be removed when it is a temporary one. This method must be implemented by derived classes.
python.library.bdb#bdb.Bdb.do_clear
format_stack_entry(frame_lineno, lprefix=': ') Return a string with information about a stack entry, identified by a (frame, lineno) tuple: The canonical form of the filename which contains the frame. The function name, or "<lambda>". The input arguments. The return value. The line of code (if it exists).
python.library.bdb#bdb.Bdb.format_stack_entry
get_all_breaks() Return all breakpoints that are set.
python.library.bdb#bdb.Bdb.get_all_breaks
get_bpbynumber(arg) Return a breakpoint specified by the given number. If arg is a string, it will be converted to a number. If arg is a non-numeric string, if the given breakpoint never existed or has been deleted, a ValueError is raised. New in version 3.2.
python.library.bdb#bdb.Bdb.get_bpbynumber
get_break(filename, lineno) Check if there is a breakpoint for lineno of filename.
python.library.bdb#bdb.Bdb.get_break
get_breaks(filename, lineno) Return all breakpoints for lineno in filename, or an empty list if none are set.
python.library.bdb#bdb.Bdb.get_breaks
get_file_breaks(filename) Return all breakpoints in filename, or an empty list if none are set.
python.library.bdb#bdb.Bdb.get_file_breaks
get_stack(f, t) Get a list of records for a frame and all higher (calling) and lower frames, and the size of the higher part.
python.library.bdb#bdb.Bdb.get_stack
reset() Set the botframe, stopframe, returnframe and quitting attributes with values ready to start debugging.
python.library.bdb#bdb.Bdb.reset
run(cmd, globals=None, locals=None) Debug a statement executed via the exec() function. globals defaults to __main__.__dict__, locals defaults to globals.
python.library.bdb#bdb.Bdb.run
runcall(func, /, *args, **kwds) Debug a single function call, and return its result.
python.library.bdb#bdb.Bdb.runcall
runctx(cmd, globals, locals) For backwards compatibility. Calls the run() method.
python.library.bdb#bdb.Bdb.runctx
runeval(expr, globals=None, locals=None) Debug an expression executed via the eval() function. globals and locals have the same meaning as in run().
python.library.bdb#bdb.Bdb.runeval
set_break(filename, lineno, temporary=0, cond, funcname) Set a new breakpoint. If the lineno line doesn’t exist for the filename passed as argument, return an error message. The filename should be in canonical form, as described in the canonic() method.
python.library.bdb#bdb.Bdb.set_break
set_continue() Stop only at breakpoints or when finished. If there are no breakpoints, set the system trace function to None.
python.library.bdb#bdb.Bdb.set_continue
set_next(frame) Stop on the next line in or below the given frame.
python.library.bdb#bdb.Bdb.set_next
set_quit() Set the quitting attribute to True. This raises BdbQuit in the next call to one of the dispatch_*() methods.
python.library.bdb#bdb.Bdb.set_quit
set_return(frame) Stop when returning from the given frame.
python.library.bdb#bdb.Bdb.set_return
set_step() Stop after one line of code.
python.library.bdb#bdb.Bdb.set_step
set_trace([frame]) Start debugging from frame. If frame is not specified, debugging starts from caller’s frame.
python.library.bdb#bdb.Bdb.set_trace
set_until(frame) Stop when the line with the line no greater than the current one is reached or when returning from current frame.
python.library.bdb#bdb.Bdb.set_until
stop_here(frame) This method checks if the frame is somewhere below botframe in the call stack. botframe is the frame in which debugging started.
python.library.bdb#bdb.Bdb.stop_here
trace_dispatch(frame, event, arg) This function is installed as the trace function of debugged frames. Its return value is the new trace function (in most cases, that is, itself). The default implementation decides how to dispatch a frame, depending on the type of event (passed as a string) that is about to be executed. event can be one of the following: "line": A new line of code is going to be executed. "call": A function is about to be called, or another code block entered. "return": A function or other code block is about to return. "exception": An exception has occurred. "c_call": A C function is about to be called. "c_return": A C function has returned. "c_exception": A C function has raised an exception. For the Python events, specialized functions (see below) are called. For the C events, no action is taken. The arg parameter depends on the previous event. See the documentation for sys.settrace() for more information on the trace function. For more information on code and frame objects, refer to The standard type hierarchy.
python.library.bdb#bdb.Bdb.trace_dispatch
user_call(frame, argument_list) This method is called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function.
python.library.bdb#bdb.Bdb.user_call
user_exception(frame, exc_info) This method is called from dispatch_exception() when stop_here() yields True.
python.library.bdb#bdb.Bdb.user_exception
user_line(frame) This method is called from dispatch_line() when either stop_here() or break_here() yields True.
python.library.bdb#bdb.Bdb.user_line
user_return(frame, return_value) This method is called from dispatch_return() when stop_here() yields True.
python.library.bdb#bdb.Bdb.user_return
exception bdb.BdbQuit Exception raised by the Bdb class for quitting the debugger.
python.library.bdb#bdb.BdbQuit
class bdb.Breakpoint(self, file, line, temporary=0, cond=None, funcname=None) This class implements temporary breakpoints, ignore counts, disabling and (re-)enabling, and conditionals. Breakpoints are indexed by number through a list called bpbynumber and by (file, line) pairs through bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line. When creating a breakpoint, its associated filename should be in canonical form. If a funcname is defined, a breakpoint hit will be counted when the first line of that function is executed. A conditional breakpoint always counts a hit. Breakpoint instances have the following methods: deleteMe() Delete the breakpoint from the list associated to a file/line. If it is the last breakpoint in that position, it also deletes the entry for the file/line. enable() Mark the breakpoint as enabled. disable() Mark the breakpoint as disabled. bpformat() Return a string with all the information about the breakpoint, nicely formatted: The breakpoint number. If it is temporary or not. Its file,line position. The condition that causes a break. If it must be ignored the next N times. The breakpoint hit count. New in version 3.2. bpprint(out=None) Print the output of bpformat() to the file out, or if it is None, to standard output.
python.library.bdb#bdb.Breakpoint
bpformat() Return a string with all the information about the breakpoint, nicely formatted: The breakpoint number. If it is temporary or not. Its file,line position. The condition that causes a break. If it must be ignored the next N times. The breakpoint hit count. New in version 3.2.
python.library.bdb#bdb.Breakpoint.bpformat
bpprint(out=None) Print the output of bpformat() to the file out, or if it is None, to standard output.
python.library.bdb#bdb.Breakpoint.bpprint
deleteMe() Delete the breakpoint from the list associated to a file/line. If it is the last breakpoint in that position, it also deletes the entry for the file/line.
python.library.bdb#bdb.Breakpoint.deleteMe
disable() Mark the breakpoint as disabled.
python.library.bdb#bdb.Breakpoint.disable
enable() Mark the breakpoint as enabled.
python.library.bdb#bdb.Breakpoint.enable
bdb.checkfuncname(b, frame) Check whether we should break here, depending on the way the breakpoint b was set. If it was set via line number, it checks if b.line is the same as the one in the frame also passed as argument. If the breakpoint was set via function name, we have to check we are in the right frame (the right function) and if we are in its first executable line.
python.library.bdb#bdb.checkfuncname
bdb.effective(file, line, frame) Determine if there is an effective (active) breakpoint at this line of code. Return a tuple of the breakpoint and a boolean that indicates if it is ok to delete a temporary breakpoint. Return (None, None) if there is no matching breakpoint.
python.library.bdb#bdb.effective
bdb.set_trace() Start debugging with a Bdb instance from caller’s frame.
python.library.bdb#bdb.set_trace
bin(x) Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples: >>> bin(3) '0b11' >>> bin(-10) '-0b1010' If prefix “0b” is desired or not, you can use either of the following ways. >>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110') See also format() for more information.
python.library.functions#bin
binascii — Convert between binary and ASCII The binascii module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like uu, base64, or binhex instead. The binascii module contains low-level functions written in C for greater speed that are used by the higher-level modules. Note a2b_* functions accept Unicode strings containing only ASCII characters. Other functions only accept bytes-like objects (such as bytes, bytearray and other objects that support the buffer protocol). Changed in version 3.3: ASCII-only unicode strings are now accepted by the a2b_* functions. The binascii module defines the following functions: binascii.a2b_uu(string) Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace. binascii.b2a_uu(data, *, backtick=False) Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by '`' instead of spaces. Changed in version 3.7: Added the backtick parameter. binascii.a2b_base64(string) Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time. binascii.b2a_base64(data, *, newline=True) Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548. Changed in version 3.6: Added the newline parameter. binascii.a2b_qp(data, header=False) Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces. binascii.b2a_qp(data, quotetabs=False, istext=True, header=False) Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream. binascii.a2b_hqx(string) Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. The string should contain a complete number of binary bytes, or (in case of the last portion of the binhex4 data) have the remaining bits zero. Deprecated since version 3.9. binascii.rledecode_hqx(data) Perform RLE-decompression on the data, as per the binhex4 standard. The algorithm uses 0x90 after a byte as a repeat indicator, followed by a count. A count of 0 specifies a byte value of 0x90. The routine returns the decompressed data, unless data input data ends in an orphaned repeat indicator, in which case the Incomplete exception is raised. Changed in version 3.2: Accept only bytestring or bytearray objects as input. Deprecated since version 3.9. binascii.rlecode_hqx(data) Perform binhex4 style RLE-compression on data and return the result. Deprecated since version 3.9. binascii.b2a_hqx(data) Perform hexbin4 binary-to-ASCII translation and return the resulting string. The argument should already be RLE-coded, and have a length divisible by 3 (except possibly the last fragment). Deprecated since version 3.9. binascii.crc_hqx(data, value) Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x16 + x12 + x5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format. binascii.crc32(data[, value]) Compute CRC-32, the 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows: print(binascii.crc32(b"hello world")) # Or, in two pieces: crc = binascii.crc32(b"hello") crc = binascii.crc32(b" world", crc) print('crc32 = {:#010x}'.format(crc)) Changed in version 3.0: The result is always unsigned. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff. binascii.b2a_hex(data[, sep[, bytes_per_sep=1]]) binascii.hexlify(data[, sep[, bytes_per_sep=1]]) Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data. Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method. If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value. >>> import binascii >>> binascii.b2a_hex(b'\xb9\x01\xef') b'b901ef' >>> binascii.hexlify(b'\xb9\x01\xef', '-') b'b9-01-ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2) b'b9_01ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2) b'b901 ef' Changed in version 3.8: The sep and bytes_per_sep parameters were added. binascii.a2b_hex(hexstr) binascii.unhexlify(hexstr) Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised. Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method. exception binascii.Error Exception raised on errors. These are usually programming errors. exception binascii.Incomplete Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again. See also Module base64 Support for RFC compliant base64-style encoding in base 16, 32, 64, and 85. Module binhex Support for the binhex format used on the Macintosh. Module uu Support for UU encoding used on Unix. Module quopri Support for quoted-printable encoding used in MIME email messages.
python.library.binascii
binascii.a2b_base64(string) Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time.
python.library.binascii#binascii.a2b_base64
binascii.a2b_hex(hexstr) binascii.unhexlify(hexstr) Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised. Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.
python.library.binascii#binascii.a2b_hex
binascii.a2b_hqx(string) Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. The string should contain a complete number of binary bytes, or (in case of the last portion of the binhex4 data) have the remaining bits zero. Deprecated since version 3.9.
python.library.binascii#binascii.a2b_hqx
binascii.a2b_qp(data, header=False) Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces.
python.library.binascii#binascii.a2b_qp
binascii.a2b_uu(string) Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.
python.library.binascii#binascii.a2b_uu
binascii.b2a_base64(data, *, newline=True) Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548. Changed in version 3.6: Added the newline parameter.
python.library.binascii#binascii.b2a_base64
binascii.b2a_hex(data[, sep[, bytes_per_sep=1]]) binascii.hexlify(data[, sep[, bytes_per_sep=1]]) Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data. Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method. If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value. >>> import binascii >>> binascii.b2a_hex(b'\xb9\x01\xef') b'b901ef' >>> binascii.hexlify(b'\xb9\x01\xef', '-') b'b9-01-ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2) b'b9_01ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2) b'b901 ef' Changed in version 3.8: The sep and bytes_per_sep parameters were added.
python.library.binascii#binascii.b2a_hex
binascii.b2a_hqx(data) Perform hexbin4 binary-to-ASCII translation and return the resulting string. The argument should already be RLE-coded, and have a length divisible by 3 (except possibly the last fragment). Deprecated since version 3.9.
python.library.binascii#binascii.b2a_hqx
binascii.b2a_qp(data, quotetabs=False, istext=True, header=False) Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream.
python.library.binascii#binascii.b2a_qp
binascii.b2a_uu(data, *, backtick=False) Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by '`' instead of spaces. Changed in version 3.7: Added the backtick parameter.
python.library.binascii#binascii.b2a_uu
binascii.crc32(data[, value]) Compute CRC-32, the 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows: print(binascii.crc32(b"hello world")) # Or, in two pieces: crc = binascii.crc32(b"hello") crc = binascii.crc32(b" world", crc) print('crc32 = {:#010x}'.format(crc)) Changed in version 3.0: The result is always unsigned. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.
python.library.binascii#binascii.crc32
binascii.crc_hqx(data, value) Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x16 + x12 + x5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format.
python.library.binascii#binascii.crc_hqx
exception binascii.Error Exception raised on errors. These are usually programming errors.
python.library.binascii#binascii.Error
binascii.b2a_hex(data[, sep[, bytes_per_sep=1]]) binascii.hexlify(data[, sep[, bytes_per_sep=1]]) Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data. Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method. If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value. >>> import binascii >>> binascii.b2a_hex(b'\xb9\x01\xef') b'b901ef' >>> binascii.hexlify(b'\xb9\x01\xef', '-') b'b9-01-ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2) b'b9_01ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2) b'b901 ef' Changed in version 3.8: The sep and bytes_per_sep parameters were added.
python.library.binascii#binascii.hexlify
exception binascii.Incomplete Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again.
python.library.binascii#binascii.Incomplete
binascii.rlecode_hqx(data) Perform binhex4 style RLE-compression on data and return the result. Deprecated since version 3.9.
python.library.binascii#binascii.rlecode_hqx
binascii.rledecode_hqx(data) Perform RLE-decompression on the data, as per the binhex4 standard. The algorithm uses 0x90 after a byte as a repeat indicator, followed by a count. A count of 0 specifies a byte value of 0x90. The routine returns the decompressed data, unless data input data ends in an orphaned repeat indicator, in which case the Incomplete exception is raised. Changed in version 3.2: Accept only bytestring or bytearray objects as input. Deprecated since version 3.9.
python.library.binascii#binascii.rledecode_hqx
binascii.a2b_hex(hexstr) binascii.unhexlify(hexstr) Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised. Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.
python.library.binascii#binascii.unhexlify
binhex — Encode and decode binhex4 files Source code: Lib/binhex.py Deprecated since version 3.9. This module encodes and decodes files in binhex4 format, a format allowing representation of Macintosh files in ASCII. Only the data fork is handled. The binhex module defines the following functions: binhex.binhex(input, output) Convert a binary file with filename input to binhex file output. The output parameter can either be a filename or a file-like object (any object supporting a write() and close() method). binhex.hexbin(input, output) Decode a binhex file input. input may be a filename or a file-like object supporting read() and close() methods. The resulting file is written to a file named output, unless the argument is None in which case the output filename is read from the binhex file. The following exception is also defined: exception binhex.Error Exception raised when something can’t be encoded using the binhex format (for example, a filename is too long to fit in the filename field), or when input is not properly encoded binhex data. See also Module binascii Support module containing ASCII-to-binary and binary-to-ASCII conversions. Notes There is an alternative, more powerful interface to the coder and decoder, see the source for details. If you code or decode textfiles on non-Macintosh platforms they will still use the old Macintosh newline convention (carriage-return as end of line).
python.library.binhex
binhex.binhex(input, output) Convert a binary file with filename input to binhex file output. The output parameter can either be a filename or a file-like object (any object supporting a write() and close() method).
python.library.binhex#binhex.binhex
exception binhex.Error Exception raised when something can’t be encoded using the binhex format (for example, a filename is too long to fit in the filename field), or when input is not properly encoded binhex data.
python.library.binhex#binhex.Error
binhex.hexbin(input, output) Decode a binhex file input. input may be a filename or a file-like object supporting read() and close() methods. The resulting file is written to a file named output, unless the argument is None in which case the output filename is read from the binhex file.
python.library.binhex#binhex.hexbin
bisect — Array bisection algorithm Source code: Lib/bisect.py This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!). The following functions are provided: bisect.bisect_left(a, x, lo=0, hi=len(a)) Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted. The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side. bisect.bisect_right(a, x, lo=0, hi=len(a)) bisect.bisect(a, x, lo=0, hi=len(a)) Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a. The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side. bisect.insort_left(a, x, lo=0, hi=len(a)) Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step. bisect.insort_right(a, x, lo=0, hi=len(a)) bisect.insort(a, x, lo=0, hi=len(a)) Similar to insort_left(), but inserting x in a after any existing entries of x. See also SortedCollection recipe that uses bisect to build a full-featured collection class with straight-forward search methods and support for a key-function. The keys are precomputed to save unnecessary calls to the key function during searches. Searching Sorted Lists The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists: def index(a, x): 'Locate the leftmost value exactly equal to x' i = bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError def find_lt(a, x): 'Find rightmost value less than x' i = bisect_left(a, x) if i: return a[i-1] raise ValueError def find_le(a, x): 'Find rightmost value less than or equal to x' i = bisect_right(a, x) if i: return a[i-1] raise ValueError def find_gt(a, x): 'Find leftmost value greater than x' i = bisect_right(a, x) if i != len(a): return a[i] raise ValueError def find_ge(a, x): 'Find leftmost item greater than or equal to x' i = bisect_left(a, x) if i != len(a): return a[i] raise ValueError Other Examples The bisect() function can be useful for numeric table lookups. This example uses bisect() to look up a letter grade for an exam score (say) based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is a ‘B’, and so on: >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): ... i = bisect(breakpoints, score) ... return grades[i] ... >>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] ['F', 'A', 'C', 'C', 'B', 'A', 'A'] Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups). Instead, it is better to search a list of precomputed keys to find the index of the record in question: >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] >>> data.sort(key=lambda r: r[1]) >>> keys = [r[1] for r in data] # precomputed list of keys >>> data[bisect_left(keys, 0)] ('black', 0) >>> data[bisect_left(keys, 1)] ('blue', 1) >>> data[bisect_left(keys, 5)] ('red', 5) >>> data[bisect_left(keys, 8)] ('yellow', 8)
python.library.bisect
bisect.bisect_right(a, x, lo=0, hi=len(a)) bisect.bisect(a, x, lo=0, hi=len(a)) Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a. The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side.
python.library.bisect#bisect.bisect
bisect.bisect_left(a, x, lo=0, hi=len(a)) Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted. The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side.
python.library.bisect#bisect.bisect_left
bisect.bisect_right(a, x, lo=0, hi=len(a)) bisect.bisect(a, x, lo=0, hi=len(a)) Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a. The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side.
python.library.bisect#bisect.bisect_right
bisect.insort_right(a, x, lo=0, hi=len(a)) bisect.insort(a, x, lo=0, hi=len(a)) Similar to insort_left(), but inserting x in a after any existing entries of x.
python.library.bisect#bisect.insort
bisect.insort_left(a, x, lo=0, hi=len(a)) Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.
python.library.bisect#bisect.insort_left
bisect.insort_right(a, x, lo=0, hi=len(a)) bisect.insort(a, x, lo=0, hi=len(a)) Similar to insort_left(), but inserting x in a after any existing entries of x.
python.library.bisect#bisect.insort_right
exception BlockingIOError Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to errno EAGAIN, EALREADY, EWOULDBLOCK and EINPROGRESS. In addition to those of OSError, BlockingIOError can have one more attribute: characters_written An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module.
python.library.exceptions#BlockingIOError
characters_written An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module.
python.library.exceptions#BlockingIOError.characters_written
class bool([x]) Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values). Changed in version 3.7: x is now a positional-only parameter.
python.library.functions#bool
breakpoint(*args, **kws) This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice. Raises an auditing event builtins.breakpoint with argument breakpointhook. New in version 3.7.
python.library.functions#breakpoint
exception BrokenPipeError A subclass of ConnectionError, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds to errno EPIPE and ESHUTDOWN.
python.library.exceptions#BrokenPipeError
exception BufferError Raised when a buffer related operation cannot be performed.
python.library.exceptions#BufferError
builtins — Built-in objects This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation. This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly: import builtins def open(path): f = builtins.open(path, 'r') return UpperCaser(f) class UpperCaser: '''Wrapper around a file that converts output to upper-case.''' def __init__(self, f): self._f = f def read(self, count=-1): return self._f.read(count).upper() # ... As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
python.library.builtins
class bytearray([source[, encoding[, errors]]]) Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations. The optional source parameter can be used to initialize the array in a few different ways: If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode(). If it is an integer, the array will have that size and will be initialized with null bytes. If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array. If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array. Without an argument, an array of size 0 is created. See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.
python.library.functions#bytearray
class bytearray([source[, encoding[, errors]]]) There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor: Creating an empty instance: bytearray() Creating a zero-filled instance with a given length: bytearray(10) From an iterable of integers: bytearray(range(20)) Copying existing binary data via the buffer protocol: bytearray(b'Hi!') As bytearray objects are mutable, they support the mutable sequence operations in addition to the common bytes and bytearray operations described in Bytes and Bytearray Operations. Also see the bytearray built-in. Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format: classmethod fromhex(string) This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytearray.fromhex('2Ef0 F1f2 ') bytearray(b'.\xf0\xf1\xf2') Changed in version 3.7: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces. A reverse conversion function exists to transform a bytearray object into its hexadecimal representation. hex([sep[, bytes_per_sep]]) Return a string object containing two hexadecimal digits for each byte in the instance. >>> bytearray(b'\xf0\xf1\xf2').hex() 'f0f1f2' New in version 3.5. Changed in version 3.8: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
python.library.stdtypes#bytearray
bytes.capitalize() bytearray.capitalize() Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
python.library.stdtypes#bytearray.capitalize
bytes.center(width[, fillbyte]) bytearray.center(width[, fillbyte]) Return a copy of the object centered 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.
python.library.stdtypes#bytearray.center
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.
python.library.stdtypes#bytearray.count
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.
python.library.stdtypes#bytearray.decode
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.
python.library.stdtypes#bytearray.endswith
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.
python.library.stdtypes#bytearray.expandtabs
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.
python.library.stdtypes#bytearray.find
classmethod fromhex(string) This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytearray.fromhex('2Ef0 F1f2 ') bytearray(b'.\xf0\xf1\xf2') Changed in version 3.7: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces.
python.library.stdtypes#bytearray.fromhex
hex([sep[, bytes_per_sep]]) Return a string object containing two hexadecimal digits for each byte in the instance. >>> bytearray(b'\xf0\xf1\xf2').hex() 'f0f1f2' New in version 3.5. Changed in version 3.8: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
python.library.stdtypes#bytearray.hex
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.
python.library.stdtypes#bytearray.index
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
python.library.stdtypes#bytearray.isalnum