每周一个 Python 模块 | linecache

简介: 从文件或导入的 Python 模块中检索文本行,保存结果缓存,以便更高效地从同一文件中读取多行。linecache 在处理 Python 源文件时,该模块用于 Python 标准库的其他部分。缓存实现在内存中将文件内容分解为单独的行。API 通过索引请求的行到一个列表中,节省了重复读取文件和解析行以找到所需行的时间。这在查找同一文件中的多行时尤其有用,例如在为错误报告生成回溯时。

从文件或导入的 Python 模块中检索文本行,保存结果缓存,以便更高效地从同一文件中读取多行。

linecache 在处理 Python 源文件时,该模块用于 Python 标准库的其他部分。缓存实现在内存中将文件内容分解为单独的行。API 通过索引请求的行到一个列表中,节省了重复读取文件和解析行以找到所需行的时间。这在查找同一文件中的多行时尤其有用,例如在为错误报告生成回溯时。


测试数据


由 Lorem Ipsum 生成器生成的该文本用作样本输入。


# linecache_data.py 
import os
import tempfile
lorem = '''Lorem ipsum dolor sit amet, consectetuer
adipiscing elit.  Vivamus eget elit. In posuere mi non
risus. Mauris id quam posuere lectus sollicitudin
varius. Praesent at mi. Nunc eu velit. Sed augue massa,
fermentum id, nonummy a, nonummy sit amet, ligula. Curabitur
eros pede, egestas at, ultricies ac, apellentesque eu,
tellus.
Sed sed odio sed mi luctus mollis. Integer et nulla ac augue
convallis accumsan. Ut felis. Donec lectus sapien, elementum
nec, condimentum ac, interdum non, tellus. Aenean viverra,
mauris vehicula semper porttitor, ipsum odio consectetuer
lorem, ac imperdiet eros odio a sapien. Nulla mauris tellus,
aliquam non, egestas a, nonummy et, erat. Vivamus sagittis
porttitor eros.'''
def make_tempfile():
    fd, temp_file_name = tempfile.mkstemp()
    os.close(fd)
    with open(temp_file_name, 'wt') as f:
        f.write(lorem)
    return temp_file_name
def cleanup(filename):
    os.unlink(filename)
复制代码


读取特定行


linecache 模块读取的文件行数以 1 开头,通常数组索引都是从 0 开始。


import linecache
from linecache_data import *
filename = make_tempfile()
# Pick out the same line from source and cache.
# (Notice that linecache counts from 1)
print('SOURCE:')
print('{!r}'.format(lorem.split('\n')[4]))
print()
print('CACHE:')
print('{!r}'.format(linecache.getline(filename, 5)))
cleanup(filename)
# output
# SOURCE:
# 'fermentum id, nonummy a, nonummy sit amet, ligula. Curabitur'
#
# CACHE:
# 'fermentum id, nonummy a, nonummy sit amet, ligula. Curabitur\n'
复制代码


返回的每一行都包含一个尾随换行符。


处理空行


返回值始终包含行尾的换行符,因此如果行为空,则返回值只是换行符。


import linecache
from linecache_data import *
filename = make_tempfile()
# Blank lines include the newline
print('BLANK : {!r}'.format(linecache.getline(filename, 8)))    # BLANK : '\n'
cleanup(filename)
复制代码


输入文件的第八行不包含文本。


错误处理


如果请求的行号超出文件中有效行的范围,则 getline() 返回空字符串。


import linecache
from linecache_data import *
filename = make_tempfile()
# The cache always returns a string, and uses
# an empty string to indicate a line which does
# not exist.
not_there = linecache.getline(filename, 500)
print('NOT THERE: {!r} includes {} characters'.format(not_there, len(not_there)))    # NOT THERE: '' includes 0 characters
cleanup(filename)
复制代码


输入文件只有 15 行,因此请求行 500 就像尝试读取文件末尾一样。

从不存在的文件读取以相同的方式处理。


import linecache
# Errors are even hidden if linecache cannot find the file
no_such_file = linecache.getline(
    'this_file_does_not_exist.txt', 1,
)
print('NO FILE: {!r}'.format(no_such_file)) # NO FILE: ''
复制代码


当调用者尝试读取数据时,模块永远不会引发异常。


阅读 Python 源文件


由于 linecache 在生成回溯时使用得非常多,因此其关键特性之一是能够通过指定模块的基本名称在导入路径中查找 Python 源模块。


import linecache
import os
# Look for the linecache module, using
# the built in sys.path search.
module_line = linecache.getline('linecache.py', 3)
print('MODULE:')
print(repr(module_line))
# Look at the linecache module source directly.
file_src = linecache.__file__
if file_src.endswith('.pyc'):
    file_src = file_src[:-1]
print('\nFILE:')
with open(file_src, 'r') as f:
    file_line = f.readlines()[2]
print(repr(file_line))
# output
# MODULE:
# 'This is intended to read lines from modules imported -- hence if a filename\n'
# 
# FILE:
# 'This is intended to read lines from modules imported -- hence if a filename\n'
复制代码


如果命名模块在当前目录中找不到具有该名称的文件,则 linecache 会搜索 sys.path。这个例子是寻找的  linecache.py,由于当前目录中没有,因此会找到标准库中的文件。


目录
相关文章
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
1464 7
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
1199 0
|
开发者 Python
如何在Python中管理模块和包的依赖关系?
在实际开发中,通常会结合多种方法来管理模块和包的依赖关系,以确保项目的顺利进行和可维护性。同时,要及时更新和解决依赖冲突等问题,以保证代码的稳定性和可靠性
849 159
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
1005 4
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
390 4
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
1143 0
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
1583 0
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
1129 0
|
Python
Python Internet 模块
Python Internet 模块。
436 74

推荐镜像

更多