blob: 8ec988527d0b2b884d4257a1efb81f55ae435f35 [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
11objects in most places where strings are expected; for example, you can use the
12:mod:`re` module to search through a memory-mapped file. Since they're mutable,
13you can change a single character by doing ``obj[index] = 'a'``, or change a
14substring by assigning to a slice: ``obj[i1:i2] = '...'``. You can also read
15and write data starting at the current file position, and :meth:`seek` through
16the file to different positions.
17
Georg Brandl86def6c2008-01-21 20:36:10 +000018A memory-mapped file is created by the :class:`mmap` constructor, which is different
Georg Brandl116aa622007-08-15 14:28:22 +000019on Unix and on Windows. In either case you must provide a file descriptor for a
20file opened for update. If you wish to map an existing Python file object, use
21its :meth:`fileno` method to obtain the correct value for the *fileno*
22parameter. Otherwise, you can open the file using the :func:`os.open` function,
23which returns a file descriptor directly (the file still needs to be closed when
24done).
25
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
28values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` to
29specify readonly, write-through or copy-on-write memory respectively. *access*
30can be used on both Unix and Windows. If *access* is not specified, Windows
31mmap returns a write-through mapping. The initial memory values for all three
32access types are taken from the specified file. Assignment to an
33:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception. Assignment
34to an :const:`ACCESS_WRITE` memory map affects both memory and the underlying
35file. Assignment to an :const:`ACCESS_COPY` memory map affects memory but does
36not update the underlying file.
37
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
42 **(Windows version)** Maps *length* bytes from the file specified by the file
Georg Brandl86def6c2008-01-21 20:36:10 +000043 handle *fileno*, and creates a mmap object. If *length* is larger than the
Georg Brandl116aa622007-08-15 14:28:22 +000044 current size of the file, the file is extended to contain *length* bytes. If
45 *length* is ``0``, the maximum length of the map is the current size of the
46 file, except that if the file is empty Windows raises an exception (you cannot
47 create an empty mapping on Windows).
48
49 *tagname*, if specified and not ``None``, is a string giving a tag name for the
50 mapping. Windows allows you to have many different mappings against the same
51 file. If you specify the name of an existing tag, that tag is opened, otherwise
52 a new tag of this name is created. If this parameter is omitted or ``None``,
53 the mapping is created without a name. Avoiding the use of the tag parameter
54 will assist in keeping your code portable between Unix and Windows.
55
Georg Brandl9afde1c2007-11-01 20:32:30 +000056 *offset* may be specified as a non-negative integer offset. mmap references will
57 be relative to the offset from the beginning of the file. *offset* defaults to 0.
58 *offset* must be a multiple of the ALLOCATIONGRANULARITY.
Georg Brandl116aa622007-08-15 14:28:22 +000059
Georg Brandl9afde1c2007-11-01 20:32:30 +000060
Georg Brandl86def6c2008-01-21 20:36:10 +000061.. class:: mmap(fileno, length[, flags[, prot[, access[, offset]]]])
Georg Brandl116aa622007-08-15 14:28:22 +000062 :noindex:
63
64 **(Unix version)** Maps *length* bytes from the file specified by the file
65 descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the
Georg Brandl86def6c2008-01-21 20:36:10 +000066 maximum length of the map will be the current size of the file when :class:`mmap`
Georg Brandl116aa622007-08-15 14:28:22 +000067 is called.
68
69 *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
70 private copy-on-write mapping, so changes to the contents of the mmap object
71 will be private to this process, and :const:`MAP_SHARED` creates a mapping
72 that's shared with all other processes mapping the same areas of the file. The
73 default value is :const:`MAP_SHARED`.
74
75 *prot*, if specified, gives the desired memory protection; the two most useful
76 values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify that the pages
77 may be read or written. *prot* defaults to :const:`PROT_READ \| PROT_WRITE`.
78
79 *access* may be specified in lieu of *flags* and *prot* as an optional keyword
80 parameter. It is an error to specify both *flags*, *prot* and *access*. See
81 the description of *access* above for information on how to use this parameter.
82
Georg Brandl9afde1c2007-11-01 20:32:30 +000083 *offset* may be specified as a non-negative integer offset. mmap references will
84 be relative to the offset from the beginning of the file. *offset* defaults to 0.
85 *offset* must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY.
Christian Heimesd8654cf2007-12-02 15:22:16 +000086
Georg Brandl86def6c2008-01-21 20:36:10 +000087 This example shows a simple way of using :class:`mmap`::
Christian Heimesd8654cf2007-12-02 15:22:16 +000088
89 import mmap
90
91 # write a simple example file
92 with open("hello.txt", "w") as f:
93 f.write("Hello Python!\n")
94
95 with open("hello.txt", "r+") as f:
96 # memory-map the file, size 0 means whole file
97 map = mmap.mmap(f.fileno(), 0)
98 # read content via standard file methods
Georg Brandla09ca382007-12-02 18:20:12 +000099 print(map.readline()) # prints "Hello Python!"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000100 # read content via slice notation
Georg Brandla09ca382007-12-02 18:20:12 +0000101 print(map[:5]) # prints "Hello"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000102 # update content using slice notation;
103 # note that new content must have same size
104 map[6:] = " world!\n"
105 # ... and read again using standard file methods
106 map.seek(0)
Georg Brandla09ca382007-12-02 18:20:12 +0000107 print(map.readline()) # prints "Hello world!"
Christian Heimesd8654cf2007-12-02 15:22:16 +0000108 # close the map
109 map.close()
110
111
112 The next example demonstrates how to create an anonymous map and exchange
113 data between the parent and child processes::
114
115 import mmap
116 import os
117
118 map = mmap.mmap(-1, 13)
119 map.write("Hello world!")
120
121 pid = os.fork()
122
123 if pid == 0: # In a child process
124 map.seek(0)
Georg Brandla09ca382007-12-02 18:20:12 +0000125 print(map.readline())
Christian Heimesd8654cf2007-12-02 15:22:16 +0000126
127 map.close()
128
Georg Brandl9afde1c2007-11-01 20:32:30 +0000129
Georg Brandl116aa622007-08-15 14:28:22 +0000130Memory-mapped file objects support the following methods:
131
132
133.. method:: mmap.close()
134
135 Close the file. Subsequent calls to other methods of the object will result in
136 an exception being raised.
137
138
Georg Brandlfceab5a2008-01-19 20:08:23 +0000139.. method:: mmap.find(string[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Georg Brandlfceab5a2008-01-19 20:08:23 +0000141 Returns the lowest index in the object where the substring *string* is found,
142 such that *string* is contained in the range [*start*, *end*]. Optional
143 arguments *start* and *end* are interpreted as in slice notation.
144 Returns ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146
147.. method:: mmap.flush([offset, size])
148
149 Flushes changes made to the in-memory copy of a file back to disk. Without use
150 of this call there is no guarantee that changes are written back before the
151 object is destroyed. If *offset* and *size* are specified, only changes to the
152 given range of bytes will be flushed to disk; otherwise, the whole extent of the
153 mapping is flushed.
154
155
156.. method:: mmap.move(dest, src, count)
157
158 Copy the *count* bytes starting at offset *src* to the destination index *dest*.
159 If the mmap was created with :const:`ACCESS_READ`, then calls to move will throw
160 a :exc:`TypeError` exception.
161
162
163.. method:: mmap.read(num)
164
165 Return a string containing up to *num* bytes starting from the current file
166 position; the file position is updated to point after the bytes that were
167 returned.
168
169
170.. method:: mmap.read_byte()
171
172 Returns a string of length 1 containing the character at the current file
173 position, and advances the file position by 1.
174
175
176.. method:: mmap.readline()
177
178 Returns a single line, starting at the current file position and up to the next
179 newline.
180
181
182.. method:: mmap.resize(newsize)
183
184 Resizes the map and the underlying file, if any. If the mmap was created with
185 :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will throw a
186 :exc:`TypeError` exception.
187
188
Georg Brandlfceab5a2008-01-19 20:08:23 +0000189.. method:: mmap.rfind(string[, start[, end]])
190
191 Returns the highest index in the object where the substring *string* is
192 found, such that *string* is contained in the range [*start*,
193 *end*]. Optional arguments *start* and *end* are interpreted as in slice
194 notation. Returns ``-1`` on failure.
195
196
Georg Brandl116aa622007-08-15 14:28:22 +0000197.. method:: mmap.seek(pos[, whence])
198
199 Set the file's current position. *whence* argument is optional and defaults to
200 ``os.SEEK_SET`` or ``0`` (absolute file positioning); other values are
201 ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) and
202 ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
203
204
205.. method:: mmap.size()
206
207 Return the length of the file, which can be larger than the size of the
208 memory-mapped area.
209
210
211.. method:: mmap.tell()
212
213 Returns the current position of the file pointer.
214
215
216.. method:: mmap.write(string)
217
218 Write the bytes in *string* into memory at the current position of the file
219 pointer; the file position is updated to point after the bytes that were
220 written. If the mmap was created with :const:`ACCESS_READ`, then writing to it
221 will throw a :exc:`TypeError` exception.
222
223
224.. method:: mmap.write_byte(byte)
225
226 Write the single-character string *byte* into memory at the current position of
227 the file pointer; the file position is advanced by ``1``. If the mmap was
228 created with :const:`ACCESS_READ`, then writing to it will throw a
229 :exc:`TypeError` exception.
230
Georg Brandl9afde1c2007-11-01 20:32:30 +0000231