PyWin32: How to Get an Application’s Version Number

Occasionally you will need to know what version of software you are using. The normal way to find this information out is usually done by opening the program, going to its Help menu and clicking the About menu item. But this is a Python blog and we want to do it programmatically! To do that on a Windows machine, we need PyWin32. In this article, we’ll look at two different methods of getting the version number of an application.


Getting the Version with win32api

First off, we’ll get the version number using PyWin32’s win32api module. It’s actually quite easy to use. Let’s take a look:

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 "Unknown version"

if __name__ == "__main__":
    version = ".".join([str (i) for i in get_version_number (
        r'C:\Program Files\Internet Explorer\iexplore.exe')])
    print version

Here we call GetFileVersionInfo with a path and then attempt to parse the result. If we cannot parse it, then that means that the method didn’t return us anything useful and that will cause an exception to be raised. We catch the exception and just return a string that tells us we couldn’t find a version number. For this example, we check to see what version of Internet Explorer is installed.


Getting the Version with win32com

To make things more interesting, in the following example we check Google Chrome’s version number using PyWin32’s win32com module. Let’s take a look:

# based on http://stackoverflow.com/questions/580924/python-windows-file-version-attribute
from win32com.client import Dispatch

def get_version_via_com(filename):
    parser = Dispatch("Scripting.FileSystemObject")
    version = parser.GetFileVersion(filename)
    return version

if __name__ == "__main__":
    path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    print get_version_via_com(path)

All we do here is import win32com’s Dispatch class and create an instance of that class. Next we call its GetFileVersion method and pass it the path to our executable. Finally we return the result which will be either the number or a message saying that no version information was available. I like this second method a bit more in that it automatically returns a message when no version information was found.


Wrapping Up

Now you know how to check an application version number on Windows. This can be helpful if you need to check if key software needs to be upgraded or perhaps you need to make sure it hasn’t been upgraded because some other application requires the older version.


Related Reading