Help! File objects and scoping

bens bs343 at you-know-where.ac.uk
Tue Jun 7 19:42:01 EDT 2005


I'm trying to return an 'mmap' object from a function.  The return
works, but some of the object's methods crash.  Here are two examples

doesntwork.py
---------------------------
import mmap
import os

name="/any/real/file/on/my/hard/drive"

def getfile(name):
    somefile=file(name, 'r+b')
    mmapped = mmap.mmap(fileno=somefile.fileno(), \
length=os.path.getsize(name))
    return mmapped

mmapped=getfile(name)
mmapped.seek(1)   #this works, so mmapped is a working mmap object
print mmapped.size()  #this dies with an error
mmapped.close()
--------------------------

doesntwork.py dies with the error:
EnvironmentError: [Errno 9] Bad file descriptor

On the other hand,
doeswork.py
---------------------------
import mmap
import os

name="/the/exact/same/file"

somefile=file(name, 'r+b')
mmapped = mmap.mmap(fileno=somefile.fileno(), \
length=os.path.getsize(name))

mmapped.seek(1)     #works fine
print mmapped.size()  #works fine, prints out the right number
mmapped.close()
--------------------------

The only difference between doeswork and doesntwork is whether 'mmapped'
is created in the global scope or created in a local scope and returned.
 Why does that make a difference?

The strangest thing about this, I think, is that the error printed out
above, EnvironmentError, is listed in the docs under "only used as base
classes for other exceptions".  In other words, it's never supposed to
be thrown.

I'll take any advice you can give me.
Thanks,
Ben Schwartz
www.mit.edu/~bens/



More information about the Python-list mailing list