blob: 7708028d9726ab0a0bb353230540bcf486dc5331 [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
Georg Brandl86def6c2008-01-21 20:36:10 +000024For both the Unix and Windows versions of the constructor, *access* may be
Georg Brandl116aa622007-08-15 14:28:22 +000025specified as an optional keyword parameter. *access* accepts one of three
Christian Heimesdae2a892008-04-19 00:55:37 +000026values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY`
27to specify read-only, write-through or copy-on-write memory respectively.
28*access* can be used on both Unix and Windows. If *access* is not specified,
29Windows mmap returns a write-through mapping. The initial memory values for
30all three access types are taken from the specified file. Assignment to an
31:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception.
32Assignment to an :const:`ACCESS_WRITE` memory map affects both memory and the
33underlying file. Assignment to an :const:`ACCESS_COPY` memory map affects
34memory but does not update the underlying file.
Georg Brandl116aa622007-08-15 14:28:22 +000035
Georg Brandl55ac8f02007-09-01 13:51:09 +000036To map anonymous memory, -1 should be passed as the fileno along with the length.
Georg Brandl116aa622007-08-15 14:28:22 +000037
Georg Brandlcd7f32b2009-06-08 09:13:45 +000038.. class:: mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +000039
Christian Heimesdae2a892008-04-19 00:55:37 +000040 **(Windows version)** Maps *length* bytes from the file specified by the
41 file handle *fileno*, and creates a mmap object. If *length* is larger
42 than the current size of the file, the file is extended to contain *length*
43 bytes. If *length* is ``0``, the maximum length of the map is the current
44 size of the file, except that if the file is empty Windows raises an
45 exception (you cannot create an empty mapping on Windows).
Georg Brandl116aa622007-08-15 14:28:22 +000046
Christian Heimesdae2a892008-04-19 00:55:37 +000047 *tagname*, if specified and not ``None``, is a string giving a tag name for
48 the mapping. Windows allows you to have many different mappings against
49 the same file. If you specify the name of an existing tag, that tag is
50 opened, otherwise a new tag of this name is created. If this parameter is
51 omitted or ``None``, the mapping is created without a name. Avoiding the
52 use of the tag parameter will assist in keeping your code portable between
53 Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +000054
Christian Heimesdae2a892008-04-19 00:55:37 +000055 *offset* may be specified as a non-negative integer offset. mmap references
56 will be relative to the offset from the beginning of the file. *offset*
57 defaults to 0. *offset* must be a multiple of the ALLOCATIONGRANULARITY.
Georg Brandl116aa622007-08-15 14:28:22 +000058
Georg Brandl9afde1c2007-11-01 20:32:30 +000059
Georg Brandlcd7f32b2009-06-08 09:13:45 +000060.. class:: mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +000061 :noindex:
62
63 **(Unix version)** Maps *length* bytes from the file specified by the file
64 descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the
Christian Heimesdae2a892008-04-19 00:55:37 +000065 maximum length of the map will be the current size of the file when
66 :class:`mmap` is called.
Georg Brandl116aa622007-08-15 14:28:22 +000067
68 *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
Christian Heimesdae2a892008-04-19 00:55:37 +000069 private copy-on-write mapping, so changes to the contents of the mmap
70 object will be private to this process, and :const:`MAP_SHARED` creates a
71 mapping that's shared with all other processes mapping the same areas of
72 the file. The default value is :const:`MAP_SHARED`.
Georg Brandl116aa622007-08-15 14:28:22 +000073
Christian Heimesdae2a892008-04-19 00:55:37 +000074 *prot*, if specified, gives the desired memory protection; the two most
75 useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify
76 that the pages may be read or written. *prot* defaults to
77 :const:`PROT_READ \| PROT_WRITE`.
Georg Brandl116aa622007-08-15 14:28:22 +000078
Christian Heimesdae2a892008-04-19 00:55:37 +000079 *access* may be specified in lieu of *flags* and *prot* as an optional
80 keyword parameter. It is an error to specify both *flags*, *prot* and
81 *access*. See the description of *access* above for information on how to
82 use this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +000083
Christian Heimesdae2a892008-04-19 00:55:37 +000084 *offset* may be specified as a non-negative integer offset. mmap references
85 will be relative to the offset from the beginning of the file. *offset*
86 defaults to 0. *offset* must be a multiple of the PAGESIZE or
87 ALLOCATIONGRANULARITY.
Georg Brandl48310cd2009-01-03 21:18:54 +000088
Victor Stinnera6cd0cf2011-05-02 01:05:37 +020089 To ensure validity of the created memory mapping the file specified
90 by the descriptor *fileno* is internally automatically synchronized
91 with physical backing store on Mac OS X and OpenVMS.
92
Georg Brandl86def6c2008-01-21 20:36:10 +000093 This example shows a simple way of using :class:`mmap`::
Christian Heimesd8654cf2007-12-02 15:22:16 +000094
95 import mmap
96
97 # write a simple example file
Benjamin Petersone0124bd2009-03-09 21:04:33 +000098 with open("hello.txt", "wb") as f:
Benjamin Petersone099b372009-04-04 17:09:35 +000099 f.write(b"Hello Python!\n")
Christian Heimesd8654cf2007-12-02 15:22:16 +0000100
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000101 with open("hello.txt", "r+b") as f:
Christian Heimesd8654cf2007-12-02 15:22:16 +0000102 # memory-map the file, size 0 means whole file
103 map = mmap.mmap(f.fileno(), 0)
104 # read content via standard file methods
Benjamin Petersone099b372009-04-04 17:09:35 +0000105 print(map.readline()) # prints b"Hello Python!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000106 # read content via slice notation
Benjamin Petersone099b372009-04-04 17:09:35 +0000107 print(map[:5]) # prints b"Hello"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000108 # update content using slice notation;
109 # note that new content must have same size
Benjamin Petersone099b372009-04-04 17:09:35 +0000110 map[6:] = b" world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000111 # ... and read again using standard file methods
112 map.seek(0)
Benjamin Petersone099b372009-04-04 17:09:35 +0000113 print(map.readline()) # prints b"Hello world!\n"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000114 # close the map
115 map.close()
116
117
Georg Brandl0bccc182010-08-01 14:50:00 +0000118 :class:`mmap` can also be used as a context manager in a :keyword:`with`
119 statement.::
120
121 import mmap
122
123 with mmap.mmap(-1, 13) as map:
124 map.write("Hello world!")
125
126 .. versionadded:: 3.2
127 Context manager support.
128
129
Christian Heimesd8654cf2007-12-02 15:22:16 +0000130 The next example demonstrates how to create an anonymous map and exchange
131 data between the parent and child processes::
132
133 import mmap
134 import os
135
136 map = mmap.mmap(-1, 13)
Benjamin Petersone099b372009-04-04 17:09:35 +0000137 map.write(b"Hello world!")
Christian Heimesd8654cf2007-12-02 15:22:16 +0000138
139 pid = os.fork()
140
141 if pid == 0: # In a child process
142 map.seek(0)
Georg Brandla09ca382007-12-02 18:20:12 +0000143 print(map.readline())
Christian Heimesd8654cf2007-12-02 15:22:16 +0000144
145 map.close()
146
Georg Brandl9afde1c2007-11-01 20:32:30 +0000147
Benjamin Petersone41251e2008-04-25 01:59:09 +0000148 Memory-mapped file objects support the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000149
Benjamin Petersone41251e2008-04-25 01:59:09 +0000150 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000151
Benjamin Petersone41251e2008-04-25 01:59:09 +0000152 Close the file. Subsequent calls to other methods of the object will
153 result in an exception being raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155
Georg Brandl0bccc182010-08-01 14:50:00 +0000156 .. attribute:: closed
157
158 True if the file is closed.
159
160 .. versionadded:: 3.2
161
162
Benjamin Petersone099b372009-04-04 17:09:35 +0000163 .. method:: find(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +0000164
Benjamin Petersone099b372009-04-04 17:09:35 +0000165 Returns the lowest index in the object where the subsequence *sub* is
166 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000167 Optional arguments *start* and *end* are interpreted as in slice notation.
168 Returns ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000171 .. method:: flush([offset[, size]])
Georg Brandl116aa622007-08-15 14:28:22 +0000172
Benjamin Petersone41251e2008-04-25 01:59:09 +0000173 Flushes changes made to the in-memory copy of a file back to disk. Without
174 use of this call there is no guarantee that changes are written back before
175 the object is destroyed. If *offset* and *size* are specified, only
176 changes to the given range of bytes will be flushed to disk; otherwise, the
177 whole extent of the mapping is flushed.
Christian Heimesdae2a892008-04-19 00:55:37 +0000178
Benjamin Petersone41251e2008-04-25 01:59:09 +0000179 **(Windows version)** A nonzero value returned indicates success; zero
180 indicates failure.
Christian Heimesdae2a892008-04-19 00:55:37 +0000181
Benjamin Petersone41251e2008-04-25 01:59:09 +0000182 **(Unix version)** A zero value is returned to indicate success. An
183 exception is raised when the call failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185
Benjamin Petersone41251e2008-04-25 01:59:09 +0000186 .. method:: move(dest, src, count)
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Benjamin Petersone41251e2008-04-25 01:59:09 +0000188 Copy the *count* bytes starting at offset *src* to the destination index
189 *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
Georg Brandl7cb13192010-08-03 12:06:29 +0000190 move will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200193 .. method:: read([n])
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200195 Return a :class:`bytes` containing up to *n* bytes starting from the
196 current file position. If the argument is omitted, *None* or negative,
197 return all bytes from the current file position to the end of the
198 mapping. The file position is updated to point after the bytes that were
199 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Charles-François Natali4dd453c2011-06-08 19:18:14 +0200201 .. versionchanged:: 3.3
202 Argument can be omitted or *None*.
Georg Brandl116aa622007-08-15 14:28:22 +0000203
Benjamin Petersone41251e2008-04-25 01:59:09 +0000204 .. method:: read_byte()
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Benjamin Petersone099b372009-04-04 17:09:35 +0000206 Returns a byte at the current file position as an integer, and advances
207 the file position by 1.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209
Benjamin Petersone41251e2008-04-25 01:59:09 +0000210 .. method:: readline()
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Benjamin Petersone41251e2008-04-25 01:59:09 +0000212 Returns a single line, starting at the current file position and up to the
213 next newline.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215
Benjamin Petersone41251e2008-04-25 01:59:09 +0000216 .. method:: resize(newsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Benjamin Petersone41251e2008-04-25 01:59:09 +0000218 Resizes the map and the underlying file, if any. If the mmap was created
219 with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
Georg Brandl7cb13192010-08-03 12:06:29 +0000220 raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222
Benjamin Petersone099b372009-04-04 17:09:35 +0000223 .. method:: rfind(sub[, start[, end]])
Georg Brandlfceab5a2008-01-19 20:08:23 +0000224
Benjamin Petersone099b372009-04-04 17:09:35 +0000225 Returns the highest index in the object where the subsequence *sub* is
226 found, such that *sub* is contained in the range [*start*, *end*].
Benjamin Petersone41251e2008-04-25 01:59:09 +0000227 Optional arguments *start* and *end* are interpreted as in slice notation.
228 Returns ``-1`` on failure.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000229
230
Benjamin Petersone41251e2008-04-25 01:59:09 +0000231 .. method:: seek(pos[, whence])
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Benjamin Petersone41251e2008-04-25 01:59:09 +0000233 Set the file's current position. *whence* argument is optional and
234 defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
235 values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
236 position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238
Benjamin Petersone41251e2008-04-25 01:59:09 +0000239 .. method:: size()
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Benjamin Petersone41251e2008-04-25 01:59:09 +0000241 Return the length of the file, which can be larger than the size of the
242 memory-mapped area.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244
Benjamin Petersone41251e2008-04-25 01:59:09 +0000245 .. method:: tell()
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Benjamin Petersone41251e2008-04-25 01:59:09 +0000247 Returns the current position of the file pointer.
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249
Benjamin Petersone099b372009-04-04 17:09:35 +0000250 .. method:: write(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Benjamin Petersone099b372009-04-04 17:09:35 +0000252 Write the bytes in *bytes* into memory at the current position of the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000253 file pointer; the file position is updated to point after the bytes that
254 were written. If the mmap was created with :const:`ACCESS_READ`, then
Georg Brandl7cb13192010-08-03 12:06:29 +0000255 writing to it will raise a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
Benjamin Petersone41251e2008-04-25 01:59:09 +0000258 .. method:: write_byte(byte)
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Benjamin Petersone099b372009-04-04 17:09:35 +0000260 Write the the integer *byte* into memory at the current
Benjamin Petersone41251e2008-04-25 01:59:09 +0000261 position of the file pointer; the file position is advanced by ``1``. If
262 the mmap was created with :const:`ACCESS_READ`, then writing to it will
Georg Brandl7cb13192010-08-03 12:06:29 +0000263 raise a :exc:`TypeError` exception.