2

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

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • 2
    So why doesn't `AMD64` tell you this? In a 32-bit binary, the other values all definitely should be 32-bits, that's entirely normal. Either `AMD64` or `x86_64` should both tell you that the CPU is 64-bit. – Martijn Pieters Feb 06 '17 at 10:09
  • @MartijnPieters: Yes, it tells me that, but is doing `is_64 = (platform.machine().find( "64" ) != -1)` a portable way to check? Will that work on all CPU/OS which are 64bits? – jpo38 Feb 06 '17 at 10:12
  • It works on 3 different architectures I tried (one of which is a VM). – Martijn Pieters Feb 06 '17 at 10:13
  • @MartijnPieters: OK, that could be an acceptable answer than. – jpo38 Feb 06 '17 at 10:14

2 Answers2

1

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'}
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

From https://stackoverflow.com/a/12578715/4124672

You may want to use this solution for python2.7 and newer:

def is_os_64bit():
    return platform.machine().endswith('64')
Community
  • 1
  • 1
lelabo_m
  • 509
  • 8
  • 21