[Tutor] How to create memory backed file?

Modulok modulok at gmail.com
Sun Dec 27 09:36:38 CET 2009


List,

How do I create a file which exists only in memory? (Think diskless.)

I need to create an in-memory file. I need to pass this file, as a
regular file object, to a subprocess. Unfortunately, the 'mmap'
module's file-like object doesn't appear to work quite like a regular
file would. (I simply assume that mmap would be the way to go. Other
suggestions welcome!) That, or I'm doing something terribly wrong. For
example:

import mmap
import sys
from subprocess import Popen, PIPE

fishes = "one fish\ntwo fish\nred fish\nblue fish\n"

#######################################
# With a real file, this works:
#######################################
fd = open('fish.txt', 'w')
fd.write(fishes)
fd = open('fish.txt', 'r')
proc1 = Popen(['cat'], stdin=fd, stdout=sys.stdout, stderr=sys.stderr)

#######################################
# This doesn't (with mmap file):
#######################################
vfd = mmap.mmap(-1, len(fishes), mmap.MAP_PRIVATE)
vfd.write(fishes)
vfd.seek(0)
proc2 = Popen(['cat'], stdin=vfd.fileno(), stdout=sys.stdout, stderr=sys.stderr)

I just get the following error:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: fileno


I'm using Python 2.5, so I cannot use that slick
'SpooledTemporaryFile' method of the 'tempfile' module. The 'cat' is
just a simple Unix system command for the purpose of illustration.

Thanks!
-Modulok-


More information about the Tutor mailing list