Detect 64bit OS (windows) in Python

Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files.

Many thanks


Solution 1:

I think the best solution to the problem has been posted by Mark Ribau.

The best answer to the question for Python 2.7 and newer is:

def is_os_64bit():
    return platform.machine().endswith('64')

On windows the cross-platform-function platform.machine() internally uses the environmental variables used in Matthew Scoutens answer.

I found the following values:

  • WinXP-32: x86
  • Vista-32: x86
  • Win7-64: AMD64
  • Debian-32: i686
  • Debian-64: x86_64

For Python 2.6 and older:

def is_windows_64bit():
    if 'PROCESSOR_ARCHITEW6432' in os.environ:
        return True
    return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')

To find the Python interpreter bit version I use:

def is_python_64bit():
    return (struct.calcsize("P") == 8)

Solution 2:

I guess you should look in os.environ['PROGRAMFILES'] for the program files folder.

Solution 3:

platform module -- Access to underlying platform’s identifying data

>>> import platform
>>> platform.architecture()
('32bit', 'WindowsPE')

On 64-bit Windows, 32-bit Python returns:

('32bit', 'WindowsPE')

And that means that this answer, even though it has been accepted, is incorrect. Please see some of the answers below for options that may work for different situations.

Solution 4:

Came here searching for properly detecting if running on 64bit windows, compiling all the above into something more concise.

Below you will find a function to test if running on 64bit windows, a function to get the 32bit Program Files folder, and a function to get the 64bit Program Files folder; all regardless of running 32bit or 64bit python. When running 32bit python, most things report as if 32bit when running on 64bit, even os.environ['PROGRAMFILES'].

import os

def Is64Windows():
    return 'PROGRAMFILES(X86)' in os.environ

def GetProgramFiles32():
    if Is64Windows():
        return os.environ['PROGRAMFILES(X86)']
    else:
        return os.environ['PROGRAMFILES']

def GetProgramFiles64():
    if Is64Windows():
        return os.environ['PROGRAMW6432']
    else:
        return None

Note: Yes, this is a bit hackish. All other methods that "should just work", do not work when running 32bit Python on 64bit Windows (at least for the various 2.x and 3.x versions I have tried).

Edits:
2011-09-07 - Added a note about why only this hackish method works properly.