jpo38 jpo38 - 4 years ago 127
Python Question

Python: How to know if the OS/CPU is 64bits

Under Windows, I'm running a 32bits python.exe. I need to know if the OS/CPU is 64bits or 32bits.

My machine is running a Windows7 64bits.

Checked this post, and tried to run this Python script:

import ctypes; print(32 if ctypes.sizeof(ctypes.c_voidp)==4 else 64, 'bit CPU')
import sys; print("%x" % sys.maxsize, sys.maxsize > 2**32)
import struct; print( 8 * struct.calcsize("P"))
import platform; print( platform.architecture()[0] )
print( platform.machine() )


It outputs:

32 bit CPU
7fffffff False
32
32bit
AMD64


No proposal from the referenced post really gives you the CPU/OS architecture info. They all report 32bits because I'm running a Python 32bits binary.

How can I determine if the CPU/OS is 32bits or 64bits in a portable way (could loopu for 64 string in platform.machine() but I doubt that's the good way)?

Answer Source

Most information you are querying is determined by the wordsize of the interpreter, not the CPU.

Only platform.machine() ignores this information; it is taken from the system uname -m data instead, which is the recommended command to determine if your system is 64-bit for both Linux and OS X, and Windows provides the exact same information (Python uses the C uname() function in all cases).

Either test for 64 in that string, or build a set of acceptable values:

'64' in platform.machine()

or

platform.machine() in {'x86_64', 'AMD64'}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download