blob: 70344575b6198c09b7c0d5c872a0cd1fe871f5e7 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Brandl845c4032008-01-21 14:16:46 +000018A memory-mapped file is created by the :class:`mmap` constructor, which is different
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Brandl845c4032008-01-21 14:16:46 +000026For both the Unix and Windows versions of the constructor, *access* may be
Georg Brandl8ec7f652007-08-15 14:28:01 +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
38.. versionchanged:: 2.5
39 To map anonymous memory, -1 should be passed as the fileno along with the
40 length.
41
Georg Brandl845c4032008-01-21 14:16:46 +000042.. versionchanged:: 2.6
43 mmap.mmap has formerly been a factory function creating mmap objects. Now
44 mmap.mmap is the class itself.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
Georg Brandl845c4032008-01-21 14:16:46 +000046.. class:: mmap(fileno, length[, tagname[, access[, offset]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000047
48 **(Windows version)** Maps *length* bytes from the file specified by the file
Georg Brandl845c4032008-01-21 14:16:46 +000049 handle *fileno*, and creates a mmap object. If *length* is larger than the
Georg Brandl8ec7f652007-08-15 14:28:01 +000050 current size of the file, the file is extended to contain *length* bytes. If
51 *length* is ``0``, the maximum length of the map is the current size of the
52 file, except that if the file is empty Windows raises an exception (you cannot
53 create an empty mapping on Windows).
54
55 *tagname*, if specified and not ``None``, is a string giving a tag name for the
56 mapping. Windows allows you to have many different mappings against the same
57 file. If you specify the name of an existing tag, that tag is opened, otherwise
58 a new tag of this name is created. If this parameter is omitted or ``None``,
59 the mapping is created without a name. Avoiding the use of the tag parameter
60 will assist in keeping your code portable between Unix and Windows.
61
Travis E. Oliphant8feafab2007-10-23 02:40:56 +000062 *offset* may be specified as a non-negative integer offset. mmap references will
63 be relative to the offset from the beginning of the file. *offset* defaults to 0.
64 *offset* must be a multiple of the ALLOCATIONGRANULARITY.
Georg Brandl8ec7f652007-08-15 14:28:01 +000065
Travis E. Oliphant8feafab2007-10-23 02:40:56 +000066
Georg Brandl845c4032008-01-21 14:16:46 +000067.. class:: mmap(fileno, length[, flags[, prot[, access[, offset]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000068 :noindex:
69
70 **(Unix version)** Maps *length* bytes from the file specified by the file
71 descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the
Georg Brandl845c4032008-01-21 14:16:46 +000072 maximum length of the map will be the current size of the file when :class:`mmap`
Georg Brandl8ec7f652007-08-15 14:28:01 +000073 is called.
74
75 *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
76 private copy-on-write mapping, so changes to the contents of the mmap object
77 will be private to this process, and :const:`MAP_SHARED` creates a mapping
78 that's shared with all other processes mapping the same areas of the file. The
79 default value is :const:`MAP_SHARED`.
80
81 *prot*, if specified, gives the desired memory protection; the two most useful
82 values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify that the pages
83 may be read or written. *prot* defaults to :const:`PROT_READ \| PROT_WRITE`.
84
85 *access* may be specified in lieu of *flags* and *prot* as an optional keyword
86 parameter. It is an error to specify both *flags*, *prot* and *access*. See
87 the description of *access* above for information on how to use this parameter.
88
Travis E. Oliphant8feafab2007-10-23 02:40:56 +000089 *offset* may be specified as a non-negative integer offset. mmap references will
90 be relative to the offset from the beginning of the file. *offset* defaults to 0.
91 *offset* must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY.
Georg Brandlfefcd4e2007-12-02 14:34:34 +000092
Georg Brandl845c4032008-01-21 14:16:46 +000093 This example shows a simple way of using :class:`mmap`::
Georg Brandlfefcd4e2007-12-02 14:34:34 +000094
95 import mmap
96
97 # write a simple example file
98 with open("hello.txt", "w") as f:
99 f.write("Hello Python!\n")
100
101 with open("hello.txt", "r+") as f:
102 # memory-map the file, size 0 means whole file
103 map = mmap.mmap(f.fileno(), 0)
104 # read content via standard file methods
105 print map.readline() # prints "Hello Python!"
106 # read content via slice notation
107 print map[:5] # prints "Hello"
108 # update content using slice notation;
109 # note that new content must have same size
110 map[6:] = " world!\n"
111 # ... and read again using standard file methods
112 map.seek(0)
113 print map.readline() # prints "Hello world!"
114 # close the map
115 map.close()
116
117
118 The next example demonstrates how to create an anonymous map and exchange
119 data between the parent and child processes::
120
121 import mmap
122 import os
123
124 map = mmap.mmap(-1, 13)
125 map.write("Hello world!")
126
127 pid = os.fork()
128
129 if pid == 0: # In a child process
130 map.seek(0)
131 print map.readline()
132
133 map.close()
134
Travis E. Oliphant8feafab2007-10-23 02:40:56 +0000135
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136Memory-mapped file objects support the following methods:
137
138
139.. method:: mmap.close()
140
141 Close the file. Subsequent calls to other methods of the object will result in
142 an exception being raised.
143
144
Andrew M. Kuchling5c60bfc2008-01-19 18:18:41 +0000145.. method:: mmap.find(string[, start[, end]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146
Andrew M. Kuchling5c60bfc2008-01-19 18:18:41 +0000147 Returns the lowest index in the object where the substring *string* is found,
148 such that *string* is contained in the range [*start*, *end*]. Optional
149 arguments *start* and *end* are interpreted as in slice notation.
150 Returns ``-1`` on failure.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151
152
153.. method:: mmap.flush([offset, size])
154
155 Flushes changes made to the in-memory copy of a file back to disk. Without use
156 of this call there is no guarantee that changes are written back before the
157 object is destroyed. If *offset* and *size* are specified, only changes to the
158 given range of bytes will be flushed to disk; otherwise, the whole extent of the
159 mapping is flushed.
160
161
162.. method:: mmap.move(dest, src, count)
163
164 Copy the *count* bytes starting at offset *src* to the destination index *dest*.
165 If the mmap was created with :const:`ACCESS_READ`, then calls to move will throw
166 a :exc:`TypeError` exception.
167
168
169.. method:: mmap.read(num)
170
171 Return a string containing up to *num* bytes starting from the current file
172 position; the file position is updated to point after the bytes that were
173 returned.
174
175
176.. method:: mmap.read_byte()
177
178 Returns a string of length 1 containing the character at the current file
179 position, and advances the file position by 1.
180
181
182.. method:: mmap.readline()
183
184 Returns a single line, starting at the current file position and up to the next
185 newline.
186
187
188.. method:: mmap.resize(newsize)
189
190 Resizes the map and the underlying file, if any. If the mmap was created with
191 :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will throw a
192 :exc:`TypeError` exception.
193
194
Andrew M. Kuchling5c60bfc2008-01-19 18:18:41 +0000195.. method:: mmap.rfind(string[, start[, end]])
196
197 Returns the highest index in the object where the substring *string* is
198 found, such that *string* is contained in the range [*start*,
199 *end*]. Optional arguments *start* and *end* are interpreted as in slice
200 notation. Returns ``-1`` on failure.
201
202
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203.. method:: mmap.seek(pos[, whence])
204
205 Set the file's current position. *whence* argument is optional and defaults to
206 ``os.SEEK_SET`` or ``0`` (absolute file positioning); other values are
207 ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) and
208 ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
209
210
211.. method:: mmap.size()
212
213 Return the length of the file, which can be larger than the size of the
214 memory-mapped area.
215
216
217.. method:: mmap.tell()
218
219 Returns the current position of the file pointer.
220
221
222.. method:: mmap.write(string)
223
224 Write the bytes in *string* into memory at the current position of the file
225 pointer; the file position is updated to point after the bytes that were
226 written. If the mmap was created with :const:`ACCESS_READ`, then writing to it
227 will throw a :exc:`TypeError` exception.
228
229
230.. method:: mmap.write_byte(byte)
231
232 Write the single-character string *byte* into memory at the current position of
233 the file pointer; the file position is advanced by ``1``. If the mmap was
234 created with :const:`ACCESS_READ`, then writing to it will throw a
235 :exc:`TypeError` exception.
236
Travis E. Oliphant8feafab2007-10-23 02:40:56 +0000237