33

Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.

8 Answers 8

45

Here is a function which reads all file attributes as a dictionary:

import win32api

#==============================================================================
def getFileProperties(fname):
#==============================================================================
    """
    Read all properties of the given file return them as a dictionary.
    """
    propNames = ('Comments', 'InternalName', 'ProductName',
        'CompanyName', 'LegalCopyright', 'ProductVersion',
        'FileDescription', 'LegalTrademarks', 'PrivateBuild',
        'FileVersion', 'OriginalFilename', 'SpecialBuild')

    props = {'FixedFileInfo': None, 'StringFileInfo': None, 'FileVersion': None}

    try:
        # backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc
        fixedInfo = win32api.GetFileVersionInfo(fname, '\\')
        props['FixedFileInfo'] = fixedInfo
        props['FileVersion'] = "%d.%d.%d.%d" % (fixedInfo['FileVersionMS'] / 65536,
                fixedInfo['FileVersionMS'] % 65536, fixedInfo['FileVersionLS'] / 65536,
                fixedInfo['FileVersionLS'] % 65536)

        # \VarFileInfo\Translation returns list of available (language, codepage)
        # pairs that can be used to retreive string info. We are using only the first pair.
        lang, codepage = win32api.GetFileVersionInfo(fname, '\\VarFileInfo\\Translation')[0]

        # any other must be of the form \StringfileInfo\%04X%04X\parm_name, middle
        # two are language/codepage pair returned from above

        strInfo = {}
        for propName in propNames:
            strInfoPath = u'\\StringFileInfo\\%04X%04X\\%s' % (lang, codepage, propName)
            ## print str_info
            strInfo[propName] = win32api.GetFileVersionInfo(fname, strInfoPath)

        props['StringFileInfo'] = strInfo
    except:
        pass

    return props
4
  • 3
    Wow, great work. How did you even find out the StringFileInfo stuff.. that's what I need. thanks a lot.
    – iridescent
    Jan 1, 2015 at 13:09
  • 2
    For those who care, 65536 is half a DWORD (2 **16) Aug 8, 2016 at 19:40
  • 1
    This is the best approach to the problem I've found so far. If anyone knows where to find documentation to back this up, it would make a great addition to this answer (I've had a look but couldn't find anything authoritative). May 11, 2020 at 15:48
  • Only works for exe and dll.
    – lovetl2002
    Jun 5, 2022 at 21:12
22

Better to add a try/except in case the file has no version number attribute.

filever.py


from win32api import GetFileVersionInfo, LOWORD, HIWORD

def get_version_number (filename):
    try:
        info = GetFileVersionInfo (filename, "\\")
        ms = info['FileVersionMS']
        ls = info['FileVersionLS']
        return HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls)
    except:
        return 0,0,0,0

if __name__ == '__main__':
  import os
  filename = os.environ["COMSPEC"]
  print ".".join ([str (i) for i in get_version_number (filename)])

yourscript.py:


import os,filever

myPath="C:\\path\\to\\check"

for root, dirs, files in os.walk(myPath):
    for file in files:
        file = file.lower() # Convert .EXE to .exe so next line works
        if (file.count('.exe') or file.count('.dll')): # Check only exe or dll files
            fullPathToFile=os.path.join(root,file)
            major,minor,subminor,revision=filever.get_version_number(fullPathToFile)
            print "Filename: %s \t Version: %s.%s.%s.%s" % (file,major,minor,subminor,revision)

Cheers!

0
15

You can use the pyWin32 module from https://github.com/mhammond/pywin32:

from win32com.client import Dispatch

ver_parser = Dispatch('Scripting.FileSystemObject')
info = ver_parser.GetFileVersion(path)

if info == 'No Version Information Available':
    info = None
4
  • Is there any way I can get the file description as well ? I did not see any method in FileSystemObject which does that :(
    – Dev.K.
    Jun 1, 2017 at 4:18
  • Worked like a charm. Thank you !!
    – Suneelm
    Jan 11, 2018 at 9:10
  • After hours of frustration and struggle with pywin32, looks like all I needed was this....Thank you
    – BeHappy
    May 30, 2019 at 23:46
  • Only works for exe and dll.
    – lovetl2002
    Jun 5, 2022 at 21:13
15

Here is a version that also works in non-Windows environments, using the pefile module:

import pefile

def LOWORD(dword):
    return dword & 0x0000ffff
def HIWORD(dword): 
    return dword >> 16
def get_product_version(path):

    pe = pefile.PE(path)
    #print PE.dump_info()

    ms = pe.VS_FIXEDFILEINFO.ProductVersionMS
    ls = pe.VS_FIXEDFILEINFO.ProductVersionLS
    return (HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls))


if __name__ == "__main__":
    import sys
    try:
        print "%d.%d.%d.%d" % get_product_version(sys.argv[1])
    except:
        print "Version info not available. Maybe the file is not a Windows executable"
4
  • 1
    I find this to the job perfectly, but it takes over 10s to do it on a 30mb exe :(
    – Steve
    Oct 14, 2015 at 8:48
  • 7
    I figured out from the source that you can cut that 10s down to 1s/2s by parsing only the resources directory, woo!: pe = pefile.PE(path, fast_load=True) pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_RESOURCE']])
    – Steve
    Oct 14, 2015 at 13:10
  • Nice! I wanted to suggest something like that.
    – derflocki
    Oct 14, 2015 at 18:04
  • 1
    pe.VS_FIXEDFILEINFO now returns a list, so you need to change to ms = pe.VS_FIXEDFILEINFO[0].ProductVersionMS ls = pe.VS_FIXEDFILEINFO[0].ProductVersionLS Also: Steve's suggestion is a massive improvement speed-wise, and is a simple plug-and-play change to syntaxaire's example. Feb 18, 2020 at 18:25
6

I found that the only cross-platform answer (using pefile) couldn't find the version string I was looking for, which is the one shown in the 'Details' tab of the 'View properties' of a .DLL file on Windows. However, this code, based on the dump_info() function in pefile, is able to find those attributes, which include original filename, copyright, company name, and file and product versions.

You may need to replace encoding with a different encoding if they are not encoded using UTF-8.

import pefile

PATH_TO_FILE = 'C:\...'
pe = pefile.PE(PATH_TO_FILE)

if hasattr(pe, 'VS_VERSIONINFO'):
    for idx in range(len(pe.VS_VERSIONINFO)):
        if hasattr(pe, 'FileInfo') and len(pe.FileInfo) > idx:
            for entry in pe.FileInfo[idx]:
                if hasattr(entry, 'StringTable'):
                    for st_entry in entry.StringTable:
                        for str_entry in sorted(list(st_entry.entries.items())):
                            print('{0}: {1}'.format(
                                str_entry[0].decode('utf-8', 'backslashreplace'),
                                str_entry[1].decode('utf-8', 'backslashreplace')))
5

Here's a working version of marsh's answer, only using the standard library. Use it like get_version_string(file, "FileVersion"). See VerQueryValueW() for the valid version strings.

from ctypes import *

# returns the requested version information from the given file
#
# `what` is one of the predefined version information strings, such as
# "FileVersion" or "CompanyName"
#
# `language` should be an 8-character string combining both the language and
# codepage (such as "040904b0"); if None, the first language in the translation
# table is used instead
#
def get_version_string(filename, what, language=None):
    # VerQueryValue() returns an array of that for VarFileInfo\Translation
    #
    class LANGANDCODEPAGE(Structure):
        _fields_ = [
            ("wLanguage", c_uint16),
            ("wCodePage", c_uint16)]

    wstr_file = wstring_at(filename)

    # getting the size in bytes of the file version info buffer
    size = windll.version.GetFileVersionInfoSizeW(wstr_file, None)
    if size == 0:
        raise WinError()

    buffer = create_string_buffer(size)

    # getting the file version info data
    if windll.version.GetFileVersionInfoW(wstr_file, None, size, buffer) == 0:
        raise WinError()

    # VerQueryValue() wants a pointer to a void* and DWORD; used both for
    # getting the default language (if necessary) and getting the actual data
    # below
    value = c_void_p(0)
    value_size = c_uint(0)

    if language is None:
        # file version information can contain much more than the version
        # number (copyright, application name, etc.) and these are all
        # translatable
        #
        # the following arbitrarily gets the first language and codepage from
        # the list
        ret = windll.version.VerQueryValueW(
            buffer, wstring_at(r"\VarFileInfo\Translation"),
            byref(value), byref(value_size))

        if ret == 0:
            raise WinError()

        # value points to a byte inside buffer, value_size is the size in bytes
        # of that particular section

        # casting the void* to a LANGANDCODEPAGE*
        lcp = cast(value, POINTER(LANGANDCODEPAGE))

        # formatting language and codepage to something like "040904b0"
        language = "{0:04x}{1:04x}".format(
            lcp.contents.wLanguage, lcp.contents.wCodePage)

    # getting the actual data
    res = windll.version.VerQueryValueW(
        buffer, wstring_at("\\StringFileInfo\\" + language + "\\" + what),
        byref(value), byref(value_size))

    if res == 0:
        raise WinError()

    # value points to a string of value_size characters, minus one for the
    # terminating null
    return wstring_at(value.value, value_size.value - 1)
2
  • 1
    At return you can pass (value_size.value -1) because now you get one null character at the end of string. Jun 13, 2019 at 8:44
  • Works very well, thank you. I don't understand why something like this is not part of the standard library. It shouldn't be necessary to load extra modules or write elaborate functions just to perform basic file operations!
    – Waterman
    Jan 27, 2022 at 9:27
4

I found this solution at "timgolden" site. Works fine.

from win32api import GetFileVersionInfo, LOWORD, HIWORD

def get_version_number (filename):
  info = GetFileVersionInfo (filename, "\\")
  ms = info['FileVersionMS']
  ls = info['FileVersionLS']
  return HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls)

if __name__ == '__main__':
  import os
  filename = os.environ["COMSPEC"]
  print ".".join ([str (i) for i in get_version_number (filename)])
2
  • Nice! Though this requires you to install pywin32
    – Zimano
    Mar 9, 2020 at 19:07
  • NameError: name 'HIWORD' is not defined
    – evandrix
    May 27, 2020 at 17:43
0

Here is a version that does not require any additional libraries. I could not use win32api like everyone had suggested:

From: https://mail.python.org/pipermail//python-list/2006-November/402797.html

Only copied here in case the original goes missing.

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)

Used like so:

   print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion')
1
  • WindowsError: exception: access violation reading 0x0000000082E47858 when getting the codepages. string_at(r.value, l.value) fails there :(
    – ewerybody
    Nov 6, 2017 at 19:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.