doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
token.DEDENT
python.library.token#token.DEDENT
token.DOT Token value for ".".
python.library.token#token.DOT
token.DOUBLESLASH Token value for "//".
python.library.token#token.DOUBLESLASH
token.DOUBLESLASHEQUAL Token value for "//=".
python.library.token#token.DOUBLESLASHEQUAL
token.DOUBLESTAR Token value for "**".
python.library.token#token.DOUBLESTAR
token.DOUBLESTAREQUAL Token value for "**=".
python.library.token#token.DOUBLESTAREQUAL
token.ELLIPSIS Token value for "...".
python.library.token#token.ELLIPSIS
token.ENCODING Token value that indicates the encoding used to decode the source bytes into text. The first token returned by tokenize.tokenize() will always be an ENCODING token.
python.library.token#token.ENCODING
token.ENDMARKER
python.library.token#token.ENDMARKER
token.EQEQUAL Token value for "==".
python.library.token#token.EQEQUAL
token.EQUAL Token value for "=".
python.library.token#token.EQUAL
token.ERRORTOKEN
python.library.token#token.ERRORTOKEN
token.GREATER Token value for ">".
python.library.token#token.GREATER
token.GREATEREQUAL Token value for ">=".
python.library.token#token.GREATEREQUAL
token.INDENT
python.library.token#token.INDENT
token.ISEOF(x) Return True if x is the marker indicating the end of input.
python.library.token#token.ISEOF
token.ISNONTERMINAL(x) Return True for non-terminal token values.
python.library.token#token.ISNONTERMINAL
token.ISTERMINAL(x) Return True for terminal token values.
python.library.token#token.ISTERMINAL
token.LBRACE Token value for "{".
python.library.token#token.LBRACE
token.LEFTSHIFT Token value for "<<".
python.library.token#token.LEFTSHIFT
token.LEFTSHIFTEQUAL Token value for "<<=".
python.library.token#token.LEFTSHIFTEQUAL
token.LESS Token value for "<".
python.library.token#token.LESS
token.LESSEQUAL Token value for "<=".
python.library.token#token.LESSEQUAL
token.LPAR Token value for "(".
python.library.token#token.LPAR
token.LSQB Token value for "[".
python.library.token#token.LSQB
token.MINEQUAL Token value for "-=".
python.library.token#token.MINEQUAL
token.MINUS Token value for "-".
python.library.token#token.MINUS
token.NAME
python.library.token#token.NAME
token.NEWLINE
python.library.token#token.NEWLINE
token.NL Token value used to indicate a non-terminating newline. The NEWLINE token indicates the end of a logical line of Python code; NL tokens are generated when a logical line of code is continued over multiple physical lines.
python.library.token#token.NL
token.NOTEQUAL Token value for "!=".
python.library.token#token.NOTEQUAL
token.NT_OFFSET
python.library.token#token.NT_OFFSET
token.NUMBER
python.library.token#token.NUMBER
token.N_TOKENS
python.library.token#token.N_TOKENS
token.OP
python.library.token#token.OP
token.PERCENT Token value for "%".
python.library.token#token.PERCENT
token.PERCENTEQUAL Token value for "%=".
python.library.token#token.PERCENTEQUAL
token.PLUS Token value for "+".
python.library.token#token.PLUS
token.PLUSEQUAL Token value for "+=".
python.library.token#token.PLUSEQUAL
token.RARROW Token value for "->".
python.library.token#token.RARROW
token.RBRACE Token value for "}".
python.library.token#token.RBRACE
token.RIGHTSHIFT Token value for ">>".
python.library.token#token.RIGHTSHIFT
token.RIGHTSHIFTEQUAL Token value for ">>=".
python.library.token#token.RIGHTSHIFTEQUAL
token.RPAR Token value for ")".
python.library.token#token.RPAR
token.RSQB Token value for "]".
python.library.token#token.RSQB
token.SEMI Token value for ";".
python.library.token#token.SEMI
token.SLASH Token value for "/".
python.library.token#token.SLASH
token.SLASHEQUAL Token value for "/=".
python.library.token#token.SLASHEQUAL
token.STAR Token value for "*".
python.library.token#token.STAR
token.STAREQUAL Token value for "*=".
python.library.token#token.STAREQUAL
token.STRING
python.library.token#token.STRING
token.TILDE Token value for "~".
python.library.token#token.TILDE
token.tok_name Dictionary mapping the numeric values of the constants defined in this module back to name strings, allowing more human-readable representation of parse trees to be generated.
python.library.token#token.tok_name
token.TYPE_COMMENT
python.library.token#token.TYPE_COMMENT
token.TYPE_IGNORE
python.library.token#token.TYPE_IGNORE
token.VBAR Token value for "|".
python.library.token#token.VBAR
token.VBAREQUAL Token value for "|=".
python.library.token#token.VBAREQUAL
tokenize — Tokenizer for Python source Source code: Lib/tokenize.py The tokenize module provides a lexical scanner for Python source code, implemented in Python. The scanner in this module returns comments as tokens as well, making it useful for implementing “pretty-printers”, including colorizers for on-screen displays. To simplify token stream handling, all operator and delimiter tokens and Ellipsis are returned using the generic OP token type. The exact type can be determined by checking the exact_type property on the named tuple returned from tokenize.tokenize(). Tokenizing Input The primary entry point is a generator: tokenize.tokenize(readline) The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the io.IOBase.readline() method of file objects. Each call to the function should return one line of input as bytes. The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the physical line. The 5 tuple is returned as a named tuple with the field names: type string start end line. The returned named tuple has an additional property named exact_type that contains the exact operator type for OP tokens. For all other token types exact_type equals the named tuple type field. Changed in version 3.1: Added support for named tuples. Changed in version 3.3: Added support for exact_type. tokenize() determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to PEP 263. tokenize.generate_tokens(readline) Tokenize a source reading unicode strings instead of bytes. Like tokenize(), the readline argument is a callable returning a single line of input. However, generate_tokens() expects readline to return a str object rather than bytes. The result is an iterator yielding named tuples, exactly like tokenize(). It does not yield an ENCODING token. All constants from the token module are also exported from tokenize. Another function is provided to reverse the tokenization process. This is useful for creating tools that tokenize a script, modify the token stream, and write back the modified script. tokenize.untokenize(iterable) Converts tokens back into Python source code. The iterable must return sequences with at least two elements, the token type and the token string. Any additional sequence elements are ignored. The reconstructed script is returned as a single string. The result is guaranteed to tokenize back to match the input so that the conversion is lossless and round-trips are assured. The guarantee applies only to the token type and token string as the spacing between tokens (column positions) may change. It returns bytes, encoded using the ENCODING token, which is the first token sequence output by tokenize(). If there is no encoding token in the input, it returns a str instead. tokenize() needs to detect the encoding of source files it tokenizes. The function it uses to do this is available: tokenize.detect_encoding(readline) The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (not decoded from bytes) it has read in. It detects the encoding from the presence of a UTF-8 BOM or an encoding cookie as specified in PEP 263. If both a BOM and a cookie are present, but disagree, a SyntaxError will be raised. Note that if the BOM is found, 'utf-8-sig' will be returned as an encoding. If no encoding is specified, then the default of 'utf-8' will be returned. Use open() to open Python source files: it uses detect_encoding() to detect the file encoding. tokenize.open(filename) Open a file in read only mode using the encoding detected by detect_encoding(). New in version 3.2. exception tokenize.TokenError Raised when either a docstring or expression that may be split over several lines is not completed anywhere in the file, for example: """Beginning of docstring or: [1, 2, 3 Note that unclosed single-quoted strings do not cause an error to be raised. They are tokenized as ERRORTOKEN, followed by the tokenization of their contents. Command-Line Usage New in version 3.3. The tokenize module can be executed as a script from the command line. It is as simple as: python -m tokenize [-e] [filename.py] The following options are accepted: -h, --help show this help message and exit -e, --exact display token names using the exact type If filename.py is specified its contents are tokenized to stdout. Otherwise, tokenization is performed on stdin. Examples Example of a script rewriter that transforms float literals into Decimal objects: from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP from io import BytesIO def decistmt(s): """Substitute Decimals for floats in a string of statements. >>> from decimal import Decimal >>> s = 'print(+21.3e-5*-.1234/81.7)' >>> decistmt(s) "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))" The format of the exponent is inherited from the platform C library. Known cases are "e-007" (Windows) and "e-07" (not Windows). Since we're only showing 12 digits, and the 13th isn't close to 5, the rest of the output should be platform-independent. >>> exec(s) #doctest: +ELLIPSIS -3.21716034272e-0...7 Output from calculations with Decimal should be identical across all platforms. >>> exec(decistmt(s)) -3.217160342717258261933904529E-7 """ result = [] g = tokenize(BytesIO(s.encode('utf-8')).readline) # tokenize the string for toknum, tokval, _, _, _ in g: if toknum == NUMBER and '.' in tokval: # replace NUMBER tokens result.extend([ (NAME, 'Decimal'), (OP, '('), (STRING, repr(tokval)), (OP, ')') ]) else: result.append((toknum, tokval)) return untokenize(result).decode('utf-8') Example of tokenizing from the command line. The script: def say_hello(): print("Hello, World!") say_hello() will be tokenized to the following output where the first column is the range of the line/column coordinates where the token is found, the second column is the name of the token, and the final column is the value of the token (if any) $ python -m tokenize hello.py 0,0-0,0: ENCODING 'utf-8' 1,0-1,3: NAME 'def' 1,4-1,13: NAME 'say_hello' 1,13-1,14: OP '(' 1,14-1,15: OP ')' 1,15-1,16: OP ':' 1,16-1,17: NEWLINE '\n' 2,0-2,4: INDENT ' ' 2,4-2,9: NAME 'print' 2,9-2,10: OP '(' 2,10-2,25: STRING '"Hello, World!"' 2,25-2,26: OP ')' 2,26-2,27: NEWLINE '\n' 3,0-3,1: NL '\n' 4,0-4,0: DEDENT '' 4,0-4,9: NAME 'say_hello' 4,9-4,10: OP '(' 4,10-4,11: OP ')' 4,11-4,12: NEWLINE '\n' 5,0-5,0: ENDMARKER '' The exact token type names can be displayed using the -e option: $ python -m tokenize -e hello.py 0,0-0,0: ENCODING 'utf-8' 1,0-1,3: NAME 'def' 1,4-1,13: NAME 'say_hello' 1,13-1,14: LPAR '(' 1,14-1,15: RPAR ')' 1,15-1,16: COLON ':' 1,16-1,17: NEWLINE '\n' 2,0-2,4: INDENT ' ' 2,4-2,9: NAME 'print' 2,9-2,10: LPAR '(' 2,10-2,25: STRING '"Hello, World!"' 2,25-2,26: RPAR ')' 2,26-2,27: NEWLINE '\n' 3,0-3,1: NL '\n' 4,0-4,0: DEDENT '' 4,0-4,9: NAME 'say_hello' 4,9-4,10: LPAR '(' 4,10-4,11: RPAR ')' 4,11-4,12: NEWLINE '\n' 5,0-5,0: ENDMARKER '' Example of tokenizing a file programmatically, reading unicode strings instead of bytes with generate_tokens(): import tokenize with tokenize.open('hello.py') as f: tokens = tokenize.generate_tokens(f.readline) for token in tokens: print(token) Or reading bytes directly with tokenize(): import tokenize with open('hello.py', 'rb') as f: tokens = tokenize.tokenize(f.readline) for token in tokens: print(token)
python.library.tokenize
tokenize.detect_encoding(readline) The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (not decoded from bytes) it has read in. It detects the encoding from the presence of a UTF-8 BOM or an encoding cookie as specified in PEP 263. If both a BOM and a cookie are present, but disagree, a SyntaxError will be raised. Note that if the BOM is found, 'utf-8-sig' will be returned as an encoding. If no encoding is specified, then the default of 'utf-8' will be returned. Use open() to open Python source files: it uses detect_encoding() to detect the file encoding.
python.library.tokenize#tokenize.detect_encoding
tokenize.generate_tokens(readline) Tokenize a source reading unicode strings instead of bytes. Like tokenize(), the readline argument is a callable returning a single line of input. However, generate_tokens() expects readline to return a str object rather than bytes. The result is an iterator yielding named tuples, exactly like tokenize(). It does not yield an ENCODING token.
python.library.tokenize#tokenize.generate_tokens
tokenize.open(filename) Open a file in read only mode using the encoding detected by detect_encoding(). New in version 3.2.
python.library.tokenize#tokenize.open
exception tokenize.TokenError Raised when either a docstring or expression that may be split over several lines is not completed anywhere in the file, for example: """Beginning of docstring or: [1, 2, 3
python.library.tokenize#tokenize.TokenError
tokenize.tokenize(readline) The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the io.IOBase.readline() method of file objects. Each call to the function should return one line of input as bytes. The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the physical line. The 5 tuple is returned as a named tuple with the field names: type string start end line. The returned named tuple has an additional property named exact_type that contains the exact operator type for OP tokens. For all other token types exact_type equals the named tuple type field. Changed in version 3.1: Added support for named tuples. Changed in version 3.3: Added support for exact_type. tokenize() determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to PEP 263.
python.library.tokenize#tokenize.tokenize
tokenize.untokenize(iterable) Converts tokens back into Python source code. The iterable must return sequences with at least two elements, the token type and the token string. Any additional sequence elements are ignored. The reconstructed script is returned as a single string. The result is guaranteed to tokenize back to match the input so that the conversion is lossless and round-trips are assured. The guarantee applies only to the token type and token string as the spacing between tokens (column positions) may change. It returns bytes, encoded using the ENCODING token, which is the first token sequence output by tokenize(). If there is no encoding token in the input, it returns a str instead.
python.library.tokenize#tokenize.untokenize
trace — Trace or track Python statement execution Source code: Lib/trace.py The trace module allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line. See also Coverage.py A popular third-party coverage tool that provides HTML output along with advanced features such as branch coverage. Command-Line Usage The trace module can be invoked from the command line. It can be as simple as python -m trace --count -C . somefile.py ... The above will execute somefile.py and generate annotated listings of all Python modules imported during the execution into the current directory. --help Display usage and exit. --version Display the version of the module and exit. New in version 3.8: Added --module option that allows to run an executable module. Main options At least one of the following options must be specified when invoking trace. The --listfuncs option is mutually exclusive with the --trace and --count options. When --listfuncs is provided, neither --count nor --trace are accepted, and vice versa. -c, --count Produce a set of annotated listing files upon program completion that shows how many times each statement was executed. See also --coverdir, --file and --no-report below. -t, --trace Display lines as they are executed. -l, --listfuncs Display the functions executed by running the program. -r, --report Produce an annotated list from an earlier program run that used the --count and --file option. This does not execute any code. -T, --trackcalls Display the calling relationships exposed by running the program. Modifiers -f, --file=<file> Name of a file to accumulate counts over several tracing runs. Should be used with the --count option. -C, --coverdir=<dir> Directory where the report files go. The coverage report for package.module is written to file dir/package/module.cover. -m, --missing When generating annotated listings, mark lines which were not executed with >>>>>>. -s, --summary When using --count or --report, write a brief summary to stdout for each file processed. -R, --no-report Do not generate annotated listings. This is useful if you intend to make several runs with --count, and then produce a single set of annotated listings at the end. -g, --timing Prefix each line with the time since the program started. Only used while tracing. Filters These options may be repeated multiple times. --ignore-module=<mod> Ignore each of the given module names and its submodules (if it is a package). The argument can be a list of names separated by a comma. --ignore-dir=<dir> Ignore all modules and packages in the named directory and subdirectories. The argument can be a list of directories separated by os.pathsep. Programmatic Interface class trace.Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False) Create an object to trace execution of a single statement or expression. All parameters are optional. count enables counting of line numbers. trace enables line execution tracing. countfuncs enables listing of the functions called during the run. countcallers enables call relationship tracking. ignoremods is a list of modules or packages to ignore. ignoredirs is a list of directories whose modules or packages should be ignored. infile is the name of the file from which to read stored count information. outfile is the name of the file in which to write updated count information. timing enables a timestamp relative to when tracing was started to be displayed. run(cmd) Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec(). runctx(cmd, globals=None, locals=None) Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries. runfunc(func, /, *args, **kwds) Call func with the given arguments under control of the Trace object with the current tracing parameters. results() Return a CoverageResults object that contains the cumulative results of all previous calls to run, runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results. class trace.CoverageResults A container for coverage results, created by Trace.results(). Should not be created directly by the user. update(other) Merge in data from another CoverageResults object. write_results(show_missing=True, summary=False, coverdir=None) Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None, the results for each source file are placed in its directory. A simple example demonstrating the use of the programmatic interface: import sys import trace # create a Trace object, telling it what to ignore, and whether to # do tracing or line-counting or both. tracer = trace.Trace( ignoredirs=[sys.prefix, sys.exec_prefix], trace=0, count=1) # run the new command using the given tracer tracer.run('main()') # make a report, placing output in the current directory r = tracer.results() r.write_results(show_missing=True, coverdir=".")
python.library.trace
class trace.CoverageResults A container for coverage results, created by Trace.results(). Should not be created directly by the user. update(other) Merge in data from another CoverageResults object. write_results(show_missing=True, summary=False, coverdir=None) Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None, the results for each source file are placed in its directory.
python.library.trace#trace.CoverageResults
update(other) Merge in data from another CoverageResults object.
python.library.trace#trace.CoverageResults.update
write_results(show_missing=True, summary=False, coverdir=None) Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None, the results for each source file are placed in its directory.
python.library.trace#trace.CoverageResults.write_results
class trace.Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False) Create an object to trace execution of a single statement or expression. All parameters are optional. count enables counting of line numbers. trace enables line execution tracing. countfuncs enables listing of the functions called during the run. countcallers enables call relationship tracking. ignoremods is a list of modules or packages to ignore. ignoredirs is a list of directories whose modules or packages should be ignored. infile is the name of the file from which to read stored count information. outfile is the name of the file in which to write updated count information. timing enables a timestamp relative to when tracing was started to be displayed. run(cmd) Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec(). runctx(cmd, globals=None, locals=None) Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries. runfunc(func, /, *args, **kwds) Call func with the given arguments under control of the Trace object with the current tracing parameters. results() Return a CoverageResults object that contains the cumulative results of all previous calls to run, runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results.
python.library.trace#trace.Trace
results() Return a CoverageResults object that contains the cumulative results of all previous calls to run, runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results.
python.library.trace#trace.Trace.results
run(cmd) Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec().
python.library.trace#trace.Trace.run
runctx(cmd, globals=None, locals=None) Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries.
python.library.trace#trace.Trace.runctx
runfunc(func, /, *args, **kwds) Call func with the given arguments under control of the Trace object with the current tracing parameters.
python.library.trace#trace.Trace.runfunc
traceback — Print or retrieve a stack traceback Source code: Lib/traceback.py This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter. The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info(). The module defines the following functions: traceback.print_tb(tb, limit=None, file=None) Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output. Changed in version 3.5: Added negative limit support. traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True) Print exception information and stack trace entries from traceback object tb to file. This differs from print_tb() in the following ways: if tb is not None, it prints a header Traceback (most recent call last): it prints the exception etype and value after the stack trace if type(value) is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error. The optional limit argument has the same meaning as for print_tb(). If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception. Changed in version 3.5: The etype argument is ignored and inferred from the type of value. traceback.print_exc(limit=None, file=None, chain=True) This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain). traceback.print_last(limit=None, file=None, chain=True) This is a shorthand for print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain). In general it will work only after an exception has reached an interactive prompt (see sys.last_type). traceback.print_stack(f=None, limit=None, file=None) Print up to limit stack trace entries (starting from the invocation point) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start. The optional file argument has the same meaning as for print_tb(). Changed in version 3.5: Added negative limit support. traceback.extract_tb(tb, limit=None) Return a StackSummary object representing a list of “pre-processed” stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. The optional limit argument has the same meaning as for print_tb(). A “pre-processed” stack trace entry is a FrameSummary object containing attributes filename, lineno, name, and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None. traceback.extract_stack(f=None, limit=None) Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional f and limit arguments have the same meaning as for print_stack(). traceback.format_list(extracted_list) Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. traceback.format_exception_only(etype, value) Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. traceback.format_exception(etype, value, tb, limit=None, chain=True) Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception(). Changed in version 3.5: The etype argument is ignored and inferred from the type of value. traceback.format_exc(limit=None, chain=True) This is like print_exc(limit) but returns a string instead of printing to a file. traceback.format_tb(tb, limit=None) A shorthand for format_list(extract_tb(tb, limit)). traceback.format_stack(f=None, limit=None) A shorthand for format_list(extract_stack(f, limit)). traceback.clear_frames(tb) Clears the local variables of all the stack frames in a traceback tb by calling the clear() method of each frame object. New in version 3.4. traceback.walk_stack(f) Walk a stack following f.f_back from the given frame, yielding the frame and line number for each frame. If f is None, the current stack is used. This helper is used with StackSummary.extract(). New in version 3.5. traceback.walk_tb(tb) Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract(). New in version 3.5. The module also defines the following classes: TracebackException Objects New in version 3.5. TracebackException objects are created from actual exceptions to capture data for later printing in a lightweight fashion. class traceback.TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False) Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class. Note that when locals are captured, they are also shown in the traceback. __cause__ A TracebackException of the original __cause__. __context__ A TracebackException of the original __context__. __suppress_context__ The __suppress_context__ value from the original exception. stack A StackSummary representing the traceback. exc_type The class of the original traceback. filename For syntax errors - the file name where the error occurred. lineno For syntax errors - the line number where the error occurred. text For syntax errors - the text where the error occurred. offset For syntax errors - the offset into the text where the error occurred. msg For syntax errors - the compiler error message. classmethod from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False) Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class. Note that when locals are captured, they are also shown in the traceback. format(*, chain=True) Format the exception. If chain is not True, __cause__ and __context__ will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output. format_exception_only() Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. StackSummary Objects New in version 3.5. StackSummary objects represent a call stack ready for formatting. class traceback.StackSummary classmethod extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False) Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb()). If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False, the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations. classmethod from_list(a_list) Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements. format() Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines. For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions. Changed in version 3.6: Long sequences of repeated frames are now abbreviated. FrameSummary Objects New in version 3.5. FrameSummary objects represent a single frame in a traceback. class traceback.FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None) Represent a single frame in the traceback or stack that is being formatted or printed. It may optionally have a stringified version of the frames locals included in it. If lookup_line is False, the source code is not looked up until the FrameSummary has the line attribute accessed (which also happens when casting it to a tuple). line may be directly provided, and will prevent line lookups happening at all. locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display. Traceback Examples This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. import sys, traceback def run_user_code(envdir): source = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = {} while True: run_user_code(envdir) The following example demonstrates the different ways to print and format the exception and traceback: import sys, traceback def lumberjack(): bright_side_of_death() def bright_side_of_death(): return tuple()[0] try: lumberjack() except IndexError: exc_type, exc_value, exc_traceback = sys.exc_info() print("*** print_tb:") traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print("*** print_exception:") # exc_type below is ignored on 3.5 and later traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print("*** print_exc:") traceback.print_exc(limit=2, file=sys.stdout) print("*** format_exc, first and last line:") formatted_lines = traceback.format_exc().splitlines() print(formatted_lines[0]) print(formatted_lines[-1]) print("*** format_exception:") # exc_type below is ignored on 3.5 and later print(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) print("*** extract_tb:") print(repr(traceback.extract_tb(exc_traceback))) print("*** format_tb:") print(repr(traceback.format_tb(exc_traceback))) print("*** tb_lineno:", exc_traceback.tb_lineno) The output for the example would look similar to this: *** print_tb: File "<doctest...>", line 10, in <module> lumberjack() *** print_exception: Traceback (most recent call last): File "<doctest...>", line 10, in <module> lumberjack() File "<doctest...>", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** print_exc: Traceback (most recent call last): File "<doctest...>", line 10, in <module> lumberjack() File "<doctest...>", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** format_exc, first and last line: Traceback (most recent call last): IndexError: tuple index out of range *** format_exception: ['Traceback (most recent call last):\n', ' File "<doctest...>", line 10, in <module>\n lumberjack()\n', ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n', ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n', 'IndexError: tuple index out of range\n'] *** extract_tb: [<FrameSummary file <doctest...>, line 10 in <module>>, <FrameSummary file <doctest...>, line 4 in lumberjack>, <FrameSummary file <doctest...>, line 7 in bright_side_of_death>] *** format_tb: [' File "<doctest...>", line 10, in <module>\n lumberjack()\n', ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n', ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n'] *** tb_lineno: 10 The following example shows the different ways to print and format the stack: >>> import traceback >>> def another_function(): ... lumberstack() ... >>> def lumberstack(): ... traceback.print_stack() ... print(repr(traceback.extract_stack())) ... print(repr(traceback.format_stack())) ... >>> another_function() File "<doctest>", line 10, in <module> another_function() File "<doctest>", line 3, in another_function lumberstack() File "<doctest>", line 6, in lumberstack traceback.print_stack() [('<doctest>', 10, '<module>', 'another_function()'), ('<doctest>', 3, 'another_function', 'lumberstack()'), ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')] [' File "<doctest>", line 10, in <module>\n another_function()\n', ' File "<doctest>", line 3, in another_function\n lumberstack()\n', ' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n'] This last example demonstrates the final few formatting functions: >>> import traceback >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'), ... ('eggs.py', 42, 'eggs', 'return "bacon"')]) [' File "spam.py", line 3, in <module>\n spam.eggs()\n', ' File "eggs.py", line 42, in eggs\n return "bacon"\n'] >>> an_error = IndexError('tuple index out of range') >>> traceback.format_exception_only(type(an_error), an_error) ['IndexError: tuple index out of range\n']
python.library.traceback
traceback.clear_frames(tb) Clears the local variables of all the stack frames in a traceback tb by calling the clear() method of each frame object. New in version 3.4.
python.library.traceback#traceback.clear_frames
traceback.extract_stack(f=None, limit=None) Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional f and limit arguments have the same meaning as for print_stack().
python.library.traceback#traceback.extract_stack
traceback.extract_tb(tb, limit=None) Return a StackSummary object representing a list of “pre-processed” stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. The optional limit argument has the same meaning as for print_tb(). A “pre-processed” stack trace entry is a FrameSummary object containing attributes filename, lineno, name, and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None.
python.library.traceback#traceback.extract_tb
traceback.format_exc(limit=None, chain=True) This is like print_exc(limit) but returns a string instead of printing to a file.
python.library.traceback#traceback.format_exc
traceback.format_exception(etype, value, tb, limit=None, chain=True) Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception(). Changed in version 3.5: The etype argument is ignored and inferred from the type of value.
python.library.traceback#traceback.format_exception
traceback.format_exception_only(etype, value) Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.
python.library.traceback#traceback.format_exception_only
traceback.format_list(extracted_list) Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None.
python.library.traceback#traceback.format_list
traceback.format_stack(f=None, limit=None) A shorthand for format_list(extract_stack(f, limit)).
python.library.traceback#traceback.format_stack
traceback.format_tb(tb, limit=None) A shorthand for format_list(extract_tb(tb, limit)).
python.library.traceback#traceback.format_tb
class traceback.FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None) Represent a single frame in the traceback or stack that is being formatted or printed. It may optionally have a stringified version of the frames locals included in it. If lookup_line is False, the source code is not looked up until the FrameSummary has the line attribute accessed (which also happens when casting it to a tuple). line may be directly provided, and will prevent line lookups happening at all. locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display.
python.library.traceback#traceback.FrameSummary
traceback.print_exc(limit=None, file=None, chain=True) This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain).
python.library.traceback#traceback.print_exc
traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True) Print exception information and stack trace entries from traceback object tb to file. This differs from print_tb() in the following ways: if tb is not None, it prints a header Traceback (most recent call last): it prints the exception etype and value after the stack trace if type(value) is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error. The optional limit argument has the same meaning as for print_tb(). If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception. Changed in version 3.5: The etype argument is ignored and inferred from the type of value.
python.library.traceback#traceback.print_exception
traceback.print_last(limit=None, file=None, chain=True) This is a shorthand for print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain). In general it will work only after an exception has reached an interactive prompt (see sys.last_type).
python.library.traceback#traceback.print_last
traceback.print_stack(f=None, limit=None, file=None) Print up to limit stack trace entries (starting from the invocation point) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start. The optional file argument has the same meaning as for print_tb(). Changed in version 3.5: Added negative limit support.
python.library.traceback#traceback.print_stack
traceback.print_tb(tb, limit=None, file=None) Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output. Changed in version 3.5: Added negative limit support.
python.library.traceback#traceback.print_tb
class traceback.StackSummary classmethod extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False) Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb()). If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False, the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations. classmethod from_list(a_list) Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements. format() Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines. For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions. Changed in version 3.6: Long sequences of repeated frames are now abbreviated.
python.library.traceback#traceback.StackSummary
classmethod extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False) Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb()). If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False, the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations.
python.library.traceback#traceback.StackSummary.extract
format() Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines. For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions. Changed in version 3.6: Long sequences of repeated frames are now abbreviated.
python.library.traceback#traceback.StackSummary.format
classmethod from_list(a_list) Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements.
python.library.traceback#traceback.StackSummary.from_list
class traceback.TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False) Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class. Note that when locals are captured, they are also shown in the traceback. __cause__ A TracebackException of the original __cause__. __context__ A TracebackException of the original __context__. __suppress_context__ The __suppress_context__ value from the original exception. stack A StackSummary representing the traceback. exc_type The class of the original traceback. filename For syntax errors - the file name where the error occurred. lineno For syntax errors - the line number where the error occurred. text For syntax errors - the text where the error occurred. offset For syntax errors - the offset into the text where the error occurred. msg For syntax errors - the compiler error message. classmethod from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False) Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class. Note that when locals are captured, they are also shown in the traceback. format(*, chain=True) Format the exception. If chain is not True, __cause__ and __context__ will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output. format_exception_only() Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output.
python.library.traceback#traceback.TracebackException
exc_type The class of the original traceback.
python.library.traceback#traceback.TracebackException.exc_type
filename For syntax errors - the file name where the error occurred.
python.library.traceback#traceback.TracebackException.filename
format(*, chain=True) Format the exception. If chain is not True, __cause__ and __context__ will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output.
python.library.traceback#traceback.TracebackException.format
format_exception_only() Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output.
python.library.traceback#traceback.TracebackException.format_exception_only
classmethod from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False) Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class. Note that when locals are captured, they are also shown in the traceback.
python.library.traceback#traceback.TracebackException.from_exception
lineno For syntax errors - the line number where the error occurred.
python.library.traceback#traceback.TracebackException.lineno