实现说明
mmap 映射文件避免整读以函数 main为骨架。
导入行就是依赖契约:Path 来自 mmap,仅此而已。
使用要点
mmap必须先装好——示例直接导入它们。- 每一步打印都带着自己的标签:
mapped bytes:、header:、patched:。
常见问题
有第三方依赖吗?
mmap——运行前用包管理器装上。
核心语句
with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as handle:
handle.write(b'read only payload')
name = handle.name
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_WRITE) as view:
print('mapped bytes:', len(view))
print('header:', view[:10].decode('ascii'))
view[4:10] = b'UPDATE'
print('patched:', view[:10].decode('ascii'))
print('second record at:', view.find(b'second'))
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as view:
try:
view[0] = 65
except TypeError as exc:
print('read-only write blocked:', type(exc).__name__)
代码示例
import mmap
import tempfile
from pathlib import Path
def main() -> None:
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / 'journal.bin'
path.write_bytes(b'0000HEADER\nfirst record\nsecond record\n')
with path.open('r+b') as handle:
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_WRITE) as view:
print('mapped bytes:', len(view))
print('header:', view[:10].decode('ascii'))
view[4:10] = b'UPDATE'
print('patched:', view[:10].decode('ascii'))
print('second record at:', view.find(b'second'))
print('on disk:', path.read_bytes()[:10].decode('ascii'))
with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as handle:
handle.write(b'read only payload')
name = handle.name
with open(name, 'rb') as handle:
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as view:
try:
view[0] = 65
except TypeError as exc:
print('read-only write blocked:', type(exc).__name__)
Path(name).unlink()
if __name__ == '__main__':
main()