33

上次我问了一个类似的问题,但那是关于 svn 相关的版本信息。现在我想知道如何查询窗口“文件版本”属性,例如。一个dll。我也关注 wmi 和 win32file 模块,但没有成功。

4

8 回答 8

45

这是一个将所有文件属性作为字典读取的函数:

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
于 2011-11-03T10:08:02.510 回答
21

最好添加一个 try/except 以防文件没有版本号属性。

文件版本.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)])

你的脚本.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)

干杯!

于 2009-08-06T08:34:19.903 回答
15

这是一个使用pefile模块也适用于非 Windows 环境的版本:

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"
于 2013-04-18T07:11:09.167 回答
14

您可以使用pyWin32来自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
于 2010-02-22T10:06:42.857 回答
4

我在“timgolden”网站上找到了这个解决方案。工作正常。

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)])
于 2009-02-27T13:40:42.960 回答
4

我发现唯一的跨平台答案(使用pefile)找不到我正在寻找的版本字符串,这是在 Windows 上的 .DLL 文件的“查看属性”的“详细信息”选项卡中显示的那个。但是,此代码基于 中的dump_info()函数pefile,能够找到这些属性,包括原始文件名、版权、公司名称以及文件和产品版本。

encoding如果它们不是使用 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')))
于 2019-10-04T18:06:00.023 回答
3

这是沼泽答案的工作版本,仅使用标准库。像使用它get_version_string(file, "FileVersion")

from ctypes import *

# returns the requested version information from the given file
#
# `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)
于 2019-05-22T23:13:49.173 回答
0

这是一个不需要任何额外库的版本。我不能像大家建议的那样使用 win32api:

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

仅在此处复制以防原件丢失。

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')
于 2016-08-12T18:58:24.663 回答