pkit pkit - 1 year ago 110
Python Question

Determine if an executable (or library) is 32 -or 64-bits (on Windows)

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.

Is there a simple way to do this using only the standard Python libraries (currently using 2.5.4)?

Answer Source

The Windows API for this is GetBinaryType. You can call this from Python using pywin32:

import win32file
if type==win32file.SCS_32BIT_BINARY:
    print "32 bit"
# And so on

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


f=open("c:\windows\explorer.exe", "rb")
if s!="MZ":
    print "Not an EXE file"
    header_offset=struct.unpack("<L", s)[0]
    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)"
        print "Unknown architecture"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download