summaryrefslogtreecommitdiffstats
path: root/Doc/library
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2007-12-02 14:34:34 (GMT)
committerGeorg Brandl <georg@python.org>2007-12-02 14:34:34 (GMT)
commitfefcd4ec405d444374cce2105b62e20344aa1240 (patch)
tree127d8dc1bacf2a5d3f68ea05c3148b72a92318d5 /Doc/library
parent87983f24cfc529415dbea96105f597d6592324b4 (diff)
downloadcpython-fefcd4ec405d444374cce2105b62e20344aa1240.zip
cpython-fefcd4ec405d444374cce2105b62e20344aa1240.tar.gz
cpython-fefcd4ec405d444374cce2105b62e20344aa1240.tar.bz2
Add example to mmap docs.
Written for GHOP by Rafal Rawicki.
Diffstat (limited to 'Doc/library')
-rw-r--r--Doc/library/mmap.rst43
1 files changed, 43 insertions, 0 deletions
diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst
index 0e982c1..070ce4f 100644
--- a/Doc/library/mmap.rst
+++ b/Doc/library/mmap.rst
@@ -86,6 +86,49 @@ not update the underlying file.
*offset* may be specified as a non-negative integer offset. mmap references will
be relative to the offset from the beginning of the file. *offset* defaults to 0.
*offset* must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY.
+
+ This example shows a simple way of using :func:`mmap`::
+
+ import mmap
+
+ # write a simple example file
+ with open("hello.txt", "w") as f:
+ f.write("Hello Python!\n")
+
+ with open("hello.txt", "r+") as f:
+ # memory-map the file, size 0 means whole file
+ map = mmap.mmap(f.fileno(), 0)
+ # read content via standard file methods
+ print map.readline() # prints "Hello Python!"
+ # read content via slice notation
+ print map[:5] # prints "Hello"
+ # update content using slice notation;
+ # note that new content must have same size
+ map[6:] = " world!\n"
+ # ... and read again using standard file methods
+ map.seek(0)
+ print map.readline() # prints "Hello world!"
+ # close the map
+ map.close()
+
+
+ The next example demonstrates how to create an anonymous map and exchange
+ data between the parent and child processes::
+
+ import mmap
+ import os
+
+ map = mmap.mmap(-1, 13)
+ map.write("Hello world!")
+
+ pid = os.fork()
+
+ if pid == 0: # In a child process
+ map.seek(0)
+ print map.readline()
+
+ map.close()
+
Memory-mapped file objects support the following methods: