当前位置:  开发笔记 > 编程语言 > 正文

Python Windows文件版本属性

如何解决《PythonWindows文件版本属性》经验,为你挑选了4个好方法。

上次我问了一个类似的问题,但这是关于svn相关的版本信息.现在我想知道如何查询Windows"文件版本"属性,例如.一个DLL.我也关注wmi和win32file模块,但没有成功.



1> 小智..:

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

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


哇,干得好.你是怎么找到StringFileInfo的东西的..那就是我需要的东西.非常感谢.

2> 小智..:

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

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)

干杯!



3> the_void..:

您可以使用http://sourceforge.net/projects/pywin32/上的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> derflocki..:

这是一个版本,也适用于非Windows环境,使用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"


我从源代码中发现,通过仅解析资源目录,你可以将10s减少到1s/2s,呜!:`pe = pefile.PE(path,fast_load = True)pe.parse_data_directories(directories = [pefile.DIRECTORY_ENTRY] [ 'IMAGE_DIRECTORY_ENTRY_RESOURCE']])`
推荐阅读
郑小蒜9299_941611_G
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有