bdew
bdew

Reputation: 1330

How to get a win32 handle of an open file in python?

I'm sure this is documented somewhere but i can't find it...

My code is getting a python object from another library (that i can't modify), and i need to call some win32 api functions on it.

Python returns something that isn't the os-level handle from file.fileno(), my guess is that it gives MSVCRT's fileno.

>>> ctypes.windll.kernel32.CreateFileA('test',0x80000000L,1,None,3,0,0)
1948 # <- HANDLE

>>> file('test','r').fileno()
4 # <- not a HANDLE

How do i convert it into a real win32 handle?

Upvotes: 10

Views: 5869

Answers (2)

Gabe
Gabe

Reputation: 86768

win32file._get_osfhandle from the PyWin32 library will return what you want. win32file._get_osfhandle(a.fileno()) returns the same thing as msvcrt.get_osfhandle(a.fileno()) in my testing.

Upvotes: 4

bdew
bdew

Reputation: 1330

I found the answer:

>>> msvcrt.get_osfhandle(a.fileno())
1956 # valid HANDLE

This is actually documented on http://docs.python.org/library/msvcrt.html , no idea how i missed it.

Upvotes: 12

Related Questions