Python获得文件版本信息

Tips

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

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)));

Post Directory

Article directory