• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`!mmap` --- Memory-mapped file support
2===========================================
3
4.. module:: mmap
5   :synopsis: Interface to memory-mapped files for Unix and Windows.
6
7--------------
8
9.. include:: ../includes/wasm-notavail.rst
10
11Memory-mapped file objects behave like both :class:`bytearray` and like
12:term:`file objects <file object>`.  You can use mmap objects in most places
13where :class:`bytearray` are expected; for example, you can use the :mod:`re`
14module to search through a memory-mapped file.  You can also change a single
15byte by doing ``obj[index] = 97``, or change a subsequence by assigning to a
16slice: ``obj[i1:i2] = b'...'``.  You can also read and write data starting at
17the current file position, and :meth:`seek` through the file to different positions.
18
19A memory-mapped file is created by the :class:`~mmap.mmap` constructor, which is
20different on Unix and on Windows.  In either case you must provide a file
21descriptor for a file opened for update. If you wish to map an existing Python
22file object, use its :meth:`~io.IOBase.fileno` method to obtain the correct value for the
23*fileno* parameter.  Otherwise, you can open the file using the
24:func:`os.open` function, which returns a file descriptor directly (the file
25still needs to be closed when done).
26
27.. note::
28   If you want to create a memory-mapping for a writable, buffered file, you
29   should :func:`~io.IOBase.flush` the file first.  This is necessary to ensure
30   that local modifications to the buffers are actually available to the
31   mapping.
32
33For both the Unix and Windows versions of the constructor, *access* may be
34specified as an optional keyword parameter. *access* accepts one of four
35values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` to
36specify read-only, write-through or copy-on-write memory respectively, or
37:const:`ACCESS_DEFAULT` to defer to *prot*.  *access* can be used on both Unix
38and Windows.  If *access* is not specified, Windows mmap returns a
39write-through mapping.  The initial memory values for all three access types
40are taken from the specified file.  Assignment to an :const:`ACCESS_READ`
41memory map raises a :exc:`TypeError` exception.  Assignment to an
42:const:`ACCESS_WRITE` memory map affects both memory and the underlying file.
43Assignment to an :const:`ACCESS_COPY` memory map affects memory but does not
44update the underlying file.
45
46.. versionchanged:: 3.7
47   Added :const:`ACCESS_DEFAULT` constant.
48
49To map anonymous memory, -1 should be passed as the fileno along with the length.
50
51.. class:: mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT, offset=0)
52
53   **(Windows version)** Maps *length* bytes from the file specified by the
54   file handle *fileno*, and creates a mmap object.  If *length* is larger
55   than the current size of the file, the file is extended to contain *length*
56   bytes.  If *length* is ``0``, the maximum length of the map is the current
57   size of the file, except that if the file is empty Windows raises an
58   exception (you cannot create an empty mapping on Windows).
59
60   *tagname*, if specified and not ``None``, is a string giving a tag name for
61   the mapping.  Windows allows you to have many different mappings against
62   the same file.  If you specify the name of an existing tag, that tag is
63   opened, otherwise a new tag of this name is created.  If this parameter is
64   omitted or ``None``, the mapping is created without a name.  Avoiding the
65   use of the *tagname* parameter will assist in keeping your code portable
66   between Unix and Windows.
67
68   *offset* may be specified as a non-negative integer offset. mmap references
69   will be relative to the offset from the beginning of the file. *offset*
70   defaults to 0.  *offset* must be a multiple of the :const:`ALLOCATIONGRANULARITY`.
71
72   .. audit-event:: mmap.__new__ fileno,length,access,offset mmap.mmap
73
74.. class:: mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, \
75                access=ACCESS_DEFAULT, offset=0, *, trackfd=True)
76   :noindex:
77
78   **(Unix version)** Maps *length* bytes from the file specified by the file
79   descriptor *fileno*, and returns a mmap object.  If *length* is ``0``, the
80   maximum length of the map will be the current size of the file when
81   :class:`~mmap.mmap` is called.
82
83   *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
84   private copy-on-write mapping, so changes to the contents of the mmap
85   object will be private to this process, and :const:`MAP_SHARED` creates a
86   mapping that's shared with all other processes mapping the same areas of
87   the file.  The default value is :const:`MAP_SHARED`. Some systems have
88   additional possible flags with the full list specified in
89   :ref:`MAP_* constants <map-constants>`.
90
91   *prot*, if specified, gives the desired memory protection; the two most
92   useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify
93   that the pages may be read or written.  *prot* defaults to
94   :const:`PROT_READ \| PROT_WRITE`.
95
96   *access* may be specified in lieu of *flags* and *prot* as an optional
97   keyword parameter.  It is an error to specify both *flags*, *prot* and
98   *access*.  See the description of *access* above for information on how to
99   use this parameter.
100
101   *offset* may be specified as a non-negative integer offset. mmap references
102   will be relative to the offset from the beginning of the file. *offset*
103   defaults to 0. *offset* must be a multiple of :const:`ALLOCATIONGRANULARITY`
104   which is equal to :const:`PAGESIZE` on Unix systems.
105
106   If *trackfd* is ``False``, the file descriptor specified by *fileno* will
107   not be duplicated, and the resulting :class:`!mmap` object will not
108   be associated with the map's underlying file.
109   This means that the :meth:`~mmap.mmap.size` and :meth:`~mmap.mmap.resize`
110   methods will fail.
111   This mode is useful to limit the number of open file descriptors.
112
113   To ensure validity of the created memory mapping the file specified
114   by the descriptor *fileno* is internally automatically synchronized
115   with the physical backing store on macOS.
116
117   .. versionchanged:: 3.13
118      The *trackfd* parameter was added.
119
120   This example shows a simple way of using :class:`~mmap.mmap`::
121
122      import mmap
123
124      # write a simple example file
125      with open("hello.txt", "wb") as f:
126          f.write(b"Hello Python!\n")
127
128      with open("hello.txt", "r+b") as f:
129          # memory-map the file, size 0 means whole file
130          mm = mmap.mmap(f.fileno(), 0)
131          # read content via standard file methods
132          print(mm.readline())  # prints b"Hello Python!\n"
133          # read content via slice notation
134          print(mm[:5])  # prints b"Hello"
135          # update content using slice notation;
136          # note that new content must have same size
137          mm[6:] = b" world!\n"
138          # ... and read again using standard file methods
139          mm.seek(0)
140          print(mm.readline())  # prints b"Hello  world!\n"
141          # close the map
142          mm.close()
143
144
145   :class:`~mmap.mmap` can also be used as a context manager in a :keyword:`with`
146   statement::
147
148      import mmap
149
150      with mmap.mmap(-1, 13) as mm:
151          mm.write(b"Hello world!")
152
153   .. versionadded:: 3.2
154      Context manager support.
155
156
157   The next example demonstrates how to create an anonymous map and exchange
158   data between the parent and child processes::
159
160      import mmap
161      import os
162
163      mm = mmap.mmap(-1, 13)
164      mm.write(b"Hello world!")
165
166      pid = os.fork()
167
168      if pid == 0:  # In a child process
169          mm.seek(0)
170          print(mm.readline())
171
172          mm.close()
173
174   .. audit-event:: mmap.__new__ fileno,length,access,offset mmap.mmap
175
176   Memory-mapped file objects support the following methods:
177
178   .. method:: close()
179
180      Closes the mmap. Subsequent calls to other methods of the object will
181      result in a ValueError exception being raised. This will not close
182      the open file.
183
184
185   .. attribute:: closed
186
187      ``True`` if the file is closed.
188
189      .. versionadded:: 3.2
190
191
192   .. method:: find(sub[, start[, end]])
193
194      Returns the lowest index in the object where the subsequence *sub* is
195      found, such that *sub* is contained in the range [*start*, *end*].
196      Optional arguments *start* and *end* are interpreted as in slice notation.
197      Returns ``-1`` on failure.
198
199      .. versionchanged:: 3.5
200         Writable :term:`bytes-like object` is now accepted.
201
202
203   .. method:: flush([offset[, size]])
204
205      Flushes changes made to the in-memory copy of a file back to disk. Without
206      use of this call there is no guarantee that changes are written back before
207      the object is destroyed.  If *offset* and *size* are specified, only
208      changes to the given range of bytes will be flushed to disk; otherwise, the
209      whole extent of the mapping is flushed.  *offset* must be a multiple of the
210      :const:`PAGESIZE` or :const:`ALLOCATIONGRANULARITY`.
211
212      ``None`` is returned to indicate success.  An exception is raised when the
213      call failed.
214
215      .. versionchanged:: 3.8
216         Previously, a nonzero value was returned on success; zero was returned
217         on error under Windows.  A zero value was returned on success; an
218         exception was raised on error under Unix.
219
220
221   .. method:: madvise(option[, start[, length]])
222
223      Send advice *option* to the kernel about the memory region beginning at
224      *start* and extending *length* bytes.  *option* must be one of the
225      :ref:`MADV_* constants <madvise-constants>` available on the system.  If
226      *start* and *length* are omitted, the entire mapping is spanned.  On
227      some systems (including Linux), *start* must be a multiple of the
228      :const:`PAGESIZE`.
229
230      Availability: Systems with the ``madvise()`` system call.
231
232      .. versionadded:: 3.8
233
234
235   .. method:: move(dest, src, count)
236
237      Copy the *count* bytes starting at offset *src* to the destination index
238      *dest*.  If the mmap was created with :const:`ACCESS_READ`, then calls to
239      move will raise a :exc:`TypeError` exception.
240
241
242   .. method:: read([n])
243
244      Return a :class:`bytes` containing up to *n* bytes starting from the
245      current file position. If the argument is omitted, ``None`` or negative,
246      return all bytes from the current file position to the end of the
247      mapping. The file position is updated to point after the bytes that were
248      returned.
249
250      .. versionchanged:: 3.3
251         Argument can be omitted or ``None``.
252
253   .. method:: read_byte()
254
255      Returns a byte at the current file position as an integer, and advances
256      the file position by 1.
257
258
259   .. method:: readline()
260
261      Returns a single line, starting at the current file position and up to the
262      next newline. The file position is updated to point after the bytes that were
263      returned.
264
265
266   .. method:: resize(newsize)
267
268      Resizes the map and the underlying file, if any.
269
270      Resizing a map created with *access* of :const:`ACCESS_READ` or
271      :const:`ACCESS_COPY`, will raise a :exc:`TypeError` exception.
272      Resizing a map created with with *trackfd* set to ``False``,
273      will raise a :exc:`ValueError` exception.
274
275      **On Windows**: Resizing the map will raise an :exc:`OSError` if there are other
276      maps against the same named file. Resizing an anonymous map (ie against the
277      pagefile) will silently create a new map with the original data copied over
278      up to the length of the new size.
279
280      .. versionchanged:: 3.11
281         Correctly fails if attempting to resize when another map is held
282         Allows resize against an anonymous map on Windows
283
284   .. method:: rfind(sub[, start[, end]])
285
286      Returns the highest index in the object where the subsequence *sub* is
287      found, such that *sub* is contained in the range [*start*, *end*].
288      Optional arguments *start* and *end* are interpreted as in slice notation.
289      Returns ``-1`` on failure.
290
291      .. versionchanged:: 3.5
292         Writable :term:`bytes-like object` is now accepted.
293
294
295   .. method:: seek(pos[, whence])
296
297      Set the file's current position.  *whence* argument is optional and
298      defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
299      values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
300      position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
301
302      .. versionchanged:: 3.13
303         Return the new absolute position instead of ``None``.
304
305   .. method:: seekable()
306
307      Return whether the file supports seeking, and the return value is always ``True``.
308
309      .. versionadded:: 3.13
310
311   .. method:: size()
312
313      Return the length of the file, which can be larger than the size of the
314      memory-mapped area.
315
316
317   .. method:: tell()
318
319      Returns the current position of the file pointer.
320
321
322   .. method:: write(bytes)
323
324      Write the bytes in *bytes* into memory at the current position of the
325      file pointer and return the number of bytes written (never less than
326      ``len(bytes)``, since if the write fails, a :exc:`ValueError` will be
327      raised).  The file position is updated to point after the bytes that
328      were written.  If the mmap was created with :const:`ACCESS_READ`, then
329      writing to it will raise a :exc:`TypeError` exception.
330
331      .. versionchanged:: 3.5
332         Writable :term:`bytes-like object` is now accepted.
333
334      .. versionchanged:: 3.6
335         The number of bytes written is now returned.
336
337
338   .. method:: write_byte(byte)
339
340      Write the integer *byte* into memory at the current
341      position of the file pointer; the file position is advanced by ``1``. If
342      the mmap was created with :const:`ACCESS_READ`, then writing to it will
343      raise a :exc:`TypeError` exception.
344
345.. _madvise-constants:
346
347MADV_* Constants
348++++++++++++++++
349
350.. data:: MADV_NORMAL
351          MADV_RANDOM
352          MADV_SEQUENTIAL
353          MADV_WILLNEED
354          MADV_DONTNEED
355          MADV_REMOVE
356          MADV_DONTFORK
357          MADV_DOFORK
358          MADV_HWPOISON
359          MADV_MERGEABLE
360          MADV_UNMERGEABLE
361          MADV_SOFT_OFFLINE
362          MADV_HUGEPAGE
363          MADV_NOHUGEPAGE
364          MADV_DONTDUMP
365          MADV_DODUMP
366          MADV_FREE
367          MADV_NOSYNC
368          MADV_AUTOSYNC
369          MADV_NOCORE
370          MADV_CORE
371          MADV_PROTECT
372          MADV_FREE_REUSABLE
373          MADV_FREE_REUSE
374
375   These options can be passed to :meth:`mmap.madvise`.  Not every option will
376   be present on every system.
377
378   Availability: Systems with the madvise() system call.
379
380   .. versionadded:: 3.8
381
382.. _map-constants:
383
384MAP_* Constants
385+++++++++++++++
386
387.. data:: MAP_SHARED
388          MAP_PRIVATE
389          MAP_32BIT
390          MAP_ALIGNED_SUPER
391          MAP_ANON
392          MAP_ANONYMOUS
393          MAP_CONCEAL
394          MAP_DENYWRITE
395          MAP_EXECUTABLE
396          MAP_HASSEMAPHORE
397          MAP_JIT
398          MAP_NOCACHE
399          MAP_NOEXTEND
400          MAP_NORESERVE
401          MAP_POPULATE
402          MAP_RESILIENT_CODESIGN
403          MAP_RESILIENT_MEDIA
404          MAP_STACK
405          MAP_TPRO
406          MAP_TRANSLATED_ALLOW_EXECUTE
407          MAP_UNIX03
408
409    These are the various flags that can be passed to :meth:`mmap.mmap`.  :data:`MAP_ALIGNED_SUPER`
410    is only available at FreeBSD and :data:`MAP_CONCEAL` is only available at OpenBSD.  Note
411    that some options might not be present on some systems.
412
413    .. versionchanged:: 3.10
414       Added :data:`MAP_POPULATE` constant.
415
416    .. versionadded:: 3.11
417       Added :data:`MAP_STACK` constant.
418
419    .. versionadded:: 3.12
420       Added :data:`MAP_ALIGNED_SUPER` and :data:`MAP_CONCEAL` constants.
421
422    .. versionadded:: 3.13
423       Added :data:`MAP_32BIT`, :data:`MAP_HASSEMAPHORE`, :data:`MAP_JIT`,
424       :data:`MAP_NOCACHE`, :data:`MAP_NOEXTEND`, :data:`MAP_NORESERVE`,
425       :data:`MAP_RESILIENT_CODESIGN`, :data:`MAP_RESILIENT_MEDIA`,
426       :data:`MAP_TPRO`, :data:`MAP_TRANSLATED_ALLOW_EXECUTE`, and
427       :data:`MAP_UNIX03` constants.
428
429