Detect 64bit OS (windows) in Python

谁都会走 提交于 2019-12-17 04:52: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


回答1:


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.




回答2:


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)



回答3:


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




回答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.




回答5:


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




回答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.




回答7:


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.




回答8:


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



回答9:


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)



回答10:


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?




回答11:


Following this documentation, try this code:

is_64bits = sys.maxsize > 2**32



回答12:


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.




回答13:


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




回答14:


import platform

platform.architecture()[0]

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




回答15:


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



回答16:


 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




回答17:


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)



回答18:


import struct

def is64Windows():
    return struct.calcsize('P') * 8 == 64



回答19:


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



来源:https://stackoverflow.com/questions/2208828/detect-64bit-os-windows-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!