确定可执行文件(或库)是 32 位还是 64 位(在 Windows 上) [英] Determine if an executable (or library) is 32 -or 64-bits (on Windows)
问题描述
我试图找出给定的可执行文件(或库)是否是从 Python 为 32 位或 64 位编译的.我运行的是 64 位 Vista,想确定某个目录中的某个应用程序是针对 32 位还是 64 位编译的.
I am trying to find out if a given executable (or library) is compiled for 32-bits or 64-bits from Python. I am running Vista 64-bits and would like to determine if a certain application in a directory is compiled for 32-bits or 64-bits.
是否有一种仅使用标准 Python 库(目前使用 2.5.4)来执行此操作的简单方法?
Is there a simple way to do this using only the standard Python libraries (currently using 2.5.4)?
推荐答案
Windows API 是 GetBinaryType
.您可以使用 pywin32 从 Python 调用它:
The Windows API for this is GetBinaryType
. You can call this from Python using pywin32:
import win32file
type=GetBinaryType("myfile.exe")
if type==win32file.SCS_32BIT_BINARY:
print "32 bit"
# And so on
如果您想在没有 pywin32 的情况下执行此操作,则必须阅读 PE 标头你自己.这是一个例子C#,这里是 Python 的快速移植:
If you want to do this without pywin32, you'll have to read the PE header yourself. Here's an example in C#, and here's a quick port to Python:
import struct
IMAGE_FILE_MACHINE_I386=332
IMAGE_FILE_MACHINE_IA64=512
IMAGE_FILE_MACHINE_AMD64=34404
f=open("c:windowsexplorer.exe", "rb")
s=f.read(2)
if s!="MZ":
print "Not an EXE file"
else:
f.seek(60)
s=f.read(4)
header_offset=struct.unpack("<L", s)[0]
f.seek(header_offset+4)
s=f.read(2)
machine=struct.unpack("<H", s)[0]
if machine==IMAGE_FILE_MACHINE_I386:
print "IA-32 (32-bit x86)"
elif machine==IMAGE_FILE_MACHINE_IA64:
print "IA-64 (Itanium)"
elif machine==IMAGE_FILE_MACHINE_AMD64:
print "AMD64 (64-bit x86)"
else:
print "Unknown architecture"
f.close()
这篇关于确定可执行文件(或库)是 32 位还是 64 位(在 Windows 上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!