使用“pefile.py”获取文件(.exe)版本

时间:2009-08-12 06:16:51

标签: python

我想使用python来获取可执行文件版本,我知道pefile.py

如何使用它来做到这一点?

注意:可执行文件可能不完整。

3 个答案:

答案 0 :(得分:2)

这是一个完整的示例脚本,可以执行您想要的操作:

import sys

def main(pename):
    from pefile import PE
    pe = PE(pename)
    if not 'VS_FIXEDFILEINFO' in pe.__dict__:
        print "ERROR: Oops, %s has no version info. Can't continue." % (pename)
        return
    if not pe.VS_FIXEDFILEINFO:
        print "ERROR: VS_FIXEDFILEINFO field not set for %s. Can't continue." % (pename)
        return
    verinfo = pe.VS_FIXEDFILEINFO
    filever = (verinfo.FileVersionMS >> 16, verinfo.FileVersionMS & 0xFFFF, verinfo.FileVersionLS >> 16, verinfo.FileVersionLS & 0xFFFF)
    prodver = (verinfo.ProductVersionMS >> 16, verinfo.ProductVersionMS & 0xFFFF, verinfo.ProductVersionLS >> 16, verinfo.ProductVersionLS & 0xFFFF)
    print "Product version: %d.%d.%d.%d" % prodver
    print "File version: %d.%d.%d.%d" % filever

if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.stderr.write("ERROR:\n\tSyntax: verinfo <pefile>\n")
        sys.exit(1)
    sys.exit(main(sys.argv[1]))

相关部分是:

    verinfo = pe.VS_FIXEDFILEINFO
    filever = (verinfo.FileVersionMS >> 16, verinfo.FileVersionMS & 0xFFFF, verinfo.FileVersionLS >> 16, verinfo.FileVersionLS & 0xFFFF)
    prodver = (verinfo.ProductVersionMS >> 16, verinfo.ProductVersionMS & 0xFFFF, verinfo.ProductVersionLS >> 16, verinfo.ProductVersionLS & 0xFFFF)

所有这些只有在检查我们在这些属性中有意义之后才会发生。

答案 1 :(得分:0)

Windows程序的版本号存储在程序文件的资源部分中,而不是PE格式的头部。我不熟悉pefile.py,所以我不知道它是否也直接处理资源部分。如果没有,您应该能够在this MSDN article

中找到所需的信息

答案 2 :(得分:0)

假设“可执行文件版本”是指a)在Windows上,b)“属性”,“详细信息”选项卡中“文件版本”下显示的信息,您可以使用带有命令的pywin32包检索此信息如下:

>>> import win32api as w
>>> hex(w.GetFileVersionInfo('c:/windows/regedit.exe', '\\')['FileVersionMS'])
'0x60000'
>>> hex(w.GetFileVersionInfo('c:/windows/regedit.exe', '\\')['FileVersionLS'])
'0x17714650'

请注意,0x60000具有主要/次要编号(6.0),而0x17714650是接下来的两个,如果将其视为两个单独的字(0x1771和0x4650,或者十进制的6001和18000),则对应于我的机器上的值,其中regedit的版本是6.0.6001.18000。

相关问题