确定可执行文件(或库)是32位还是64位(在Windows上)

pki*_*kit 9 python windows dll 64-bit executable

我试图找出一个给定的可执行文件(或库)是否从Python编译为32位或64位.我运行Vista 64位,并想确定目录中的某个应用程序是否编译为32位或64位.

有没有一种简单的方法只使用标准的Python库(目前使用2.5.4)?

Mar*_*n B 21

Windows API就是这样的GetBinaryType.你可以使用pywin32从Python调用它:

import win32file
type=GetBinaryType("myfile.exe")
if type==win32file.SCS_32BIT_BINARY:
    print "32 bit"
# And so on
Run Code Online (Sandbox Code Playgroud)

如果你想在没有pywin32的情况下这样做,你必须自己阅读PE头.这是C#中的一个示例,这是Python的快速端口:

import struct

IMAGE_FILE_MACHINE_I386=332
IMAGE_FILE_MACHINE_IA64=512
IMAGE_FILE_MACHINE_AMD64=34404

f=open("c:\windows\explorer.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()
Run Code Online (Sandbox Code Playgroud)


Jas*_*mbs 5

如果您在Windows上运行Python 2.5或更高版本,则还可以通过使用ctypes使用不带pywin32的Windows API。

from ctypes import windll, POINTER
from ctypes.wintypes import LPWSTR, DWORD, BOOL

SCS_32BIT_BINARY = 0 # A 32-bit Windows-based application
SCS_64BIT_BINARY = 6 # A 64-bit Windows-based application
SCS_DOS_BINARY = 1 # An MS-DOS-based application
SCS_OS216_BINARY = 5 # A 16-bit OS/2-based application
SCS_PIF_BINARY = 3 # A PIF file that executes an MS-DOS-based application
SCS_POSIX_BINARY = 4 # A POSIX-based application
SCS_WOW_BINARY = 2 # A 16-bit Windows-based application

_GetBinaryType = windll.kernel32.GetBinaryTypeW
_GetBinaryType.argtypes = (LPWSTR, POINTER(DWORD))
_GetBinaryType.restype = BOOL

def GetBinaryType(filepath):
    res = DWORD()
    handle_nonzero_success(_GetBinaryType(filepath, res))
    return res
Run Code Online (Sandbox Code Playgroud)

然后像使用win32file.GetBinaryType一样使用GetBinaryType。

注意,您将必须实现handle_nonzero_success,如果返回值为0,则基本上会引发异常。