区分在 Windows 和其他操作系统(通常是 Linux)上运行 Python 应用程序的常用检查是使用条件:
if sys.platform == 'win32':
...
但我想知道在过去几年更广泛使用 64 位 Python 的今天使用安全吗? 32 真的是 32 位,还是指 Win32 API?
如果有一天 sys.platform 有可能成为“win64”,那么这种情况会更普遍吗?
if sys.platform.startswith('win'):
...
我知道还有另一种检测 Windows 的方法:
if os.name == 'nt':
...
但我真的从未在其他代码中看到使用后者。
那么最好的方法是什么?
UPD:如果可以的话,我想避免使用额外的库。需要安装额外的库来检查我是否在 Windows 中工作,这可能会让 Linux 用户感到恼火。
最佳答案
sys.platform
将是 win32
与底层 Windows 系统的位数无关,如您在 PC/pyconfig.h
中所见(来自 Python 2.6 源代码分发版):
#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"
可以找到original patch在网络上介绍了这一点,提供了更多解释:
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.
关于python - 在 64 位 Python 上使用 sys.platform= ='win32' 检查是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2144748/