Detect 64bit OS (windows) in Python
Asked Answered
P

23

44

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

Proboscidean answered 5/2, 2010 at 16:55 Comment(3)
Knowing this won't tell you where the program files are stored.Fineman
>>> import ctypes, sys >>> i = ctypes.c_int() >>> kernel32 = ctypes.windll.kernel32 >>> process = kernel32.GetCurrentProcess() >>> kernel32.IsWow64Process(process, ctypes.byref(i)) gossamer-threads.com/lists/python/python/663523Greggrega
When reading through the answers, be warned: some of them return the version (32/64bit) of installed Python, some the version of the processor architecture, and only some actually return the version (32/64bit) of the OS. Which is what the question asks for. Many of the answers confuse these.Trampoline
B
31

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.

Bashaw answered 5/2, 2010 at 17:31 Comment(10)
But I agree, use the environment variable to locate %PROGRAMFILES%Bashaw
On 64-bit Windows it returns the same thing.Safford
This won't work, because python chose to always return win32 for compatibility. This is also why there are only 'hackish' way to find out.Sprung
@Thomas If I do print platform.architecture()[0], it displays 64bit on Windows 7 64bit.Humblebee
@Humblebee You are probably running 64 bit Python on 64 bit Windows.Stheno
@Stheno Ribau: Maybe you are right, but when I start IDLE, it shows me "Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32".Humblebee
@Humblebee That looks like 2.7.1 64bit. Running platform.architecture() in six different versions of IDLE on Windows 7 64bit yields: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 (2.6.6 32bit) => ('32bit', 'WindowsPE'); Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32 (2.6.6 64bit) => ('64bit', 'WindowsPE'); Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 (2.7.2 32bit) => ('32bit', 'WindowsPE');Stheno
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32 (2.7.2 64bit) => ('64bit', 'WindowsPE'); Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 (3.2.2 32bit) => ('32bit', 'WindowsPE'); Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32 (3.2.2 64bit) => ('64bit', 'WindowsPE').Stheno
On 64 bit system, if 32 bit python2.7 is installed..it will return ('32bit', 'WindowsPE')..Spann
This doesn't return the system platform, but the Python platform, which is what I was looking for.Diarrhoea
J
67

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)
Jerrodjerrol answered 25/9, 2012 at 8:8 Comment(6)
This is the right answer. It is the only one that works also if you are using Python 32bit on 64bit Windows installation. +1Postulate
I don't think this is always safe either: You could have a 32-bit OS running on 64-bit processor architecture.Trampoline
@Petri, in this case all three function correctly return FalseJerrodjerrol
@phobie, have you tried? I don't have a 32-bit OS on 64-bit hardware, do you?Trampoline
Yes! The underlaying hardware has no impact. The functions have been tested with EM64T systems on all OSs listed by me.Jerrodjerrol
Note that you first have to import platform!Verona
C
38

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

Courbet answered 5/2, 2010 at 17:1 Comment(5)
+1 for solving the problem instead of answering the question - not always a good thing, but in this case it is.Tension
This is the right solution, rather than hardcoding a directory. However, this will not lead to the 32-bit program files on 64-bit Windows, if that's what is needed.Ink
Yes, it will lead to the correct Program Files on Win64. Here are my values on Win7 64: ProgramFiles=C:\Program Files (x86) ProgramFiles(x86)=C:\Program Files (x86) ProgramW6432=C:\Program FilesSafford
FYI: It will lead to the x86 version if you are running 32 bit python, but the x64 version if running 64 bit python.Stheno
@MikeGraham it is not the right solution because whether your program (i.e. in our case the Python interpreter) runs as WOW64 or native 64-bit program governs whether the WOW64 (%SystemRoot%\SysWOW64\cmd.exe) or 64-bit cmd.exe (%SystemRoot%\System32\cmd.exe) gets to run on a 64-bit Windows and thereby makes the output of this value relative to the environment.Cerecloth
B
31

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.

Bashaw answered 5/2, 2010 at 17:31 Comment(10)
But I agree, use the environment variable to locate %PROGRAMFILES%Bashaw
On 64-bit Windows it returns the same thing.Safford
This won't work, because python chose to always return win32 for compatibility. This is also why there are only 'hackish' way to find out.Sprung
@Thomas If I do print platform.architecture()[0], it displays 64bit on Windows 7 64bit.Humblebee
@Humblebee You are probably running 64 bit Python on 64 bit Windows.Stheno
@Stheno Ribau: Maybe you are right, but when I start IDLE, it shows me "Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32".Humblebee
@Humblebee That looks like 2.7.1 64bit. Running platform.architecture() in six different versions of IDLE on Windows 7 64bit yields: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 (2.6.6 32bit) => ('32bit', 'WindowsPE'); Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32 (2.6.6 64bit) => ('64bit', 'WindowsPE'); Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 (2.7.2 32bit) => ('32bit', 'WindowsPE');Stheno
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32 (2.7.2 64bit) => ('64bit', 'WindowsPE'); Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 (3.2.2 32bit) => ('32bit', 'WindowsPE'); Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32 (3.2.2 64bit) => ('64bit', 'WindowsPE').Stheno
On 64 bit system, if 32 bit python2.7 is installed..it will return ('32bit', 'WindowsPE')..Spann
This doesn't return the system platform, but the Python platform, which is what I was looking for.Diarrhoea
S
29

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.

Stheno answered 29/4, 2011 at 22:27 Comment(0)
S
9
def os_platform():
    true_platform = os.environ['PROCESSOR_ARCHITECTURE']
    try:
            true_platform = os.environ["PROCESSOR_ARCHITEW6432"]
    except KeyError:
            pass
            #true_platform not assigned to if this does not exist
    return true_platform

http://blogs.msdn.com/b/david.wang/archive/2006/03/26/howto-detect-process-bitness.aspx

Shiah answered 31/8, 2011 at 16:32 Comment(1)
this does indeed return the true platform, even on 32bit python running on 64bit windows; however, true_platform will be "x86" for 32bit python on 32bit windows, "AMD64" for 32bit or 64bit python on windows 64bit for many machines (most intel consumer CPU, most AMD consumer CPU), "I64" for 32bit or 64bit python on windows 64bit for itanium and similar machines. just be aware of this.Stheno
A
6

Many of these proposed solutions, such as platform.architecture(), fail because their results depend on whether you are running 32-bit or 64-bit Python.

The only reliable method I have found is to check for the existence of os.environ['PROGRAMFILES(X86)'], which is unfortunately hackish.

Alarcon answered 18/9, 2010 at 6:42 Comment(0)
I
3

You should be using environment variables to access this. The program files directory is stored in the environment variable PROGRAMFILES on x86 Windows, the 32-bit program files is directory is stored in the PROGRAMFILES(X86) environment variable, these can be accessed by using os.environ('PROGRAMFILES').

Use sys.getwindowsversion() or the existence of PROGRAMFILES(X86) (if 'PROGRAMFILES(X86)' in os.environ) to determine what version of Windows you are using.

Ink answered 5/2, 2010 at 17:37 Comment(1)
getwindowsversion() does not lead to the bit version used by the os! I. e. it returns similar results for Win7 32-bit and 64-bit. For the environmental variables have a look at the answer of Mark Ribau!Jerrodjerrol
P
2

Following this documentation, try this code:

is_64bits = sys.maxsize > 2**32
Pave answered 24/7, 2014 at 21:19 Comment(3)
No. I ran this on a 64 bit windows server 2012R2, it returned False but worked on windows 7. Better use reg keys or environment variables.Laager
@Laager The official documentation explains that both the platform.architecture() and the sys.maxsize > 2**32 are trying to detect whether the python intepretor itself is in 32 bit or 64 bit, NOT whether your OS is in 32 bit or 64 bit. Therefore the result you observed was presumably caused by your installation of different builts of Python on those machines. Depending on your purpose, these behavior may or may not be considered a wrong behavior.Colpitis
Right. The question does not ask for the interpretor bitness. It mentions the operating system bitness.Laager
L
2

Im aware that in comments of the question this method was already used. This is the method the .net framework uses:

import ctypes

def is64_bit_os():
    """ Returns wethever system is a 64bit operating system"""
    is64bit = ctypes.c_bool()
    handle = ctypes.windll.kernel32.GetCurrentProcess() # should be -1, because the current process is currently defined as (HANDLE) -1
    success = ctypes.windll.kernel32.IsWow64Process(handle, ctypes.byref(is64bit)) #should return 1
    return (success and is64bit).value
print(is64_bit_os())
Lambert answered 20/4, 2017 at 6:46 Comment(0)
G
2

I just found another way to do this, which may be useful in some situations.

import subprocess
import os

def os_arch():
    os_arch = '32-bit'
    if os.name == 'nt':
        output = subprocess.check_output(['wmic', 'os', 'get', 'OSArchitecture'])
        os_arch = output.split()[1]
    else:
        output = subprocess.check_output(['uname', '-m'])
        if 'x86_64' in output:
            os_arch = '64-bit'
        else:
            os_arch = '32-bit'
    return os_arch

print 'os_arch=%s' % os_arch()

I tested this code in the following environments:

  • Ubuntu 16.04 + Python 2.7.12
  • Mac OS Sierra + Python 2.7.11
  • Windows 7 Pro 32-bit + Python 2.7.5 (32-bit)
  • Windows 10 Home 64-bit + Python 2.7.13 (32-bit)
Gamekeeper answered 28/7, 2017 at 7:18 Comment(0)
C
1

The subject lines asks about detecting 64 or 32bit OS, while the body talks about determining the location of ProgramFiles. The latter has a couple of workable answers here. I'd like to add another solution generalized to handle StartMenu, Desktop, etc. as well as ProgramFiles: How to get path of Start Menu's Programs directory?

Ciliary answered 5/2, 2010 at 16:56 Comment(0)
A
1

When you need to find out things about windows system, it is usually somewhere in the registry, according to MS documentation, you should look at (http://support.microsoft.com/kb/556009) this key value:

HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0

and if it is:

0x00000020 (32 in decimal)

It is a 32 bit machine.

Androecium answered 15/12, 2014 at 5:57 Comment(3)
Has anyone tested this? Despite the KB title, the KB article actually talks about processor information, so I suspect that the info refers to processor architecture, not the OS version.Trampoline
On Windows7 (64-bit) running in a Parallels VM on OSX, the registry value is 0x00000001 (1 in decimal)Trampoline
On Windows 10 (64-bit), there no longer is such registry attribute ("Platform ID"). But there is a "Platform Specific Field 1", and it's value is 0x00000002 (2 in decimal). Go figure... :(Trampoline
F
0

64-bit versions of Windows use something called registry redirection and reflection keys. There is a compatibility layer called WoW64 which enables compatibility of 32-bit applications. Starting from Windows 7 and Windows Server 2008 R2 WoW64 registry keys are not longer reflected but shared. You can read about it here:

registry-reflection: msdn.microsoft.com/en-us/library/aa384235(v=vs.85).aspx

affected-keys: msdn.microsoft.com/en-us/library/aa384253(v=vs.85).aspx

wikipedia: en.wikipedia.org/wiki/WoW64

All you need to do is detect existence of those keys. You can use _winreg for that. Use try: and try opening key, example:

try:
aReg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run")
Fraudulent answered 29/1, 2011 at 11:4 Comment(0)
A
0
 import _winreg
 def get_registry_value(key, subkey, value):
   key = getattr(_winreg, key)
   handle = _winreg.OpenKey(key, subkey )
   (value, type) = _winreg.QueryValueEx(handle, value)
   return value

 windowsbit=cputype = get_registry_value(
        "HKEY_LOCAL_MACHINE",
        "SYSTEM\\CurrentControlSet\Control\\Session Manager\\Environment",
        "PROCESSOR_ARCHITECTURE")
 print windowsbit

just run this code

if you are working on 64 bit windows machine this will print AMD64

or if you are working on 32 bit it will print AMD32

i hope this code can help to solve this problem fully

Adventist answered 22/5, 2014 at 22:45 Comment(0)
M
0

This works for me in the Python versions I use: 2.7 and 2.5.4

    import win32com.client
    import _winreg

    shell = win32com.client.Dispatch('WScript.Shell')
    proc_arch = shell.ExpandEnvironmentStrings(r'%PROCESSOR_ARCHITECTURE%').lower()

    if proc_arch == 'x86':
        print "32 bit"
    elif proc_arch == 'amd64':
        print "64 bit"
    else:
        raise Exception("Unhandled arch: %s" % proc_arch)
Muntjac answered 30/10, 2014 at 1:18 Comment(0)
N
0

Just to update this old thread - it looks like the platform module reports the correct architecture now (at least, in Python 2.7.8):

c:\python27\python.exe -c "import platform; print platform.architecture(), platform.python_version()"
('32bit', 'WindowsPE') 2.7.6

c:\home\python278-x64\python.exe -c "import platform; print platform.architecture(), platform.python_version()"
('64bit', 'WindowsPE') 2.7.8

(sorry I don't have the rep to comment on the first answer which still claims to be wrong :)

Nyctophobia answered 4/6, 2015 at 11:16 Comment(1)
You probably installed the 64-bit version of Python. The issue is that this will not detect an 64-bit OS if you have installed a 32-bit version of Python.Tsarevitch
S
0
import platform

platform.architecture()[0]

It will return '32bit' or '64bit' depending on system architecture.

Saum answered 13/8, 2017 at 11:26 Comment(1)
no, this is not reliable it returns the architecture of your interpreterAuspex
U
0

The solution posted by Alexander Brüsch is the correct solution, but it has a bug that only reveals itself on python3.x. He neglected to cast the returned value from GetCurrentProcess() to a HANDLE type. Passing a simple integer as the first parameter of IsWow64Process() returns 0 (which is an error flag from win32api). Also, Alexander incorrectly handles the return statement (success has no .value attribute).

For those who stumble on this thread, here is the corrected code:

import ctypes

def is64_bit_os():
    """Returns True if running 32-bit code on 64-bit operating system"""
    is64bit = ctypes.c_bool()
    handle = ctypes.wintypes.HANDLE(ctypes.windll.kernel32.GetCurrentProcess())
    success = ctypes.windll.kernel32.IsWow64Process(handle, ctypes.byref(is64bit))
    return success and is64bit.value
print(is64_bit_os())
Ursala answered 21/12, 2019 at 15:34 Comment(0)
A
0

There is a function named machine in platform module. I installed both Python3.8 32-bit and 64-bit versions on the same 64-bit machine with 64-bit Windows 10 and here is what I found:

Comparison of all the functions in platform module

And it looks like platform.machine returns machine architecture without bothering what type of python is installed. so here is my final compilation

import platform

def is_64bit():
    return platform.machine().endswith('64')
Amends answered 23/2, 2021 at 6:36 Comment(0)
S
0

Most of the answers here are incorrect :/

Here is a simple translation of the well known method used in CMD and this is how microsoft do it too.

import os
_os_bit=64
if os.environ.get('PROCESSOR_ARCHITECTURE').lower() == 'x86' and os.environ.get('PROCESSOR_ARCHITEW6432') is None: _os_bit=32

print(_os_bit)

but remember: Windows 10 on ARM includes an x86-on-ARM64 emulation, so the possible values for PROCESSOR_ARCHITECTURE are: AMD64 or IA64 or ARM64 or x86

Spragens answered 12/1, 2022 at 11:2 Comment(0)
N
0

A solution, putting together the options from the links below and using os module:

import os
#next save the response from the command prompt saved to a file 
window = os.system('PowerShell.exe "gwmi win32_operatingsystem | select osarchitecture" > prompt.txt')
#next read the file
f = open('prompt.txt','r')
windowsos = f.readlines()
f.close()
print(windowsos[3][:-1])

https://datatofish.com/command-prompt-python/ https://www.radishlogic.com/windows/how-to-check-if-your-windows-10-is-64-bit-or-32-bit/ https://www.tutorialspoint.com/how-to-run-a-powershell-script-from-the-command-prompt

Nopar answered 6/1, 2023 at 1:56 Comment(0)
C
-1
import struct

def is64Windows():
    return struct.calcsize('P') * 8 == 64
Cooley answered 7/6, 2016 at 0:46 Comment(1)
This is also just telling the arch of python interpreter itself.Gamekeeper
I
-2

There should be a directory under Windows 64bit, a Folder called \Windows\WinSxS64 for 64 bit, under Windows 32bit, it's WinSxS.

Ish answered 5/2, 2010 at 17:10 Comment(2)
This is fragile and hackish. Python provides built-in ways to directly access information about the OS, and it doesn't depend on the Windows installation directory being in a normal place or having a normal name.Ink
@Mike Except that it doesn't work on Windows most of the time. Try running a 32bit Python on 64bit windows. It returns 32bit for most cases if using a default compile from python.org. (At least for all the 2.x versions I have used.)Stheno

© 2022 - 2024 — McMap. All rights reserved.