blob: ac1963f5bbe4e1210f6da41c292aa7a1d38d00ed [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
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +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 Brandl8ec7f652007-08-15 14:28:01 +000017
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +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 Brandl8ec7f652007-08-15 14:28:01 +000025
Ross Lagerwall528c4ad2011-07-25 07:23:58 +020026.. note::
27 If you want to create a memory-mapping for a writable, buffered file, you
28 should :func:`~io.IOBase.flush` the file first. This is necessary to ensure
29 that local modifications to the buffers are actually available to the
30 mapping.
31
Georg Brandl845c4032008-01-21 14:16:46 +000032For both the Unix and Windows versions of the constructor, *access* may be
Georg Brandl8ec7f652007-08-15 14:28:01 +000033specified as an optional keyword parameter. *access* accepts one of three
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000034values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY`
Jeroen Ruigrok van der Wervenea7fa722008-04-17 12:39:45 +000035to specify read-only, write-through or copy-on-write memory respectively.
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000036*access* can be used on both Unix and Windows. If *access* is not specified,
37Windows mmap returns a write-through mapping. The initial memory values for
38all three access types are taken from the specified file. Assignment to an
39:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception.
40Assignment to an :const:`ACCESS_WRITE` memory map affects both memory and the
41underlying file. Assignment to an :const:`ACCESS_COPY` memory map affects
42memory but does not update the underlying file.
Georg Brandl8ec7f652007-08-15 14:28:01 +000043
44.. versionchanged:: 2.5
45 To map anonymous memory, -1 should be passed as the fileno along with the
46 length.
47
Georg Brandl845c4032008-01-21 14:16:46 +000048.. versionchanged:: 2.6
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000049 mmap.mmap has formerly been a factory function creating mmap objects. Now
Georg Brandl845c4032008-01-21 14:16:46 +000050 mmap.mmap is the class itself.
Georg Brandl8ec7f652007-08-15 14:28:01 +000051
Georg Brandl845c4032008-01-21 14:16:46 +000052.. class:: mmap(fileno, length[, tagname[, access[, offset]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000054 **(Windows version)** Maps *length* bytes from the file specified by the
55 file handle *fileno*, and creates a mmap object. If *length* is larger
56 than the current size of the file, the file is extended to contain *length*
57 bytes. If *length* is ``0``, the maximum length of the map is the current
58 size of the file, except that if the file is empty Windows raises an
59 exception (you cannot create an empty mapping on Windows).
Georg Brandl8ec7f652007-08-15 14:28:01 +000060
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000061 *tagname*, if specified and not ``None``, is a string giving a tag name for
62 the mapping. Windows allows you to have many different mappings against
63 the same file. If you specify the name of an existing tag, that tag is
64 opened, otherwise a new tag of this name is created. If this parameter is
65 omitted or ``None``, the mapping is created without a name. Avoiding the
66 use of the tag parameter will assist in keeping your code portable between
67 Unix and Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +000068
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000069 *offset* may be specified as a non-negative integer offset. mmap references
70 will be relative to the offset from the beginning of the file. *offset*
71 defaults to 0. *offset* must be a multiple of the ALLOCATIONGRANULARITY.
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
Travis E. Oliphant8feafab2007-10-23 02:40:56 +000073
Georg Brandl845c4032008-01-21 14:16:46 +000074.. class:: mmap(fileno, length[, flags[, prot[, access[, offset]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000075 :noindex:
76
77 **(Unix version)** Maps *length* bytes from the file specified by the file
78 descriptor *fileno*, and returns a mmap object. If *length* is ``0``, the
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000079 maximum length of the map will be the current size of the file when
80 :class:`mmap` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +000081
82 *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000083 private copy-on-write mapping, so changes to the contents of the mmap
84 object will be private to this process, and :const:`MAP_SHARED` creates a
85 mapping that's shared with all other processes mapping the same areas of
86 the file. The default value is :const:`MAP_SHARED`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000087
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000088 *prot*, if specified, gives the desired memory protection; the two most
89 useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify
90 that the pages may be read or written. *prot* defaults to
91 :const:`PROT_READ \| PROT_WRITE`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000093 *access* may be specified in lieu of *flags* and *prot* as an optional
94 keyword parameter. It is an error to specify both *flags*, *prot* and
95 *access*. See the description of *access* above for information on how to
96 use this parameter.
Georg Brandl8ec7f652007-08-15 14:28:01 +000097
Jeroen Ruigrok van der Werven069dfad2008-04-16 12:47:01 +000098 *offset* may be specified as a non-negative integer offset. mmap references
99 will be relative to the offset from the beginning of the file. *offset*
100 defaults to 0. *offset* must be a multiple of the PAGESIZE or
101 ALLOCATIONGRANULARITY.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000102
Victor Stinner112d48a2011-05-03 14:36:36 +0200103 To ensure validity of the created memory mapping the file specified
104 by the descriptor *fileno* is internally automatically synchronized
105 with physical backing store on Mac OS X and OpenVMS.
106
Georg Brandl845c4032008-01-21 14:16:46 +0000107 This example shows a simple way of using :class:`mmap`::
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000108
109 import mmap
110
111 # write a simple example file
Hirokazu Yamamoto02172dd2009-02-28 15:24:00 +0000112 with open("hello.txt", "wb") as f:
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000113 f.write("Hello Python!\n")
114
Hirokazu Yamamoto02172dd2009-02-28 15:24:00 +0000115 with open("hello.txt", "r+b") as f:
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000116 # memory-map the file, size 0 means whole file
Ezio Melotti5e324242013-03-13 02:26:11 +0200117 mm = mmap.mmap(f.fileno(), 0)
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000118 # read content via standard file methods
Ezio Melotti5e324242013-03-13 02:26:11 +0200119 print mm.readline() # prints "Hello Python!"
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000120 # read content via slice notation
Ezio Melotti5e324242013-03-13 02:26:11 +0200121 print mm[:5] # prints "Hello"
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000122 # update content using slice notation;
123 # note that new content must have same size
Ezio Melotti5e324242013-03-13 02:26:11 +0200124 mm[6:] = " world!\n"
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000125 # ... and read again using standard file methods
Ezio Melotti5e324242013-03-13 02:26:11 +0200126 mm.seek(0)
127 print mm.readline() # prints "Hello world!"
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000128 # close the map
Ezio Melotti5e324242013-03-13 02:26:11 +0200129 mm.close()
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000130
131
132 The next example demonstrates how to create an anonymous map and exchange
133 data between the parent and child processes::
134
135 import mmap
136 import os
137
Ezio Melotti5e324242013-03-13 02:26:11 +0200138 mm = mmap.mmap(-1, 13)
139 mm.write("Hello world!")
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000140
141 pid = os.fork()
142
143 if pid == 0: # In a child process
Ezio Melotti5e324242013-03-13 02:26:11 +0200144 mm.seek(0)
145 print mm.readline()
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000146
Ezio Melotti5e324242013-03-13 02:26:11 +0200147 mm.close()
Georg Brandlfefcd4e2007-12-02 14:34:34 +0000148
Travis E. Oliphant8feafab2007-10-23 02:40:56 +0000149
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000150 Memory-mapped file objects support the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151
152
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000153 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000154
Senthil Kumaranb65685f2013-09-09 22:38:58 -0700155 Closes the mmap. Subsequent calls to other methods of the object will
156 result in a ValueError exception being raised. This will not close
157 the open file.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158
159
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000160 .. method:: find(string[, start[, end]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000162 Returns the lowest index in the object where the substring *string* is
163 found, such that *string* is contained in the range [*start*, *end*].
164 Optional arguments *start* and *end* are interpreted as in slice notation.
165 Returns ``-1`` on failure.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166
167
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000168 .. method:: flush([offset, size])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000170 Flushes changes made to the in-memory copy of a file back to disk. Without
171 use of this call there is no guarantee that changes are written back before
172 the object is destroyed. If *offset* and *size* are specified, only
173 changes to the given range of bytes will be flushed to disk; otherwise, the
174 whole extent of the mapping is flushed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000175
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000176 **(Windows version)** A nonzero value returned indicates success; zero
177 indicates failure.
Jeroen Ruigrok van der Werven967a83c2008-04-16 12:57:43 +0000178
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000179 **(Unix version)** A zero value is returned to indicate success. An
180 exception is raised when the call failed.
Jeroen Ruigrok van der Werven967a83c2008-04-16 12:57:43 +0000181
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000183 .. method:: move(dest, src, count)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000185 Copy the *count* bytes starting at offset *src* to the destination index
186 *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
Georg Brandl21946af2010-10-06 09:28:45 +0000187 move will raise a :exc:`TypeError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188
189
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000190 .. method:: read(num)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000192 Return a string containing up to *num* bytes starting from the current
193 file position; the file position is updated to point after the bytes that
194 were returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000195
196
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000197 .. method:: read_byte()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000199 Returns a string of length 1 containing the character at the current file
200 position, and advances the file position by 1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000201
202
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000203 .. method:: readline()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000205 Returns a single line, starting at the current file position and up to the
206 next newline.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000207
208
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000209 .. method:: resize(newsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000210
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000211 Resizes the map and the underlying file, if any. If the mmap was created
212 with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
Georg Brandl21946af2010-10-06 09:28:45 +0000213 raise a :exc:`TypeError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000214
215
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000216 .. method:: rfind(string[, start[, end]])
Andrew M. Kuchling5c60bfc2008-01-19 18:18:41 +0000217
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000218 Returns the highest index in the object where the substring *string* is
219 found, such that *string* is contained in the range [*start*, *end*].
220 Optional arguments *start* and *end* are interpreted as in slice notation.
221 Returns ``-1`` on failure.
Andrew M. Kuchling5c60bfc2008-01-19 18:18:41 +0000222
223
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000224 .. method:: seek(pos[, whence])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000226 Set the file's current position. *whence* argument is optional and
227 defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
228 values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
229 position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000230
231
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000232 .. method:: size()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000233
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000234 Return the length of the file, which can be larger than the size of the
235 memory-mapped area.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000236
237
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000238 .. method:: tell()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000240 Returns the current position of the file pointer.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241
242
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000243 .. method:: write(string)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000245 Write the bytes in *string* into memory at the current position of the
246 file pointer; the file position is updated to point after the bytes that
247 were written. If the mmap was created with :const:`ACCESS_READ`, then
Georg Brandl21946af2010-10-06 09:28:45 +0000248 writing to it will raise a :exc:`TypeError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249
250
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000251 .. method:: write_byte(byte)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000253 Write the single-character string *byte* into memory at the current
254 position of the file pointer; the file position is advanced by ``1``. If
255 the mmap was created with :const:`ACCESS_READ`, then writing to it will
Georg Brandl21946af2010-10-06 09:28:45 +0000256 raise a :exc:`TypeError` exception.