Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 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 | |
Éric Araujo | 29a0b57 | 2011-08-19 02:14:03 +0200 | [diff] [blame] | 9 | **Source code:** :source:`Lib/linecache.py` |
| 10 | |
| 11 | -------------- |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 12 | |
| 13 | The :mod:`linecache` module allows one to get any line from any file, while |
| 14 | attempting to optimize internally, using a cache, the common case where many |
| 15 | lines are read from a single file. This is used by the :mod:`traceback` module |
| 16 | to retrieve source lines for inclusion in the formatted traceback. |
| 17 | |
| 18 | The :mod:`linecache` module defines the following functions: |
| 19 | |
| 20 | |
| 21 | .. function:: getline(filename, lineno[, module_globals]) |
| 22 | |
Georg Brandl | 21946af | 2010-10-06 09:28:45 +0000 | [diff] [blame] | 23 | Get line *lineno* from file named *filename*. This function will never raise an |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 24 | exception --- it will return ``''`` on errors (the terminating newline character |
| 25 | will be included for lines that are found). |
| 26 | |
| 27 | .. index:: triple: module; search; path |
| 28 | |
| 29 | If a file named *filename* is not found, the function will look for it in the |
| 30 | module search path, ``sys.path``, after first checking for a :pep:`302` |
| 31 | ``__loader__`` in *module_globals*, in case the module was imported from a |
| 32 | zipfile or other non-filesystem import source. |
| 33 | |
| 34 | .. versionadded:: 2.5 |
| 35 | The *module_globals* parameter was added. |
| 36 | |
| 37 | |
| 38 | .. function:: clearcache() |
| 39 | |
| 40 | Clear the cache. Use this function if you no longer need lines from files |
| 41 | previously read using :func:`getline`. |
| 42 | |
| 43 | |
| 44 | .. function:: checkcache([filename]) |
| 45 | |
| 46 | Check the cache for validity. Use this function if files in the cache may have |
| 47 | changed on disk, and you require the updated version. If *filename* is omitted, |
| 48 | it will check all the entries in the cache. |
| 49 | |
| 50 | Example:: |
| 51 | |
| 52 | >>> import linecache |
| 53 | >>> linecache.getline('/etc/passwd', 4) |
| 54 | 'sys:x:3:3:sys:/dev:/bin/sh\n' |
| 55 | |