mmap --- メモリマップファイル


利用可能性: Emscripten でなく、WASI でもないこと。

このモジュールは WebAssembly プラットフォーム wasm32-emscriptenwasm32-wasi では動作しないか、利用不可です。詳しくは、WebAssemblyプラットフォーム を見てください。

メモリにマップされたファイルオブジェクトは、 bytearrayファイルオブジェクト の両方のように振舞います。しかし通常の文字列オブジェクトとは異なり、これらは可変です。 bytearray が期待されるほとんどの場所で mmap オブジェクトを利用できます。例えば、メモリマップファイルを探索するために re モジュールを使うことができます。それらは可変なので、 obj[index] = 97 のように文字を変換できますし、スライスを使うことで obj[i1:i2] = b'...' のように部分文字列を変換することができます。現在のファイル位置をデータの始めとする読込みや書込み、ファイルの異なる位置へ seek() することもできます。

A memory-mapped file is created by the mmap constructor, which is different on Unix and on Windows. In either case you must provide a file descriptor for a file opened for update. If you wish to map an existing Python file object, use its fileno() method to obtain the correct value for the fileno parameter. Otherwise, you can open the file using the os.open() function, which returns a file descriptor directly (the file still needs to be closed when done).

注釈

書き込み可能でバッファされたファイルへのメモリマップファイルを作りたいのであれば、まず最初にファイルの flush() を呼び出すべきです。これはバッファへのローカルな修正がマッピングで実際に利用可能になることを保障するために必要です。

Unix バージョンと Windows バージョンのどちらのコンストラクタについても、オプションのキーワード・パラメータとして access を指定できます。 access は4つの値の内の1つを受け入れます。 ACCESS_READ は読み出し専用、 ACCESS_WRITE は書き込み可能、 ACCESS_COPY はコピーした上での書き込み、ACCESS_DEFAULTprot に従います。 access は Unix と Windows の両方で使用することができます。 access が指定されない場合、 Windows の mmap は書き込み可能マップを返します。 3つのアクセス型すべてに対する初期メモリ値は、指定されたファイルから得られます。 ACCESS_READ 型のメモリマップに対して書き込むと TypeError 例外を送出します。 ACCESS_WRITE 型のメモリマップへの書き込みはメモリと元のファイルの両方に影響を与えます。 ACCESS_COPY 型のメモリマップへの書き込みはメモリに影響を与えますが、元のファイルを更新することはありません。

バージョン 3.7 で変更: 定数 ACCESS_DEFAULT が追加されました。

無名メモリ(anonymous memory)にマップするためには fileno として -1 を渡し、length を与えてください。

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

(Windows バージョン) ファイルハンドル fileno によって指定されたファイルから length バイトをマップして、 mmap オブジェクトを生成します。 length が現在のファイルサイズより大きな場合、ファイルサイズは length を含む大きさにまで拡張されます。 length0 の場合、マップの最大の長さは現在のファイルサイズになります。ただし、ファイル自体が空のときは Windows が例外を送出します (Windows では空のマップを作成することができません)。

tagname, if specified and not None, is a string giving a tag name for the mapping. Windows allows you to have many different mappings against the same file. If you specify the name of an existing tag, that tag is opened, otherwise a new tag of this name is created. If this parameter is omitted or 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 です。offsetALLOCATIONGRANULARITY の倍数でなければなりません。

引数 fileno, length, access, offset 付きで 監査イベント mmap.__new__ を送出します。

class mmap.mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])

(Unix バージョン) ファイルディスクリプタ fileno で指定されたファイルから length バイトをマップし、mmap オブジェクトを返します。length0 の場合、マップの最大の長さは mmap が呼ばれた時点でのファイルサイズになります。

flags specifies the nature of the mapping. MAP_PRIVATE creates a private copy-on-write mapping, so changes to the contents of the mmap object will be private to this process, and MAP_SHARED creates a mapping that's shared with all other processes mapping the same areas of the file. The default value is MAP_SHARED. Some systems have additional possible flags with the full list specified in MAP_* constants.

prot が指定された場合、希望のメモリ保護を与えます。 2つの最も有用な値は、 PROT_READPROT_WRITE です。これは、読込み可能または書込み可能を指定するものです。 prot のデフォルトは PROT_READ | PROT_WRITE です。

access はオプションのキーワード・パラメータとして、 flagsprot の代わりに指定してもかまいません。 flags, protaccess の両方を指定することは間違っています。このパラメータの使用法についての情報は、先に述べた access の記述を参照してください。

offset may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. offset defaults to 0. offset must be a multiple of ALLOCATIONGRANULARITY which is equal to PAGESIZE on Unix systems.

To ensure validity of the created memory mapping the file specified by the descriptor fileno is internally automatically synchronized with the physical backing store on macOS.

この例は 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()

mmapwith 文の中でコンテキストマネージャとしても使えます:

import mmap

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

バージョン 3.2 で追加: コンテキストマネージャのサポート。

次の例では無名マップを作り親プロセスと子プロセスの間でデータのやりとりをしてみせます:

import mmap
import os

mm = mmap.mmap(-1, 13)
mm.write(b"Hello world!")

pid = os.fork()

if pid == 0:  # In a child process
    mm.seek(0)
    print(mm.readline())

    mm.close()

引数 fileno, length, access, offset 付きで 監査イベント mmap.__new__ を送出します。

メモリマップファイルオブジェクトは以下のメソッドをサポートしています:

close()

メモリマップファイルを閉じます。この呼出しの後にオブジェクトの他のメソッドの呼出すことは、 ValueError 例外の送出を引き起こします。このメソッドは開いたファイルのクローズはしません。

closed

ファイルが閉じている場合 True となります。

バージョン 3.2 で追加.

find(sub[, start[, end]])

オブジェクト内の [start, end] の範囲に含まれている部分シーケンス sub が見つかった場所の最も小さいインデックスを返します。オプションの引数 startend はスライスに使われるときのように解釈されます。失敗したときには -1 を返します。

バージョン 3.5 で変更: 書き込み可能な bytes-like object を使用できるようになりました。

flush([offset[, size]])

Flushes changes made to the in-memory copy of a file back to disk. Without use of this call there is no guarantee that changes are written back before the object is destroyed. If offset and size are specified, only changes to the given range of bytes will be flushed to disk; otherwise, the whole extent of the mapping is flushed. offset must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY.

None is returned to indicate success. An exception is raised when the call failed.

バージョン 3.8 で変更: Previously, a nonzero value was returned on success; zero was returned on error under Windows. A zero value was returned on success; an exception was raised on error under Unix.

madvise(option[, start[, length]])

Send advice option to the kernel about the memory region beginning at start and extending length bytes. option must be one of the MADV_* constants available on the system. If start and length are omitted, the entire mapping is spanned. On some systems (including Linux), start must be a multiple of the PAGESIZE.

Availability: Systems with the madvise() system call.

バージョン 3.8 で追加.

move(dest, src, count)

オフセット src から始まる count バイトをインデックス dest の位置へコピーします。もし mmap が ACCESS_READ で作成されていた場合、 TypeError 例外を発生させます。

read([n])

現在のファイル位置からの最大 n バイトを含む bytes を返します。引数が省略されるか、 None もしくは負の値が指定された場合、現在のファイル位置からマップ終端までの全てのバイト列を返します。ファイル位置は返されたバイト列の直後を指すように更新されます。

バージョン 3.3 で変更: 引数が省略可能になり、 None も受け付けるようになりました。

read_byte()

現在のファイル位置のバイトを整数値として返し、ファイル位置を 1 進めます。

readline()

Returns a single line, starting at the current file position and up to the next newline. The file position is updated to point after the bytes that were returned.

resize(newsize)

マップと元ファイル(がもしあれば)のサイズを変更します。もし mmap が ACCESS_READ または ACCESS_COPY で作成されたならば、マップサイズの変更は TypeError 例外を発生させます。

On Windows: Resizing the map will raise an OSError if there are other maps against the same named file. Resizing an anonymous map (ie against the pagefile) will silently create a new map with the original data copied over up to the length of the new size.

バージョン 3.11 で変更: Correctly fails if attempting to resize when another map is held Allows resize against an anonymous map on Windows

rfind(sub[, start[, end]])

オブジェクト内の [start, end] の範囲に含まれている部分シーケンス sub が見つかった場所の最も大きいインデックスを返します。オプションの引数 startend はスライスに使われるときのように解釈されます。失敗したときには -1 を返します。

バージョン 3.5 で変更: 書き込み可能な bytes-like object を使用できるようになりました。

seek(pos[, whence])

ファイルの現在位置をセットします。 whence 引数はオプションであり、デフォルトは os.SEEK_SET つまり 0 (絶対位置)です。その他の値として、 os.SEEK_CUR つまり 1 (現在位置からの相対位置)と os.SEEK_END つまり 2 (ファイルの終わりからの相対位置)があります。

size()

ファイルの長さを返します。メモリマップ領域のサイズより大きいかもしれません。

tell()

ファイルポインタの現在位置を返します。

write(bytes)

メモリ内のファイルポイントの現在位置に bytes のバイト列を書き込み、書き込まれたバイト数を返します(もし書き込みが失敗したら ValueError が送出されるため、len(bytes) より少なくなりません)。ファイル位置はバイト列が書き込まれた位置に更新されます。もしmmapが ACCESS_READ とともに作成されていた場合は、書き込みは TypeError 例外を送出するでしょう。

バージョン 3.5 で変更: 書き込み可能な bytes-like object を使用できるようになりました。

バージョン 3.6 で変更: 書きこまれたバイト数を返すようになりました。

write_byte(byte)

メモリ内のファイル・ポインタの現在位置に整数 byte を書き込みます。ファイル位置は 1 だけ進みます。もし mmap が ACCESS_READ で作成されていた場合、書き込み時に TypeError 例外を発生させるでしょう。

MADV_* Constants

mmap.MADV_NORMAL
mmap.MADV_RANDOM
mmap.MADV_SEQUENTIAL
mmap.MADV_WILLNEED
mmap.MADV_DONTNEED
mmap.MADV_REMOVE
mmap.MADV_DONTFORK
mmap.MADV_DOFORK
mmap.MADV_HWPOISON
mmap.MADV_MERGEABLE
mmap.MADV_UNMERGEABLE
mmap.MADV_SOFT_OFFLINE
mmap.MADV_HUGEPAGE
mmap.MADV_NOHUGEPAGE
mmap.MADV_DONTDUMP
mmap.MADV_DODUMP
mmap.MADV_FREE
mmap.MADV_NOSYNC
mmap.MADV_AUTOSYNC
mmap.MADV_NOCORE
mmap.MADV_CORE
mmap.MADV_PROTECT
mmap.MADV_FREE_REUSABLE
mmap.MADV_FREE_REUSE

These options can be passed to mmap.madvise(). Not every option will be present on every system.

Availability: Systems with the madvise() system call.

バージョン 3.8 で追加.

MAP_* Constants

mmap.MAP_SHARED
mmap.MAP_PRIVATE
mmap.MAP_DENYWRITE
mmap.MAP_EXECUTABLE
mmap.MAP_ANON
mmap.MAP_ANONYMOUS
mmap.MAP_POPULATE
mmap.MAP_STACK
mmap.MAP_ALIGNED_SUPER
mmap.MAP_CONCEAL

These are the various flags that can be passed to mmap.mmap(). MAP_ALIGNED_SUPER is only available at FreeBSD and MAP_CONCEAL is only available at OpenBSD. Note that some options might not be present on some systems.

バージョン 3.10 で変更: Added MAP_POPULATE constant.

バージョン 3.11 で追加: Added MAP_STACK constant.

バージョン 3.12 で追加: Added MAP_ALIGNED_SUPER constant. Added MAP_CONCEAL constant.