blob: 0361320dc1ac21ce2d514490bcfa93053763fb71 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`mmap` --- Memory-mapped file support
3==========================================
4
5.. module:: mmap
6 :synopsis: Interface to memory-mapped files for Unix and Windows.
7
8
9Memory-mapped file objects behave like both strings and like file objects.
10Unlike normal string objects, however, these are mutable. You can use mmap
Christian Heimesdae2a892008-04-19 00:55:37 +000011objects in most places where strings are expected; for example, you can use
12the :mod:`re` module to search through a memory-mapped file. Since they're
13mutable, you can change a single character by doing ``obj[index] = 'a'``, or
14change a substring by assigning to a slice: ``obj[i1:i2] = '...'``. You can
15also read and write data starting at the current file position, and
16:meth:`seek` through the file to different positions.
Georg Brandl116aa622007-08-15 14:28:22 +000017
Christian Heimesdae2a892008-04-19 00:55:37 +000018A memory-mapped file is created by the :class:`mmap` constructor, which is
19different on Unix and on Windows. In either case you must provide a file
20descriptor for a file opened for update. If you wish to map an existing Python
21file object, use its :meth:`fileno` method to obtain the correct value for the
22*fileno* parameter. Otherwise, you can open the file using the
23:func:`os.open` function, which returns a file descriptor directly (the file
24still needs to be closed when done).
Georg Brandl116aa622007-08-15 14:28:22 +000025
Georg Brandl86def6c2008-01-21 20:36:10 +000026For both the Unix and Windows versions of the constructor, *access* may be
Georg Brandl116aa622007-08-15 14:28:22 +000027specified as an optional keyword parameter. *access* accepts one of three
Christian Heimesdae2a892008-04-19 00:55:37 +000028values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY`
29to specify read-only, write-through or copy-on-write memory respectively.
30*access* can be used on both Unix and Windows. If *access* is not specified,
31Windows mmap returns a write-through mapping. The initial memory values for
32all three access types are taken from the specified file. Assignment to an
33:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception.
34Assignment to an :const:`ACCESS_WRITE` memory map affects both memory and the
35underlying file. Assignment to an :const:`ACCESS_COPY` memory map affects
36memory but does not update the underlying file.
Georg Brandl116aa622007-08-15 14:28:22 +000037
Georg Brandl55ac8f02007-09-01 13:51:09 +000038To map anonymous memory, -1 should be passed as the fileno along with the length.
Georg Brandl116aa622007-08-15 14:28:22 +000039
Georg Brandl86def6c2008-01-21 20:36:10 +000040.. class:: mmap(fileno, length[, tagname[, access[, offset]]])
Georg Brandl116aa622007-08-15 14:28:22 +000041
Christian Heimesdae2a892008-04-19 00:55:37 +000042 **(Windows version)** Maps *length* bytes from the file specified by the
43 file handle *fileno*, and creates a mmap object. If *length* is larger
44 than the current size of the file, the file is extended to contain *length*
45 bytes. If *length* is ``0``, the maximum length of the map is the current
46 size of the file, except that if the file is empty Windows raises an
47 exception (you cannot create an empty mapping on Windows).
Georg Brandl116aa622007-08-15 14:28:22 +000048
Christian Heimesdae2a892008-04-19 00:55:37 +000049 *tagname*, if specified and not ``None``, is a string giving a tag name for
50 the mapping. Windows allows you to have many different mappings against
51 the same file. If you specify the name of an existing tag, that tag is
52 opened, otherwise a new tag of this name is created. If this parameter is
53 omitted or ``None``, the mapping is created without a name. Avoiding the
54 use of the tag parameter will assist in keeping your code portable between
55 Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +000056
Christian Heimesdae2a892008-04-19 00:55:37 +000057 *offset* may be specified as a non-negative integer offset. mmap references
58 will be relative to the offset from the beginning of the file. *offset*
59 defaults to 0. *offset* must be a multiple of the ALLOCATIONGRANULARITY.
Georg Brandl116aa622007-08-15 14:28:22 +000060
Georg Brandl9afde1c2007-11-01 20:32:30 +000061
Georg Brandl86def6c2008-01-21 20:36:10 +000062.. class:: mmap(fileno, length[, flags[, prot[, access[, offset]]]])
Georg Brandl116aa622007-08-15 14:28:22 +000063 :noindex:
64
65 **(Unix version)** Maps *length* bytes from the file specified by the file
66 descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the
Christian Heimesdae2a892008-04-19 00:55:37 +000067 maximum length of the map will be the current size of the file when
68 :class:`mmap` is called.
Georg Brandl116aa622007-08-15 14:28:22 +000069
70 *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
Christian Heimesdae2a892008-04-19 00:55:37 +000071 private copy-on-write mapping, so changes to the contents of the mmap
72 object will be private to this process, and :const:`MAP_SHARED` creates a
73 mapping that's shared with all other processes mapping the same areas of
74 the file. The default value is :const:`MAP_SHARED`.
Georg Brandl116aa622007-08-15 14:28:22 +000075
Christian Heimesdae2a892008-04-19 00:55:37 +000076 *prot*, if specified, gives the desired memory protection; the two most
77 useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify
78 that the pages may be read or written. *prot* defaults to
79 :const:`PROT_READ \| PROT_WRITE`.
Georg Brandl116aa622007-08-15 14:28:22 +000080
Christian Heimesdae2a892008-04-19 00:55:37 +000081 *access* may be specified in lieu of *flags* and *prot* as an optional
82 keyword parameter. It is an error to specify both *flags*, *prot* and
83 *access*. See the description of *access* above for information on how to
84 use this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +000085
Christian Heimesdae2a892008-04-19 00:55:37 +000086 *offset* may be specified as a non-negative integer offset. mmap references
87 will be relative to the offset from the beginning of the file. *offset*
88 defaults to 0. *offset* must be a multiple of the PAGESIZE or
89 ALLOCATIONGRANULARITY.
Christian Heimesd8654cf2007-12-02 15:22:16 +000090
Georg Brandl86def6c2008-01-21 20:36:10 +000091 This example shows a simple way of using :class:`mmap`::
Christian Heimesd8654cf2007-12-02 15:22:16 +000092
93 import mmap
94
95 # write a simple example file
96 with open("hello.txt", "w") as f:
97 f.write("Hello Python!\n")
98
99 with open("hello.txt", "r+") as f:
100 # memory-map the file, size 0 means whole file
101 map = mmap.mmap(f.fileno(), 0)
102 # read content via standard file methods
Georg Brandla09ca382007-12-02 18:20:12 +0000103 print(map.readline()) # prints "Hello Python!"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000104 # read content via slice notation
Georg Brandla09ca382007-12-02 18:20:12 +0000105 print(map[:5]) # prints "Hello"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000106 # update content using slice notation;
107 # note that new content must have same size
108 map[6:] = " world!\n"
109 # ... and read again using standard file methods
110 map.seek(0)
Georg Brandla09ca382007-12-02 18:20:12 +0000111 print(map.readline()) # prints "Hello world!"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000112 # close the map
113 map.close()
114
115
116 The next example demonstrates how to create an anonymous map and exchange
117 data between the parent and child processes::
118
119 import mmap
120 import os
121
122 map = mmap.mmap(-1, 13)
123 map.write("Hello world!")
124
125 pid = os.fork()
126
127 if pid == 0: # In a child process
128 map.seek(0)
Georg Brandla09ca382007-12-02 18:20:12 +0000129 print(map.readline())
Christian Heimesd8654cf2007-12-02 15:22:16 +0000130
131 map.close()
132
Georg Brandl9afde1c2007-11-01 20:32:30 +0000133
Georg Brandl116aa622007-08-15 14:28:22 +0000134Memory-mapped file objects support the following methods:
135
136
137.. method:: mmap.close()
138
Christian Heimesdae2a892008-04-19 00:55:37 +0000139 Close the file. Subsequent calls to other methods of the object will
140 result in an exception being raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142
Georg Brandlfceab5a2008-01-19 20:08:23 +0000143.. method:: mmap.find(string[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Christian Heimesdae2a892008-04-19 00:55:37 +0000145 Returns the lowest index in the object where the substring *string* is
146 found, such that *string* is contained in the range [*start*, *end*].
147 Optional arguments *start* and *end* are interpreted as in slice notation.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000148 Returns ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150
151.. method:: mmap.flush([offset, size])
152
Christian Heimesdae2a892008-04-19 00:55:37 +0000153 Flushes changes made to the in-memory copy of a file back to disk. Without
154 use of this call there is no guarantee that changes are written back before
155 the object is destroyed. If *offset* and *size* are specified, only
156 changes to the given range of bytes will be flushed to disk; otherwise, the
157 whole extent of the mapping is flushed.
158
159 **(Windows version)** A nonzero value returned indicates success; zero
160 indicates failure.
161
162 **(Unix version)** A zero value is returned to indicate success. An
163 exception is raised when the call failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165
166.. method:: mmap.move(dest, src, count)
167
Christian Heimesdae2a892008-04-19 00:55:37 +0000168 Copy the *count* bytes starting at offset *src* to the destination index
169 *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
170 move will throw a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172
173.. method:: mmap.read(num)
174
175 Return a string containing up to *num* bytes starting from the current file
176 position; the file position is updated to point after the bytes that were
177 returned.
178
179
180.. method:: mmap.read_byte()
181
182 Returns a string of length 1 containing the character at the current file
183 position, and advances the file position by 1.
184
185
186.. method:: mmap.readline()
187
Christian Heimesdae2a892008-04-19 00:55:37 +0000188 Returns a single line, starting at the current file position and up to the
189 next newline.
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191
192.. method:: mmap.resize(newsize)
193
Christian Heimesdae2a892008-04-19 00:55:37 +0000194 Resizes the map and the underlying file, if any. If the mmap was created
195 with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
196 throw a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198
Georg Brandlfceab5a2008-01-19 20:08:23 +0000199.. method:: mmap.rfind(string[, start[, end]])
200
201 Returns the highest index in the object where the substring *string* is
Christian Heimesdae2a892008-04-19 00:55:37 +0000202 found, such that *string* is contained in the range [*start*, *end*].
203 Optional arguments *start* and *end* are interpreted as in slice notation.
204 Returns ``-1`` on failure.
Georg Brandlfceab5a2008-01-19 20:08:23 +0000205
206
Georg Brandl116aa622007-08-15 14:28:22 +0000207.. method:: mmap.seek(pos[, whence])
208
Christian Heimesdae2a892008-04-19 00:55:37 +0000209 Set the file's current position. *whence* argument is optional and
210 defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
211 values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current position)
212 and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
215.. method:: mmap.size()
216
217 Return the length of the file, which can be larger than the size of the
218 memory-mapped area.
219
220
221.. method:: mmap.tell()
222
223 Returns the current position of the file pointer.
224
225
226.. method:: mmap.write(string)
227
228 Write the bytes in *string* into memory at the current position of the file
229 pointer; the file position is updated to point after the bytes that were
Christian Heimesdae2a892008-04-19 00:55:37 +0000230 written. If the mmap was created with :const:`ACCESS_READ`, then writing to
231 it will throw a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233
234.. method:: mmap.write_byte(byte)
235
Christian Heimesdae2a892008-04-19 00:55:37 +0000236 Write the single-character string *byte* into memory at the current
237 position of the file pointer; the file position is advanced by ``1``. If
238 the mmap was created with :const:`ACCESS_READ`, then writing to it will
239 throw a :exc:`TypeError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Georg Brandl9afde1c2007-11-01 20:32:30 +0000241