Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

winapi

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?

like image 741
bdew Avatar asked May 26 '11 08:05

bdew


2 Answers

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.

like image 131
bdew Avatar answered Nov 12 '22 22:11

bdew


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.

like image 34
Gabe Avatar answered Nov 12 '22 22:11

Gabe