How to receive a FILE* from Python under MinGW?

Gabriel Genellina gagsl-py2 at
Fri Mar 23 09:48:39 CET 2007

En Fri, 23 Mar 2007 01:47:22 -0300, John Pye <john.pye at> escribió:

> On Mar 23, 3:33 pm, "Gabriel Genellina" <gagsl-... at>
> wrote:
>> import msvcrt
>> fh = msvcrt.get_osfhandle(f.fileno())
> ..
>> example.filetest(fh)
>> f.close()
> Cool, that looks great, Gabriel.
> But is there any way I can hide the get_osfhandle call inside my
> Python module? That way I wouldn't need to request end users to make
> contorted 'if platform.system()=="Windows"' calls everywhere.
> Maybe this *is* workable, after all :-)

I can think of two ways:

- Define a Python function to do that, and test the platform just there.  
Something like that:

def exportable_file(f):
   if we_are_working_on_windows:
     import msvcrt
     return msvcrt.get_osfhandle(f.fileno())
     return f

And replace all places where a Python file goes into a C extension, with  

- Define your own file class, inheriting from file, and store that handle  
as an attribute

class my_file_class(file):
   def __init__(self, name, mode="r", buffering=-1):
     file.__init__(self, name, mode, buffering)
     self.handle = msvcrt.get_osfhandle(self.fileno())

But I've not checked this; I'm not sure if file creation always goes thru  
this __init__; I assume the file will never change its FILE struct (f_fp  
member) (uhm, is there any way to re-open a file?). Perhaps this approach  
has many assumptions to be usable at all - uh, forget it.

Gabriel Genellina

More information about the Python-list mailing list