是否可以安全使用sys.platform =='win32的“检查64位的Python?安全、platform、sys、Python

2023-09-07 23:32:34 作者:书的世界~输不起

通常的检查的Windows上运行的Python应用程序和其他操作系统(Linux的典型值)的使用条件区分:

The usual check to differentiate between running Python-application on Windows and on other OSes (Linux typically) is to use conditional:

if sys.platform == 'win32':
    ...

但我不知道它是今天的安全时使用64位的Python被越来越广泛地应用于过去几年? 32是否真的意味着32位,或者基本上它指的是Win32 API的?

But I wonder is it safe to use today when 64-bit Python is more widely used in last years? Does 32 really means 32-bit, or basically it refers to Win32 API?

如果有可能要休息一天sys.platform为Win64的,也许这样的情况会更普遍?

If there is possibility to have one day sys.platform as 'win64' maybe such condition would be more universal?

if sys.platform.startswith('win'):
    ...

还有另一种方式来检测到Windows我所知道的:

There is also another way to detect Windows I'm aware of:

if os.name == 'nt':
    ...

但我真的从来没有在C使用后者的另一$ C $看到了。

But I really never saw in other code the use of the latter.

什么是最好的办法呢?

UPD :我想避免使用额外的库,如果我能。无需安装额外的库来检查我的工作不是在Windows可能是恼人的Linux用户。

UPD: I'd like to avoid using extra libraries if I can. Requiring installing extra library to check that I'm work not in the Windows may be annoying for Linux users.

推荐答案

sys.platform 的win32 不管底层的Windows系统的位数的,因为你可以在 PC / pyconfig.h 看(从Python 2.6源代码发布):

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:

的主要问题是:是Win64的所以从它更像比Win32的不同,共同的,一般情况下,Python程序员不应该曾经有做差异化在他的Python code。或者,至少足以使这样的分化由Python scriptor是罕见的,以至于一些其它机制提供充足(即使preferable)。目前,答案是肯定的。希望MS不会改变这个答案。

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.