mmap — 内存映射文件支持


可用性 :非 WASI。

This module does not work or is not available on WebAssembly. See WebAssembly 平台 了解更多信息。

内存映射文件对象的行为像 bytearray 和像 文件对象 。可以在大多数地方使用 mmap 对象若 bytearray 被期望;例如,可以使用 re 模块搜索内存映射文件。还可以改变单个字节通过执行 obj[index] = 97 ,或通过赋值切片改变子序列: obj[i1:i2] = b'...' 。还可以从当前文件位置开始读写数据,及 seek() 透过文件到不同位置。

内存映射文件的创建通过 mmap 构造函数,这在 Unix 和 Windows 会有所不同。无论哪种情况,都必须为更新打开文件提供文件描述符。若希望映射现有 Python 文件对象,使用其 fileno() 方法以获取正确值对于 fileno 参数。否则,可以打开文件使用 os.open() 函数,直接返回文件描述符 (文件仍需关闭当完成时)。

注意

若想要为可写缓冲文件创建内存映射,应 flush() 文件首先。这是必要的,以确保本地修改缓冲实际可用于映射。

对于 Unix 和 Windows 版本的构造函数, access 可以被指定为可选关键词参数。 access 接受 4 值之一: ACCESS_READ , ACCESS_WRITE ,或 ACCESS_COPY 以分别指定只读、透写或写时拷贝内存,或 ACCESS_DEFAULT to defer to prot . access 可以用于 Unix 和 Windows。若 access is not specified, Windows mmap returns a write-through mapping. The initial memory values for all three access types are taken from the specified file. Assignment to an ACCESS_READ 内存映射引发 TypeError 异常。赋值 ACCESS_WRITE 内存映射影响内存和底层文件。赋值 ACCESS_COPY 内存映射影响内存但不会更新底层文件。

3.7 版改变: 添加 ACCESS_DEFAULT 常量。

要映射匿名内存,-1 应作为 fileno 同长度一起传递。

class mmap. mmap ( fileno , length , tagname = None , access = ACCESS_DEFAULT , offset = 0 )

(Windows 版本) 映射 length 字节从文件指定通过文件句柄 fileno ,并创建 mmap 对象。若 length > 文件的当前大小,将扩展文件以包含 length 字节。若 length is 0 ,映射的最大长度是文件的当前大小,除文件为空 Windows 引发异常外 (不可以在 Windows 创建空映射)。

tagname ,若指定且不是 None ,是给出映射标签名的字符串。Windows 允许同一文件拥有许多不同映射。若指定现有标签名,则打开该标签,否则将创建此名称的新标签。若此参数被省略或 None , the mapping is created without a name. Avoiding the use of the tagname parameter will assist in keeping your code portable between Unix and Windows.

offset 可以指定为非负整数偏移。mmap 引用将相对文件开头偏移。 offset 默认为 0。 offset 必须是倍增的 ALLOCATIONGRANULARITY .

引发 审计事件 mmap.__new__ 采用自变量 fileno , length , access , offset .

class mmap. mmap ( fileno , length , flags = MAP_SHARED , prot = PROT_WRITE | PROT_READ , access = ACCESS_DEFAULT , offset = 0 , * , trackfd = True )

(Unix 版本) 映射 length 字节从文件指定通过文件描述符 fileno ,并返回 mmap 对象。若 length is 0 ,映射的最大长度将是文件的当前大小当 mmap 被调用。

flags 指定映射的性质。 MAP_PRIVATE 创建私有的写时拷贝映射,因此对 mmap 对象内容的更改将是此进程私有的,和 MAP_SHARED 创建与映射文件相同区域所有其它进程共享的映射。默认值为 MAP_SHARED . Some systems have additional possible flags with the full list specified in MAP_* constants .

prot 若指定,给出期望内存保护;2 个最有用的值是 PROT_READ and PROT_WRITE ,以指定页面可以被读取或写入。 prot 默认为 PROT_READ | PROT_WRITE .

access 可以指定以代替 flags and prot 作为可选关键词参数。它是错误的同时指定 flags , prot and access 。见描述对于 access 上文对如何使用此参数的有关信息。

offset 可以指定为非负整数偏移。mmap 引用将相对文件开头偏移。 offset 默认为 0。 offset 必须是倍增的 ALLOCATIONGRANULARITY 等于 PAGESIZE 在 Unix 系统。

trackfd is False , the file descriptor specified by fileno will not be duplicated, and the resulting mmap object will not be associated with the map’s underlying file. This means that the size() and resize() methods will fail. This mode is useful to limit the number of open file descriptors.

要确保创建内存有效映射文件,指定通过描述符 fileno is internally automatically synchronized with the physical backing store on macOS.

Changed in version 3.13: The trackfd 参数被添加。

此范例展示简单方式使用 mmap :

import mmap
# write a simple example file
with open("hello.txt", "wb") as f:
    f.write(b"Hello Python!\n")
with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print(mm.readline())  # prints b"Hello Python!\n"
    # read content via slice notation
    print(mm[:5])  # prints b"Hello"
    # update content using slice notation;
    # note that new content must have same size
    mm[6:] = b" world!\n"
    # ... and read again using standard file methods
    mm.seek(0)
    print(mm.readline())  # prints b"Hello  world!\n"
    # close the map
    mm.close()
											

mmap 还可以用作上下文管理器在 with 语句:

import mmap
with mmap.mmap(-1, 13) as mm:
    mm.write(b"Hello world!")