Is it safe to use sys.platform=='win32' check on 64-bit Python?

不打扰是莪最后的温柔 提交于 2019-12-03 04:12:28

sys.platform will be win32 regardless of the bitness of the underlying Windows system, as you can see in PC/pyconfig.h (from the Python 2.6 source distribution):

#if defined(MS_WIN64)
/* maintain "win32" sys.platform for backward compatibility of Python code,
   the Win64 API should be close enough to the Win32 API to make this
   preferable */
#       define PLATFORM "win32"

It's possible to find the original patch that introduced this on the web, which offers a bit more explanation:

The main question is: is Win64 so much more like Win32 than different from it that the common-case general Python programmer should not ever have to make the differentiation in his Python code. Or, at least, enough so that such differentiation by the Python scriptor is rare enough that some other provided mechanism is sufficient (even preferable). Currently the answer is yes. Hopefully MS will not change this answer.

Personally I use platinfo for detecting the underlying platform.

>>> from platinfo import PlatInfo
>>> pi = PlatInfo()
>>> pi.os
'win64'
>>> pi.arch
'x64'
>>> pi.name()
'win64-x64'

For 32-bit, pi.name() returns win32-x86.

Notice that you cannot use either sys.platform or os.name for this on Jython:

$ jython -c "import sys, os; print sys.platform; print os.name"
java1.6.0_20
java

I think there's a plan in Jython project to change os.name to report the underlying OS similarly as CPython, but because people are using os.name == 'java' to check are they on Jython this change cannot be done overnight. There is, however, already os._name on Jython 2.5.x:

$ jython -c "import os; print os._name"
posix

Personally I tend to use os.sep == '/' with code that needs to run both on Jython and CPython, and both on Windows and unixy platforms. It's somewhat ugly but works.

The caveats for Windows/32 and Windows/64 are the same, so they should use the same value. The only difference would be in e.g. sys.maxint and ctypes. If you need to distinguish between 32 and 64 regardless then platform is your best bet.

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