linecache --- 隨機存取文字列

原始碼:Lib/linecache.py


Thelinecache module allows one to get any line from a Python source file, whileattempting to optimize internally, using a cache, the common case where manylines are read from a single file. This is used by thetraceback moduleto retrieve source lines for inclusion in the formatted traceback.

tokenize.open() 函式用來開啟檔案。這個函式使用tokenize.detect_encoding() 來取得檔案的編碼;在沒有編碼標記的情況下,檔案編碼預設為 UTF-8。

Thelinecache module defines the following functions:

linecache.getline(filename,lineno,module_globals=None)

從名為filename 的檔案中取得lineno 行。這個函式不會產生例外 --- 它會在出錯時回傳'' (找到的行會包含終止換行字元)。

如果filename 表示一個凍結模組(以'<frozen' 開頭),且module_globals 不是None,則函式會嘗試從module_globals['__file__'] 取得實際的檔案名稱。

如果找不到名為filename 的檔案,函式會先檢查module_globals 中是否有PEP 302__loader__ 載入器。如果有這樣一個載入器,而且它定義了一個get_source 方法,這之後它就會決定原始碼行(如果get_source() 回傳None,那麼就會回傳'')。最後,如果filename 是相對的檔案名稱,則會相對於模組搜尋路徑sys.path 中的項目進行搜尋。

在 3.14 版的變更:凍結模組的支援filename

linecache.clearcache()

清除快取。如果你不再需要先前使用getline() 讀取的檔案行數,請使用此函式。

linecache.checkcache(filename=None)

檢查快取是否有效。如果快取中的檔案可能已在磁碟上變更,而你需要更新的版本,請使用此功能。 如果省略filename,則會檢查快取中的所有項目。

linecache.lazycache(filename,module_globals)

即使module_globals 在稍後的呼叫中是None ,也可以擷取非檔案型模組的足夠細節,以允許稍後透過getline() 取得其行。這可以避免在真正需要某一行之前進行 I/O 操作,而不必無限期地帶著模組的全域變數。

在 3.5 版被加入.

範例:

>>>importlinecache>>>linecache.getline(linecache.__file__,8)'import sys\n'