linecache
--- 隨機存取文字列¶
原始碼: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).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
.
- linecache.clearcache()¶
Clear the cache. Use this function if you no longer need lines from filespreviously read using
getline()
.
- 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 via
getline()
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.在 3.5 版被加入.
範例:
>>>importlinecache>>>linecache.getline(linecache.__file__,8)'import sys\n'