tags:

views:

366

answers:

4

I'm doing some work with the windows registry. Depending on whether you're running python as 32-bit or 64-bit, the key value will be different. How do I detect if Python is running as a 64-bit application as opposed to a 32-bit application?

Note: I'm not interested in detecting 32-bit/64-bit Windows - just the Python platform.

+13  A: 
import platform
platform.architecture()

From the Python docs:

Queries the given executable (defaults to the Python interpreter binary) for various architecture information.

Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.

Cristian
+2  A: 

You can try platform.architecture

ccheneson
+11  A: 

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on OS X multi-architecture builds such as the Apple-supplied default with OS X 10.6, the same executable file may be capable of running in either mode, as the example below demonstrates. The safest multi-platform approach is to test sys.maxint on Python 2.x or sys.maxsize on Python 3.x.

$ /usr/bin/python
Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxint
(('64bit', ''), 9223372036854775807)
>>> ^D
$ export VERSIONER_PYTHON_PREFER_32_BIT=yes
$ /usr/bin/python
Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxint
(('64bit', ''), 2147483647)
Ned Deily
Cool thanks for the detail.
nbolton
Interesting gotcha. That smells a bit like a bug though. Is it supposed to work that way?
gnibbler
I would consider it a bug. Looking at the code in the platform module, it seems to be a bit fragile and in this case it has to do with the way Apple implemented their multi-arch selection feature. I'm adding a note to ensure we look at this when the python.org OS X multi-arch selection feature is finalized.
Ned Deily
(I've also opened a bug with Apple.)
Ned Deily
A: 

Out of curiousity... Isn't it possible to assume that you're on 32-bit, wrapped in try..except that would then try using the 64-bit key on failure? That's how I'd probably do it.

Neil Santos