每周一个 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,由于当前目录中没有,因此会找到标准库中的文件。


目录
相关文章
|
14天前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
53 4
|
8天前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
88 0
|
2月前
|
存储 安全 数据处理
Python 内置模块 collections 详解
`collections` 是 Python 内置模块,提供多种高效数据类型,如 `namedtuple`、`deque`、`Counter` 等,帮助开发者优化数据处理流程,提升代码可读性与性能,适用于复杂数据结构管理与高效操作场景。
103 0
|
11月前
|
开发者 Python
如何在Python中管理模块和包的依赖关系?
在实际开发中,通常会结合多种方法来管理模块和包的依赖关系,以确保项目的顺利进行和可维护性。同时,要及时更新和解决依赖冲突等问题,以保证代码的稳定性和可靠性
320 62
|
3月前
|
数据安全/隐私保护 Python
抖音私信脚本app,协议私信群发工具,抖音python私信模块
这个实现包含三个主要模块:抖音私信核心功能类、辅助工具类和主程序入口。核心功能包括登录
|
6月前
|
Python
Python教程:os 与 sys 模块详细用法
os 模块用于与操作系统交互,主要涉及夹操作、路径操作和其他操作。例如,`os.rename()` 重命名文件,`os.mkdir()` 创建文件夹,`os.path.abspath()` 获取文件绝对路径等。sys 模块则用于与 Python 解释器交互,常用功能如 `sys.path` 查看模块搜索路径,`sys.platform` 检测操作系统等。这些模块提供了丰富的工具,便于开发中处理系统和文件相关任务。
237 14
|
10月前
|
Python
Python Internet 模块
Python Internet 模块。
211 74
|
7月前
|
人工智能 自然语言处理 Shell
[oeasy]python070_如何导入模块_导入模块的作用_hello_dunder_双下划线
本文介绍了如何在Python中导入模块及其作用,重点讲解了`__hello__`模块的导入与使用。通过`import`命令可以将外部模块引入当前环境,增强代码功能。例如,导入`__hello__`模块后可输出“Hello world!”。此外,还演示了如何使用`help()`和`dir()`函数查询模块信息,并展示了导入多个模块的方法。最后,通过一个实例,介绍了如何利用`jieba`、`WordCloud`和`matplotlib`模块生成词云图。总结来说,模块是封装好的功能部件,能够简化编程任务并提高效率。未来将探讨如何创建自定义模块。
86 8
|
7月前
|
缓存 Shell 开发工具
[oeasy]python071_我可以自己做一个模块吗_自定义模块_引入模块_import_diy
本文介绍了 Python 中模块的导入与自定义模块的创建。首先,我们回忆了模块的概念,即封装好功能的部件,并通过导入 `__hello__` 模块实现了输出 "hello world!" 的功能。接着,尝试创建并编辑自己的模块 `my_file.py`,引入 `time` 模块以获取当前时间,并在其中添加自定义输出。
104 5
|
11月前
|
算法 数据安全/隐私保护 开发者
马特赛特旋转算法:Python的随机模块背后的力量
马特赛特旋转算法是Python `random`模块的核心,由松本真和西村拓士于1997年提出。它基于线性反馈移位寄存器,具有超长周期和高维均匀性,适用于模拟、密码学等领域。Python中通过设置种子值初始化状态数组,经状态更新和输出提取生成随机数,代码简单高效。
269 63

推荐镜像

更多