blob: 0f895d76b83fa89767d2ce8641435eec9086f3d3 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`mmap` --- Memory-mapped file support
2==========================================
3
4.. module:: mmap
5 :synopsis: Interface to memory-mapped files for Unix and Windows.
6
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007--------------
Georg Brandl116aa622007-08-15 14:28:22 +00008
Antoine Pitrou11cb9612010-09-15 11:11:28 +00009Memory-mapped file objects behave like both :class:`bytearray` and like
10:term:`file objects <file object>`. You can use mmap objects in most places
11where :class:`bytearray` are expected; for example, you can use the :mod:`re`
12module to search through a memory-mapped file. You can also change a single
13byte by doing ``obj[index] = 97``, or change a subsequence by assigning to a
14slice: ``obj[i1:i2] = b'...'``. You can also read and write data starting at
15the current file position, and :meth:`seek` through the file to different positions.
Georg Brandl116aa622007-08-15 14:28:22 +000016
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +020017A memory-mapped file is created by the :class:`~mmap.mmap` constructor, which is
Christian Heimesdae2a892008-04-19 00:55:37 +000018different on Unix and on Windows. In either case you must provide a file
19descriptor for a file opened for update. If you wish to map an existing Python
20file object, use its :meth:`fileno` method to obtain the correct value for the
21*fileno* parameter. Otherwise, you can open the file using the
22:func:`os.open` function, which returns a file descriptor directly (the file
23still needs to be closed when done).
Georg Brandl116aa622007-08-15 14:28:22 +000024
Ross Lagerwall59c01ed2011-07-25 07:12:43 +020025.. note::
26 If you want to create a memory-mapping for a writable, buffered file, you
27 should :func:`~io.IOBase.flush` the file first. This is necessary to ensure
28 that local modifications to the buffers are actually available to the
29 mapping.
30
Georg Brandl86def6c2008-01-21 20:36:10 +000031For both the Unix and Windows versions of the constructor, *access* may be
Justus Schwabedal5a8a84b2017-11-07 15:51:43 -050032specified as an optional keyword parameter. *access* accepts one of four
33values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` to
34specify read-only, write-through or copy-on-write memory respectively, or
35:const:`ACCESS_DEFAULT` to defer to *prot*. *access* can be used on both Unix
36and Windows. If *access* is not specified, Windows mmap returns a
37write-through mapping. The initial memory values for all three access types
38are taken from the specified file. Assignment to an :const:`ACCESS_READ`
39memory map raises a :exc:`TypeError` exception. Assignment to an
40:const:`ACCESS_WRITE` memory map affects both memory and the underlying file.
41Assignment to an :const:`ACCESS_COPY` memory map affects memory but does not
42update the underlying file.
43
44.. versionchanged:: 3.7
45 Added :const:`ACCESS_DEFAULT` constant.
Georg Brandl116aa622007-08-15 14:28:22 +000046
Georg Brandl55ac8f02007-09-01 13:51:09 +000047To map anonymous memory, -1 should be passed as the fileno along with the length.
Georg Brandl116aa622007-08-15 14:28:22 +000048
Georg Brandlcd7f32b2009-06-08 09:13:45 +000049.. class:: mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +000050
Christian Heimesdae2a892008-04-19 00:55:37 +000051 **(Windows version)** Maps *length* bytes from the file specified by the
52 file handle *fileno*, and creates a mmap object. If *length* is larger
53 than the current size of the file, the file is extended to contain *length*
54 bytes. If *length* is ``0``, the maximum length of the map is the current
55 size of the file, except that if the file is empty Windows raises an
56 exception (you cannot create an empty mapping on Windows).
Georg Brandl116aa622007-08-15 14:28:22 +000057
Christian Heimesdae2a892008-04-19 00:55:37 +000058 *tagname*, if specified and not ``None``, is a string giving a tag name for
59 the mapping. Windows allows you to have many different mappings against
60 the same file. If you specify the name of an existing tag, that tag is
61 opened, otherwise a new tag of this name is created. If this parameter is
62 omitted or ``None``, the mapping is created without a name. Avoiding the
63 use of the tag parameter will assist in keeping your code portable between
64 Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +000065
Christian Heimesdae2a892008-04-19 00:55:37 +000066 *offset* may be specified as a non-negative integer offset. mmap references
67 will be relative to the offset from the beginning of the file. *offset*
Pablo Galindo027664a2018-10-20 01:37:55 +010068 defaults to 0. *offset* must be a multiple of the :const:`ALLOCATIONGRANULARITY`.
Georg Brandl116aa622007-08-15 14:28:22 +000069
Georg Brandl9afde1c2007-11-01 20:32:30 +000070
Georg Brandlcd7f32b2009-06-08 09:13:45 +000071.. class:: mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +000072 :noindex:
73
74 **(Unix version)** Maps *length* bytes from the file specified by the file
75 descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the
Christian Heimesdae2a892008-04-19 00:55:37 +000076 maximum length of the map will be the current size of the file when
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +020077 :class:`~mmap.mmap` is called.
Georg Brandl116aa622007-08-15 14:28:22 +000078
79 *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
Christian Heimesdae2a892008-04-19 00:55:37 +000080 private copy-on-write mapping, so changes to the contents of the mmap
81 object will be private to this process, and :const:`MAP_SHARED` creates a
82 mapping that's shared with all other processes mapping the same areas of
83 the file. The default value is :const:`MAP_SHARED`.
Georg Brandl116aa622007-08-15 14:28:22 +000084
Christian Heimesdae2a892008-04-19 00:55:37 +000085 *prot*, if specified, gives the desired memory protection; the two most
86 useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify
87 that the pages may be read or written. *prot* defaults to
88 :const:`PROT_READ \| PROT_WRITE`.
Georg Brandl116aa622007-08-15 14:28:22 +000089
Christian Heimesdae2a892008-04-19 00:55:37 +000090 *access* may be specified in lieu of *flags* and *prot* as an optional
91 keyword parameter. It is an error to specify both *flags*, *prot* and
92 *access*. See the description of *access* above for information on how to
93 use this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +000094
Christian Heimesdae2a892008-04-19 00:55:37 +000095 *offset* may be specified as a non-negative integer offset. mmap references
96 will be relative to the offset from the beginning of the file. *offset*
Pablo Galindo027664a2018-10-20 01:37:55 +010097 defaults to 0. *offset* must be a multiple of :const:`ALLOCATIONGRANULARITY`
98 which is equal to :const:`PAGESIZE` on Unix systems.
Georg Brandl48310cd2009-01-03 21:18:54 +000099
Victor Stinnera6cd0cf2011-05-02 01:05:37 +0200100 To ensure validity of the created memory mapping the file specified
101 by the descriptor *fileno* is internally automatically synchronized
102 with physical backing store on Mac OS X and OpenVMS.
103
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +0200104 This example shows a simple way of using :class:`~mmap.mmap`::
Christian Heimesd8654cf2007-12-02 15:22:16 +0000105
106 import mmap
107
108 # write a simple example file
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000109 with open("hello.txt", "wb") as f:
Benjamin Petersone099b372009-04-04 17:09:35 +0000110 f.write(b"Hello Python!\n")
Christian Heimesd8654cf2007-12-02 15:22:16 +0000111
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000112 with open("hello.txt", "r+b") as f:
Christian Heimesd8654cf2007-12-02 15:22:16 +0000113 # memory-map the file, size 0 means whole file
Ezio Melotti67714622013-03-13 02:27:00 +0200114 mm = mmap.mmap(f.fileno(), 0)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000115 # read content via standard file methods
Ezio Melotti67714622013-03-13 02:27:00 +0200116 print(mm.readline()) # prints b"Hello Python!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000117 # read content via slice notation
Ezio Melotti67714622013-03-13 02:27:00 +0200118 print(mm[:5]) # prints b"Hello"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000119 # update content using slice notation;
120 # note that new content must have same size
Ezio Melotti67714622013-03-13 02:27:00 +0200121 mm[6:] = b" world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000122 # ... and read again using standard file methods
Ezio Melotti67714622013-03-13 02:27:00 +0200123 mm.seek(0)
124 print(mm.readline()) # prints b"Hello world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000125 # close the map
Ezio Melotti67714622013-03-13 02:27:00 +0200126 mm.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000127
128
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +0200129 :class:`~mmap.mmap` can also be used as a context manager in a :keyword:`with`
Julien Palard78553132018-03-28 23:14:15 +0200130 statement::
Georg Brandl0bccc182010-08-01 14:50:00 +0000131
132 import mmap
133
Ezio Melotti67714622013-03-13 02:27:00 +0200134 with mmap.mmap(-1, 13) as mm:
Zachary Ware42f740d2016-04-28 14:47:12 -0500135 mm.write(b"Hello world!")
Georg Brandl0bccc182010-08-01 14:50:00 +0000136
137 .. versionadded:: 3.2
138 Context manager support.
139
140
Christian Heimesd8654cf2007-12-02 15:22:16 +0000141 The next example demonstrates how to create an anonymous map and exchange
142 data between the parent and child processes::
143
144 import mmap
145 import os
146
Ezio Melotti67714622013-03-13 02:27:00 +0200147 mm = mmap.mmap(-1, 13)
148 mm.write(b"Hello world!")
Christian Heimesd8654cf2007-12-02 15:22:16 +0000149
150 pid = os.fork()
151
Serhiy Storchakadba90392016-05-10 12:01:23 +0300152 if pid == 0: # In a child process
Ezio Melotti67714622013-03-13 02:27:00 +0200153 mm.seek(0)
154 print(mm.readline())
Christian Heimesd8654cf2007-12-02 15:22:16 +0000155
Ezio Melotti67714622013-03-13 02:27:00 +0200156 mm.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000157
Georg Brandl9afde1c2007-11-01 20:32:30 +0000158
Benjamin Petersone41251e2008-04-25 01:59:09 +0000159 Memory-mapped file objects support the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Benjamin Petersone41251e2008-04-25 01:59:09 +0000161 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Senthil Kumaranb9183952013-09-09 22:39:28 -0700163 Closes the mmap. Subsequent calls to other methods of the object will
164 result in a ValueError exception being raised. This will not close
165 the open file.
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167
Georg Brandl0bccc182010-08-01 14:50:00 +0000168 .. attribute:: closed
169
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200170 ``True`` if the file is closed.
Georg Brandl0bccc182010-08-01 14:50:00 +0000171
172 .. versionadded:: 3.2
173
174
Benjamin Petersone099b372009-04-04 17:09:35 +0000175 .. method:: find(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Benjamin Petersone099b372009-04-04 17:09:35 +0000177 Returns the lowest index in the object where the subsequence *sub* is
178 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000179 Optional arguments *start* and *end* are interpreted as in slice notation.
180 Returns ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Georg Brandl8c16cb92016-02-25 20:17:45 +0100182 .. versionchanged:: 3.5
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200183 Writable :term:`bytes-like object` is now accepted.
184
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000186 .. method:: flush([offset[, size]])
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Benjamin Petersone41251e2008-04-25 01:59:09 +0000188 Flushes changes made to the in-memory copy of a file back to disk. Without
189 use of this call there is no guarantee that changes are written back before
190 the object is destroyed. If *offset* and *size* are specified, only
191 changes to the given range of bytes will be flushed to disk; otherwise, the
Pablo Galindo027664a2018-10-20 01:37:55 +0100192 whole extent of the mapping is flushed. *offset* must be a multiple of the
193 :const:`PAGESIZE` or :const:`ALLOCATIONGRANULARITY`.
Christian Heimesdae2a892008-04-19 00:55:37 +0000194
Berker Peksage7d4b2f2018-08-22 21:21:05 +0300195 ``None`` is returned to indicate success. An exception is raised when the
196 call failed.
Christian Heimesdae2a892008-04-19 00:55:37 +0000197
Berker Peksage7d4b2f2018-08-22 21:21:05 +0300198 .. versionchanged:: 3.8
199 Previously, a nonzero value was returned on success; zero was returned
200 on error under Windows. A zero value was returned on success; an
201 exception was raised on error under Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203
Benjamin Petersone41251e2008-04-25 01:59:09 +0000204 .. method:: move(dest, src, count)
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Benjamin Petersone41251e2008-04-25 01:59:09 +0000206 Copy the *count* bytes starting at offset *src* to the destination index
207 *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
Georg Brandl7cb13192010-08-03 12:06:29 +0000208 move will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200211 .. method:: read([n])
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200213 Return a :class:`bytes` containing up to *n* bytes starting from the
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300214 current file position. If the argument is omitted, ``None`` or negative,
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200215 return all bytes from the current file position to the end of the
216 mapping. The file position is updated to point after the bytes that were
217 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200219 .. versionchanged:: 3.3
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300220 Argument can be omitted or ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Benjamin Petersone41251e2008-04-25 01:59:09 +0000222 .. method:: read_byte()
Georg Brandl116aa622007-08-15 14:28:22 +0000223
Benjamin Petersone099b372009-04-04 17:09:35 +0000224 Returns a byte at the current file position as an integer, and advances
225 the file position by 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227
Benjamin Petersone41251e2008-04-25 01:59:09 +0000228 .. method:: readline()
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Benjamin Petersone41251e2008-04-25 01:59:09 +0000230 Returns a single line, starting at the current file position and up to the
231 next newline.
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233
Benjamin Petersone41251e2008-04-25 01:59:09 +0000234 .. method:: resize(newsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Benjamin Petersone41251e2008-04-25 01:59:09 +0000236 Resizes the map and the underlying file, if any. If the mmap was created
237 with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
Georg Brandl7cb13192010-08-03 12:06:29 +0000238 raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240
Benjamin Petersone099b372009-04-04 17:09:35 +0000241 .. method:: rfind(sub[, start[, end]])
Georg Brandlfceab5a2008-01-19 20:08:23 +0000242
Benjamin Petersone099b372009-04-04 17:09:35 +0000243 Returns the highest index in the object where the subsequence *sub* is
244 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000245 Optional arguments *start* and *end* are interpreted as in slice notation.
246 Returns ``-1`` on failure.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000247
Georg Brandl8c16cb92016-02-25 20:17:45 +0100248 .. versionchanged:: 3.5
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200249 Writable :term:`bytes-like object` is now accepted.
250
Georg Brandlfceab5a2008-01-19 20:08:23 +0000251
Benjamin Petersone41251e2008-04-25 01:59:09 +0000252 .. method:: seek(pos[, whence])
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Benjamin Petersone41251e2008-04-25 01:59:09 +0000254 Set the file's current position. *whence* argument is optional and
255 defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
256 values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
257 position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
Georg Brandl116aa622007-08-15 14:28:22 +0000258
259
Benjamin Petersone41251e2008-04-25 01:59:09 +0000260 .. method:: size()
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Benjamin Petersone41251e2008-04-25 01:59:09 +0000262 Return the length of the file, which can be larger than the size of the
263 memory-mapped area.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
Benjamin Petersone41251e2008-04-25 01:59:09 +0000266 .. method:: tell()
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Benjamin Petersone41251e2008-04-25 01:59:09 +0000268 Returns the current position of the file pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270
Benjamin Petersone099b372009-04-04 17:09:35 +0000271 .. method:: write(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Benjamin Petersone099b372009-04-04 17:09:35 +0000273 Write the bytes in *bytes* into memory at the current position of the
Berker Peksag6282e652016-03-02 19:30:18 +0200274 file pointer and return the number of bytes written (never less than
275 ``len(bytes)``, since if the write fails, a :exc:`ValueError` will be
276 raised). The file position is updated to point after the bytes that
277 were written. If the mmap was created with :const:`ACCESS_READ`, then
Georg Brandl7cb13192010-08-03 12:06:29 +0000278 writing to it will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
Georg Brandl8c16cb92016-02-25 20:17:45 +0100280 .. versionchanged:: 3.5
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200281 Writable :term:`bytes-like object` is now accepted.
282
Berker Peksag6282e652016-03-02 19:30:18 +0200283 .. versionchanged:: 3.6
284 The number of bytes written is now returned.
285
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Benjamin Petersone41251e2008-04-25 01:59:09 +0000287 .. method:: write_byte(byte)
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Ezio Melottie130a522011-10-19 10:58:56 +0300289 Write the integer *byte* into memory at the current
Benjamin Petersone41251e2008-04-25 01:59:09 +0000290 position of the file pointer; the file position is advanced by ``1``. If
291 the mmap was created with :const:`ACCESS_READ`, then writing to it will
Georg Brandl7cb13192010-08-03 12:06:29 +0000292 raise a :exc:`TypeError` exception.