blob: 1598cb83acaa808c7c144bbd4c1a2df0ad6ef14e [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
7
Antoine Pitrou11cb9612010-09-15 11:11:28 +00008Memory-mapped file objects behave like both :class:`bytearray` and like
9:term:`file objects <file object>`. You can use mmap objects in most places
10where :class:`bytearray` are expected; for example, you can use the :mod:`re`
11module to search through a memory-mapped file. You can also change a single
12byte by doing ``obj[index] = 97``, or change a subsequence by assigning to a
13slice: ``obj[i1:i2] = b'...'``. You can also read and write data starting at
14the current file position, and :meth:`seek` through the file to different positions.
Georg Brandl116aa622007-08-15 14:28:22 +000015
Christian Heimesdae2a892008-04-19 00:55:37 +000016A memory-mapped file is created by the :class:`mmap` constructor, which is
17different on Unix and on Windows. In either case you must provide a file
18descriptor for a file opened for update. If you wish to map an existing Python
19file object, use its :meth:`fileno` method to obtain the correct value for the
20*fileno* parameter. Otherwise, you can open the file using the
21:func:`os.open` function, which returns a file descriptor directly (the file
22still needs to be closed when done).
Georg Brandl116aa622007-08-15 14:28:22 +000023
Ross Lagerwall59c01ed2011-07-25 07:12:43 +020024.. note::
25 If you want to create a memory-mapping for a writable, buffered file, you
26 should :func:`~io.IOBase.flush` the file first. This is necessary to ensure
27 that local modifications to the buffers are actually available to the
28 mapping.
29
Georg Brandl86def6c2008-01-21 20:36:10 +000030For both the Unix and Windows versions of the constructor, *access* may be
Georg Brandl116aa622007-08-15 14:28:22 +000031specified as an optional keyword parameter. *access* accepts one of three
Christian Heimesdae2a892008-04-19 00:55:37 +000032values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY`
33to specify read-only, write-through or copy-on-write memory respectively.
34*access* can be used on both Unix and Windows. If *access* is not specified,
35Windows mmap returns a write-through mapping. The initial memory values for
36all three access types are taken from the specified file. Assignment to an
37:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception.
38Assignment to an :const:`ACCESS_WRITE` memory map affects both memory and the
39underlying file. Assignment to an :const:`ACCESS_COPY` memory map affects
40memory but does not update the underlying file.
Georg Brandl116aa622007-08-15 14:28:22 +000041
Georg Brandl55ac8f02007-09-01 13:51:09 +000042To map anonymous memory, -1 should be passed as the fileno along with the length.
Georg Brandl116aa622007-08-15 14:28:22 +000043
Georg Brandlcd7f32b2009-06-08 09:13:45 +000044.. class:: mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +000045
Christian Heimesdae2a892008-04-19 00:55:37 +000046 **(Windows version)** Maps *length* bytes from the file specified by the
47 file handle *fileno*, and creates a mmap object. If *length* is larger
48 than the current size of the file, the file is extended to contain *length*
49 bytes. If *length* is ``0``, the maximum length of the map is the current
50 size of the file, except that if the file is empty Windows raises an
51 exception (you cannot create an empty mapping on Windows).
Georg Brandl116aa622007-08-15 14:28:22 +000052
Christian Heimesdae2a892008-04-19 00:55:37 +000053 *tagname*, if specified and not ``None``, is a string giving a tag name for
54 the mapping. Windows allows you to have many different mappings against
55 the same file. If you specify the name of an existing tag, that tag is
56 opened, otherwise a new tag of this name is created. If this parameter is
57 omitted or ``None``, the mapping is created without a name. Avoiding the
58 use of the tag parameter will assist in keeping your code portable between
59 Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +000060
Christian Heimesdae2a892008-04-19 00:55:37 +000061 *offset* may be specified as a non-negative integer offset. mmap references
62 will be relative to the offset from the beginning of the file. *offset*
63 defaults to 0. *offset* must be a multiple of the ALLOCATIONGRANULARITY.
Georg Brandl116aa622007-08-15 14:28:22 +000064
Georg Brandl9afde1c2007-11-01 20:32:30 +000065
Georg Brandlcd7f32b2009-06-08 09:13:45 +000066.. class:: mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +000067 :noindex:
68
69 **(Unix version)** Maps *length* bytes from the file specified by the file
70 descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the
Christian Heimesdae2a892008-04-19 00:55:37 +000071 maximum length of the map will be the current size of the file when
72 :class:`mmap` is called.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74 *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
Christian Heimesdae2a892008-04-19 00:55:37 +000075 private copy-on-write mapping, so changes to the contents of the mmap
76 object will be private to this process, and :const:`MAP_SHARED` creates a
77 mapping that's shared with all other processes mapping the same areas of
78 the file. The default value is :const:`MAP_SHARED`.
Georg Brandl116aa622007-08-15 14:28:22 +000079
Christian Heimesdae2a892008-04-19 00:55:37 +000080 *prot*, if specified, gives the desired memory protection; the two most
81 useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify
82 that the pages may be read or written. *prot* defaults to
83 :const:`PROT_READ \| PROT_WRITE`.
Georg Brandl116aa622007-08-15 14:28:22 +000084
Christian Heimesdae2a892008-04-19 00:55:37 +000085 *access* may be specified in lieu of *flags* and *prot* as an optional
86 keyword parameter. It is an error to specify both *flags*, *prot* and
87 *access*. See the description of *access* above for information on how to
88 use this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +000089
Christian Heimesdae2a892008-04-19 00:55:37 +000090 *offset* may be specified as a non-negative integer offset. mmap references
91 will be relative to the offset from the beginning of the file. *offset*
92 defaults to 0. *offset* must be a multiple of the PAGESIZE or
93 ALLOCATIONGRANULARITY.
Georg Brandl48310cd2009-01-03 21:18:54 +000094
Victor Stinnera6cd0cf2011-05-02 01:05:37 +020095 To ensure validity of the created memory mapping the file specified
96 by the descriptor *fileno* is internally automatically synchronized
97 with physical backing store on Mac OS X and OpenVMS.
98
Georg Brandl86def6c2008-01-21 20:36:10 +000099 This example shows a simple way of using :class:`mmap`::
Christian Heimesd8654cf2007-12-02 15:22:16 +0000100
101 import mmap
102
103 # write a simple example file
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000104 with open("hello.txt", "wb") as f:
Benjamin Petersone099b372009-04-04 17:09:35 +0000105 f.write(b"Hello Python!\n")
Christian Heimesd8654cf2007-12-02 15:22:16 +0000106
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000107 with open("hello.txt", "r+b") as f:
Christian Heimesd8654cf2007-12-02 15:22:16 +0000108 # memory-map the file, size 0 means whole file
109 map = mmap.mmap(f.fileno(), 0)
110 # read content via standard file methods
Benjamin Petersone099b372009-04-04 17:09:35 +0000111 print(map.readline()) # prints b"Hello Python!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000112 # read content via slice notation
Benjamin Petersone099b372009-04-04 17:09:35 +0000113 print(map[:5]) # prints b"Hello"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000114 # update content using slice notation;
115 # note that new content must have same size
Benjamin Petersone099b372009-04-04 17:09:35 +0000116 map[6:] = b" world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000117 # ... and read again using standard file methods
118 map.seek(0)
Benjamin Petersone099b372009-04-04 17:09:35 +0000119 print(map.readline()) # prints b"Hello world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000120 # close the map
121 map.close()
122
123
Georg Brandl0bccc182010-08-01 14:50:00 +0000124 :class:`mmap` can also be used as a context manager in a :keyword:`with`
125 statement.::
126
127 import mmap
128
129 with mmap.mmap(-1, 13) as map:
130 map.write("Hello world!")
131
132 .. versionadded:: 3.2
133 Context manager support.
134
135
Christian Heimesd8654cf2007-12-02 15:22:16 +0000136 The next example demonstrates how to create an anonymous map and exchange
137 data between the parent and child processes::
138
139 import mmap
140 import os
141
142 map = mmap.mmap(-1, 13)
Benjamin Petersone099b372009-04-04 17:09:35 +0000143 map.write(b"Hello world!")
Christian Heimesd8654cf2007-12-02 15:22:16 +0000144
145 pid = os.fork()
146
147 if pid == 0: # In a child process
148 map.seek(0)
Georg Brandla09ca382007-12-02 18:20:12 +0000149 print(map.readline())
Christian Heimesd8654cf2007-12-02 15:22:16 +0000150
151 map.close()
152
Georg Brandl9afde1c2007-11-01 20:32:30 +0000153
Benjamin Petersone41251e2008-04-25 01:59:09 +0000154 Memory-mapped file objects support the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Benjamin Petersone41251e2008-04-25 01:59:09 +0000156 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Benjamin Petersone41251e2008-04-25 01:59:09 +0000158 Close the file. Subsequent calls to other methods of the object will
159 result in an exception being raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161
Georg Brandl0bccc182010-08-01 14:50:00 +0000162 .. attribute:: closed
163
164 True if the file is closed.
165
166 .. versionadded:: 3.2
167
168
Benjamin Petersone099b372009-04-04 17:09:35 +0000169 .. method:: find(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +0000170
Benjamin Petersone099b372009-04-04 17:09:35 +0000171 Returns the lowest index in the object where the subsequence *sub* is
172 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000173 Optional arguments *start* and *end* are interpreted as in slice notation.
174 Returns ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000177 .. method:: flush([offset[, size]])
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Benjamin Petersone41251e2008-04-25 01:59:09 +0000179 Flushes changes made to the in-memory copy of a file back to disk. Without
180 use of this call there is no guarantee that changes are written back before
181 the object is destroyed. If *offset* and *size* are specified, only
182 changes to the given range of bytes will be flushed to disk; otherwise, the
183 whole extent of the mapping is flushed.
Christian Heimesdae2a892008-04-19 00:55:37 +0000184
Benjamin Petersone41251e2008-04-25 01:59:09 +0000185 **(Windows version)** A nonzero value returned indicates success; zero
186 indicates failure.
Christian Heimesdae2a892008-04-19 00:55:37 +0000187
Benjamin Petersone41251e2008-04-25 01:59:09 +0000188 **(Unix version)** A zero value is returned to indicate success. An
189 exception is raised when the call failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191
Benjamin Petersone41251e2008-04-25 01:59:09 +0000192 .. method:: move(dest, src, count)
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Benjamin Petersone41251e2008-04-25 01:59:09 +0000194 Copy the *count* bytes starting at offset *src* to the destination index
195 *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
Georg Brandl7cb13192010-08-03 12:06:29 +0000196 move will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200199 .. method:: read([n])
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200201 Return a :class:`bytes` containing up to *n* bytes starting from the
202 current file position. If the argument is omitted, *None* or negative,
203 return all bytes from the current file position to the end of the
204 mapping. The file position is updated to point after the bytes that were
205 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200207 .. versionchanged:: 3.3
208 Argument can be omitted or *None*.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Benjamin Petersone41251e2008-04-25 01:59:09 +0000210 .. method:: read_byte()
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Benjamin Petersone099b372009-04-04 17:09:35 +0000212 Returns a byte at the current file position as an integer, and advances
213 the file position by 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215
Benjamin Petersone41251e2008-04-25 01:59:09 +0000216 .. method:: readline()
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Benjamin Petersone41251e2008-04-25 01:59:09 +0000218 Returns a single line, starting at the current file position and up to the
219 next newline.
Georg Brandl116aa622007-08-15 14:28:22 +0000220
221
Benjamin Petersone41251e2008-04-25 01:59:09 +0000222 .. method:: resize(newsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000223
Benjamin Petersone41251e2008-04-25 01:59:09 +0000224 Resizes the map and the underlying file, if any. If the mmap was created
225 with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
Georg Brandl7cb13192010-08-03 12:06:29 +0000226 raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228
Benjamin Petersone099b372009-04-04 17:09:35 +0000229 .. method:: rfind(sub[, start[, end]])
Georg Brandlfceab5a2008-01-19 20:08:23 +0000230
Benjamin Petersone099b372009-04-04 17:09:35 +0000231 Returns the highest index in the object where the subsequence *sub* is
232 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000233 Optional arguments *start* and *end* are interpreted as in slice notation.
234 Returns ``-1`` on failure.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000235
236
Benjamin Petersone41251e2008-04-25 01:59:09 +0000237 .. method:: seek(pos[, whence])
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Benjamin Petersone41251e2008-04-25 01:59:09 +0000239 Set the file's current position. *whence* argument is optional and
240 defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
241 values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
242 position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244
Benjamin Petersone41251e2008-04-25 01:59:09 +0000245 .. method:: size()
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Benjamin Petersone41251e2008-04-25 01:59:09 +0000247 Return the length of the file, which can be larger than the size of the
248 memory-mapped area.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250
Benjamin Petersone41251e2008-04-25 01:59:09 +0000251 .. method:: tell()
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Benjamin Petersone41251e2008-04-25 01:59:09 +0000253 Returns the current position of the file pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255
Benjamin Petersone099b372009-04-04 17:09:35 +0000256 .. method:: write(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Benjamin Petersone099b372009-04-04 17:09:35 +0000258 Write the bytes in *bytes* into memory at the current position of the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000259 file pointer; the file position is updated to point after the bytes that
260 were written. If the mmap was created with :const:`ACCESS_READ`, then
Georg Brandl7cb13192010-08-03 12:06:29 +0000261 writing to it will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000262
263
Benjamin Petersone41251e2008-04-25 01:59:09 +0000264 .. method:: write_byte(byte)
Georg Brandl116aa622007-08-15 14:28:22 +0000265
Benjamin Petersone099b372009-04-04 17:09:35 +0000266 Write the the integer *byte* into memory at the current
Benjamin Petersone41251e2008-04-25 01:59:09 +0000267 position of the file pointer; the file position is advanced by ``1``. If
268 the mmap was created with :const:`ACCESS_READ`, then writing to it will
Georg Brandl7cb13192010-08-03 12:06:29 +0000269 raise a :exc:`TypeError` exception.