0CCh Blog

Python获得文件版本信息

Python干啥都挺方便的,出了调用win32的api。当然了,可以用pywin32这种库。但我不喜欢为了一两个api又给简单的东西加一堆依赖。比如获取文件版本,本来想在网上找个函数复制过去用得了,却发现还真没啥好用的。无奈自己就写了一个。


class VS_FIXEDFILEINFO(Structure):
_fields_ = [
("dwSignature", c_int),
("dwStrucVersion", c_int),
("dwFileVersionMS", c_int),
("dwFileVersionLS", c_int),
("dwProductVersionMS", c_int),
("dwProductVersionLS", c_int),
("dwFileFlagsMask", c_int),
("dwFileFlags", c_int),
("dwFileOS", c_int),
("dwFileType", c_int),
("dwFileSubtype", c_int),
("dwFileDateMS", c_int),
("dwFileDateLS", c_int)
]
def LOWORD(dword): return dword & 0x0000ffff
def HIWORD(dword): return dword >> 16
def GetFileVersion(filename):
size = windll.version.GetFileVersionInfoSizeW(filename, None)
if not size:
return ''
res = create_string_buffer(size)
windll.version.GetFileVersionInfoW(filename, None, size, res)
r = VS_FIXEDFILEINFO()
l = c_uint()
p = c_void_p()
windll.version.VerQueryValueW(res, '\\', byref(p), byref(l));
memmove(byref(r), p, sizeof(VS_FIXEDFILEINFO))
if not l.value:
return ''

return ('%d.%d.%d.%d' % (HIWORD(r.dwFileVersionMS), LOWORD(r.dwFileVersionMS),
HIWORD(r.dwProductVersionLS), LOWORD(r.dwProductVersionLS)));