Using ctypes with Windows API to get FileVersion of a file

looping kadeko at gmail.com
Tue Nov 14 06:16:24 EST 2006


Hi,
I need to get the FileVersion of some files on Windows. The best way
look like to use function GetFileVersionInfo from the Windows API. I
first try with pywin32 and it work well, but with ctypes now included
in Python 2.5, use it look like a good idea.
So I write the code below that work fine, but I'm not sure it's the
best way to do what I want.
My main concern is about the codepages extraction: could I use a struct
to make the job ?
Codepages is actually an array of struct, how could I use ctypes to
extract it ?

Thanks for your comments and advices.

import array
from ctypes import *

def get_file_info(filename, info):
    """
    Extract information from a file.
    """
    # Get size needed for buffer (0 if no info)
    size = windll.version.GetFileVersionInfoSizeA(filename, None)
    # If no info in file -> empty string
    if not size:
        return ''
    # Create buffer
    res = create_string_buffer(size)
    # Load file informations into buffer res
    windll.version.GetFileVersionInfoA(filename, None, size, res)
    r = c_uint()
    l = c_uint()
    # Look for codepages
    windll.version.VerQueryValueA(res, '\\VarFileInfo\\Translation',
                                  byref(r), byref(l))
    # If no codepage -> empty string
    if not l.value:
        return ''
    # Take the first codepage (what else ?)
    codepages = array.array('H', string_at(r.value, l.value))
    codepage = tuple(codepages[:2].tolist())
    # Extract information
    windll.version.VerQueryValueA(res, ('\\StringFileInfo\\%04x%04x\\'
+ info) % codepage,
                                        byref(r), byref(l))
    return string_at(r.value, l.value)
    
print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion')




More information about the Python-list mailing list