blob: dacf8aa002a21fde88ffa8b61458929ee4da7588 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`linecache` --- Random access to text lines
2================================================
3
4.. module:: linecache
5 :synopsis: This module provides random access to individual lines from text files.
6.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
7
Raymond Hettinger10480942011-01-10 03:26:08 +00008**Source code:** :source:`Lib/linecache.py`
Georg Brandl116aa622007-08-15 14:28:22 +00009
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000010--------------
11
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`linecache` module allows one to get any line from any file, while
13attempting to optimize internally, using a cache, the common case where many
14lines are read from a single file. This is used by the :mod:`traceback` module
15to retrieve source lines for inclusion in the formatted traceback.
16
17The :mod:`linecache` module defines the following functions:
18
19
Georg Brandlcd7f32b2009-06-08 09:13:45 +000020.. function:: getline(filename, lineno, module_globals=None)
Georg Brandl116aa622007-08-15 14:28:22 +000021
Georg Brandl7cb13192010-08-03 12:06:29 +000022 Get line *lineno* from file named *filename*. This function will never raise an
Georg Brandl116aa622007-08-15 14:28:22 +000023 exception --- it will return ``''`` on errors (the terminating newline character
24 will be included for lines that are found).
25
26 .. index:: triple: module; search; path
27
28 If a file named *filename* is not found, the function will look for it in the
29 module search path, ``sys.path``, after first checking for a :pep:`302`
30 ``__loader__`` in *module_globals*, in case the module was imported from a
31 zipfile or other non-filesystem import source.
32
Georg Brandl116aa622007-08-15 14:28:22 +000033
34.. function:: clearcache()
35
36 Clear the cache. Use this function if you no longer need lines from files
37 previously read using :func:`getline`.
38
39
Georg Brandlcd7f32b2009-06-08 09:13:45 +000040.. function:: checkcache(filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 Check the cache for validity. Use this function if files in the cache may have
43 changed on disk, and you require the updated version. If *filename* is omitted,
44 it will check all the entries in the cache.
45
Georg Brandlcd7f32b2009-06-08 09:13:45 +000046
Georg Brandl116aa622007-08-15 14:28:22 +000047Example::
48
49 >>> import linecache
50 >>> linecache.getline('/etc/passwd', 4)
51 'sys:x:3:3:sys:/dev:/bin/sh\n'
52