blob: d8a9ff3af36fbb15a6a3e5e35386c000d635e92b [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
8
9The :mod:`linecache` module allows one to get any line from any file, while
10attempting to optimize internally, using a cache, the common case where many
11lines are read from a single file. This is used by the :mod:`traceback` module
12to retrieve source lines for inclusion in the formatted traceback.
13
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000014.. seealso::
15
16 Latest version of the :source:`linecache module Python source code
17 <Lib/linecache.py>`
18
Georg Brandl116aa622007-08-15 14:28:22 +000019The :mod:`linecache` module defines the following functions:
20
21
Georg Brandlcd7f32b2009-06-08 09:13:45 +000022.. function:: getline(filename, lineno, module_globals=None)
Georg Brandl116aa622007-08-15 14:28:22 +000023
Georg Brandl7cb13192010-08-03 12:06:29 +000024 Get line *lineno* from file named *filename*. This function will never raise an
Georg Brandl116aa622007-08-15 14:28:22 +000025 exception --- it will return ``''`` on errors (the terminating newline character
26 will be included for lines that are found).
27
28 .. index:: triple: module; search; path
29
30 If a file named *filename* is not found, the function will look for it in the
31 module search path, ``sys.path``, after first checking for a :pep:`302`
32 ``__loader__`` in *module_globals*, in case the module was imported from a
33 zipfile or other non-filesystem import source.
34
Georg Brandl116aa622007-08-15 14:28:22 +000035
36.. function:: clearcache()
37
38 Clear the cache. Use this function if you no longer need lines from files
39 previously read using :func:`getline`.
40
41
Georg Brandlcd7f32b2009-06-08 09:13:45 +000042.. function:: checkcache(filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +000043
44 Check the cache for validity. Use this function if files in the cache may have
45 changed on disk, and you require the updated version. If *filename* is omitted,
46 it will check all the entries in the cache.
47
Georg Brandlcd7f32b2009-06-08 09:13:45 +000048
Georg Brandl116aa622007-08-15 14:28:22 +000049Example::
50
51 >>> import linecache
52 >>> linecache.getline('/etc/passwd', 4)
53 'sys:x:3:3:sys:/dev:/bin/sh\n'
54