linecache — Random access to text lines

Source code:Lib/linecache.py


Thelinecache module allows one to get any line from a Python source file, whileattempting to optimize internally, using a cache, the common case where manylines are read from a single file. This is used by thetraceback moduleto retrieve source lines for inclusion in the formatted traceback.

Thetokenize.open() function is used to open files. Thisfunction usestokenize.detect_encoding() to get the encoding of thefile; in the absence of an encoding token, the file encoding defaults to UTF-8.

Thelinecache module defines the following functions:

linecache.getline(filename,lineno,module_globals=None)

Get linelineno from file namedfilename. This function will never raise anexception — it will return'' on errors (the terminating newline characterwill be included for lines that are found).

Iffilename indicates a frozen module (starting with'<frozen'), the functionwill attepmt to get the real file name frommodule_globals['__file__'] ifmodule_globals is notNone.

If a file namedfilename is not found, the function first checksfor aPEP 302__loader__ inmodule_globals.If there is such a loader and it defines aget_source method,then that determines the source lines(ifget_source() returnsNone, then'' is returned).Finally, iffilename is a relative filename,it is looked up relative to the entries in the module search path,sys.path.

Changed in version 3.14:Supportfilename of frozen modules.

linecache.clearcache()

Clear the cache. Use this function if you no longer need lines from filespreviously read usinggetline().

linecache.checkcache(filename=None)

Check the cache for validity. Use this function if files in the cache may havechanged on disk, and you require the updated version. Iffilename is omitted,it will check all the entries in the cache.

linecache.lazycache(filename,module_globals)

Capture enough detail about a non-file-based module to permit getting itslines later viagetline() even ifmodule_globals isNone in the latercall. This avoids doing I/O until a line is actually needed, without havingto carry the module globals around indefinitely.

Added in version 3.5.

Example:

>>>importlinecache>>>linecache.getline(linecache.__file__,8)'import sys\n'