blob: 18e05e31f751089b31907ae6f734108976cb1fb0 [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
Ezio Melotti67714622013-03-13 02:27:00 +0200109 mm = mmap.mmap(f.fileno(), 0)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000110 # read content via standard file methods
Ezio Melotti67714622013-03-13 02:27:00 +0200111 print(mm.readline()) # prints b"Hello Python!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000112 # read content via slice notation
Ezio Melotti67714622013-03-13 02:27:00 +0200113 print(mm[: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
Ezio Melotti67714622013-03-13 02:27:00 +0200116 mm[6:] = b" world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000117 # ... and read again using standard file methods
Ezio Melotti67714622013-03-13 02:27:00 +0200118 mm.seek(0)
119 print(mm.readline()) # prints b"Hello world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000120 # close the map
Ezio Melotti67714622013-03-13 02:27:00 +0200121 mm.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000122
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
Ezio Melotti67714622013-03-13 02:27:00 +0200129 with mmap.mmap(-1, 13) as mm:
130 mm.write("Hello world!")
Georg Brandl0bccc182010-08-01 14:50:00 +0000131
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
Ezio Melotti67714622013-03-13 02:27:00 +0200142 mm = mmap.mmap(-1, 13)
143 mm.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
Ezio Melotti67714622013-03-13 02:27:00 +0200148 mm.seek(0)
149 print(mm.readline())
Christian Heimesd8654cf2007-12-02 15:22:16 +0000150
Ezio Melotti67714622013-03-13 02:27:00 +0200151 mm.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000152
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
Senthil Kumaranb9183952013-09-09 22:39:28 -0700158 Closes the mmap. Subsequent calls to other methods of the object will
159 result in a ValueError exception being raised. This will not close
160 the open file.
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162
Georg Brandl0bccc182010-08-01 14:50:00 +0000163 .. attribute:: closed
164
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200165 ``True`` if the file is closed.
Georg Brandl0bccc182010-08-01 14:50:00 +0000166
167 .. versionadded:: 3.2
168
169
Benjamin Petersone099b372009-04-04 17:09:35 +0000170 .. method:: find(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +0000171
Benjamin Petersone099b372009-04-04 17:09:35 +0000172 Returns the lowest index in the object where the subsequence *sub* is
173 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000174 Optional arguments *start* and *end* are interpreted as in slice notation.
175 Returns ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000176
177
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000178 .. method:: flush([offset[, size]])
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Benjamin Petersone41251e2008-04-25 01:59:09 +0000180 Flushes changes made to the in-memory copy of a file back to disk. Without
181 use of this call there is no guarantee that changes are written back before
182 the object is destroyed. If *offset* and *size* are specified, only
183 changes to the given range of bytes will be flushed to disk; otherwise, the
184 whole extent of the mapping is flushed.
Christian Heimesdae2a892008-04-19 00:55:37 +0000185
Benjamin Petersone41251e2008-04-25 01:59:09 +0000186 **(Windows version)** A nonzero value returned indicates success; zero
187 indicates failure.
Christian Heimesdae2a892008-04-19 00:55:37 +0000188
Benjamin Petersone41251e2008-04-25 01:59:09 +0000189 **(Unix version)** A zero value is returned to indicate success. An
190 exception is raised when the call failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192
Benjamin Petersone41251e2008-04-25 01:59:09 +0000193 .. method:: move(dest, src, count)
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Benjamin Petersone41251e2008-04-25 01:59:09 +0000195 Copy the *count* bytes starting at offset *src* to the destination index
196 *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
Georg Brandl7cb13192010-08-03 12:06:29 +0000197 move will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200200 .. method:: read([n])
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200202 Return a :class:`bytes` containing up to *n* bytes starting from the
203 current file position. If the argument is omitted, *None* or negative,
204 return all bytes from the current file position to the end of the
205 mapping. The file position is updated to point after the bytes that were
206 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200208 .. versionchanged:: 3.3
209 Argument can be omitted or *None*.
Georg Brandl116aa622007-08-15 14:28:22 +0000210
Benjamin Petersone41251e2008-04-25 01:59:09 +0000211 .. method:: read_byte()
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Benjamin Petersone099b372009-04-04 17:09:35 +0000213 Returns a byte at the current file position as an integer, and advances
214 the file position by 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216
Benjamin Petersone41251e2008-04-25 01:59:09 +0000217 .. method:: readline()
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Benjamin Petersone41251e2008-04-25 01:59:09 +0000219 Returns a single line, starting at the current file position and up to the
220 next newline.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222
Benjamin Petersone41251e2008-04-25 01:59:09 +0000223 .. method:: resize(newsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Benjamin Petersone41251e2008-04-25 01:59:09 +0000225 Resizes the map and the underlying file, if any. If the mmap was created
226 with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
Georg Brandl7cb13192010-08-03 12:06:29 +0000227 raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229
Benjamin Petersone099b372009-04-04 17:09:35 +0000230 .. method:: rfind(sub[, start[, end]])
Georg Brandlfceab5a2008-01-19 20:08:23 +0000231
Benjamin Petersone099b372009-04-04 17:09:35 +0000232 Returns the highest index in the object where the subsequence *sub* is
233 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000234 Optional arguments *start* and *end* are interpreted as in slice notation.
235 Returns ``-1`` on failure.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000236
237
Benjamin Petersone41251e2008-04-25 01:59:09 +0000238 .. method:: seek(pos[, whence])
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Benjamin Petersone41251e2008-04-25 01:59:09 +0000240 Set the file's current position. *whence* argument is optional and
241 defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
242 values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
243 position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245
Benjamin Petersone41251e2008-04-25 01:59:09 +0000246 .. method:: size()
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Benjamin Petersone41251e2008-04-25 01:59:09 +0000248 Return the length of the file, which can be larger than the size of the
249 memory-mapped area.
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251
Benjamin Petersone41251e2008-04-25 01:59:09 +0000252 .. method:: tell()
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Benjamin Petersone41251e2008-04-25 01:59:09 +0000254 Returns the current position of the file pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256
Benjamin Petersone099b372009-04-04 17:09:35 +0000257 .. method:: write(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Benjamin Petersone099b372009-04-04 17:09:35 +0000259 Write the bytes in *bytes* into memory at the current position of the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000260 file pointer; the file position is updated to point after the bytes that
261 were written. If the mmap was created with :const:`ACCESS_READ`, then
Georg Brandl7cb13192010-08-03 12:06:29 +0000262 writing to it will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264
Benjamin Petersone41251e2008-04-25 01:59:09 +0000265 .. method:: write_byte(byte)
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Ezio Melottie130a522011-10-19 10:58:56 +0300267 Write the integer *byte* into memory at the current
Benjamin Petersone41251e2008-04-25 01:59:09 +0000268 position of the file pointer; the file position is advanced by ``1``. If
269 the mmap was created with :const:`ACCESS_READ`, then writing to it will
Georg Brandl7cb13192010-08-03 12:06:29 +0000270 raise a :exc:`TypeError` exception.