blob: 8ebee0585566818937ab362de913be8c77e29864 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`linecache` --- Random access to text lines
3================================================
4
5.. module:: linecache
6 :synopsis: This module provides random access to individual lines from text files.
7.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
8
9
10The :mod:`linecache` module allows one to get any line from any file, while
11attempting to optimize internally, using a cache, the common case where many
12lines are read from a single file. This is used by the :mod:`traceback` module
13to retrieve source lines for inclusion in the formatted traceback.
14
Raymond Hettingere0e08222010-11-06 07:10:31 +000015.. seealso::
16
17 Latest version of the `linecache module Python source code
18 <http://svn.python.org/view/python/branches/release27-maint/Lib/linecache.py?view=markup>`_
19
Georg Brandl8ec7f652007-08-15 14:28:01 +000020The :mod:`linecache` module defines the following functions:
21
22
23.. function:: getline(filename, lineno[, module_globals])
24
Georg Brandl21946af2010-10-06 09:28:45 +000025 Get line *lineno* from file named *filename*. This function will never raise an
Georg Brandl8ec7f652007-08-15 14:28:01 +000026 exception --- it will return ``''`` on errors (the terminating newline character
27 will be included for lines that are found).
28
29 .. index:: triple: module; search; path
30
31 If a file named *filename* is not found, the function will look for it in the
32 module search path, ``sys.path``, after first checking for a :pep:`302`
33 ``__loader__`` in *module_globals*, in case the module was imported from a
34 zipfile or other non-filesystem import source.
35
36 .. versionadded:: 2.5
37 The *module_globals* parameter was added.
38
39
40.. function:: clearcache()
41
42 Clear the cache. Use this function if you no longer need lines from files
43 previously read using :func:`getline`.
44
45
46.. function:: checkcache([filename])
47
48 Check the cache for validity. Use this function if files in the cache may have
49 changed on disk, and you require the updated version. If *filename* is omitted,
50 it will check all the entries in the cache.
51
52Example::
53
54 >>> import linecache
55 >>> linecache.getline('/etc/passwd', 4)
56 'sys:x:3:3:sys:/dev:/bin/sh\n'
57