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