何时使用 os.name、sys.platform 或 platform.system?

2022-01-11 00:00:00 python operating-system python-import

问题描述

据我所知,Python 有 3 种方法可以找出正在运行的操作系统:

As far as I know, Python has 3 ways of finding out what operating system is running on:

  1. 操作系统名称
  2. sys.platform
  3. platform.system()

了解这些信息在条件导入或使用不同平台的功能时通常很有用(例如,Windows 上的 time.clock()time.time() 上UNIX).

Knowing this information is often useful in conditional imports, or using functionality that differs between platforms (e.g. time.clock() on Windows v.s. time.time() on UNIX).

我的问题是,为什么要使用 3 种不同的方法?什么时候应该使用一种方式而不是另一种方式?哪种方式是最好的"(最具前瞻性或最不可能意外排除您的程序实际可以在其上运行的特定系统)?

My question is, why 3 different ways of doing this? When should one way be used and not another? Which way is the 'best' (most future-proof or least likely to accidentally exclude a particular system which your program can actually run on)?

似乎 sys.platformos.name 更具体,让您可以区分 win32cygwin(而不是仅仅 nt),以及来自 darwinlinux2(而不是仅仅 posix).但如果是这样,那sys.platformplatform.system()的区别是什么?

It seems like sys.platform is more specific than os.name, allowing you to distinguish win32 from cygwin (as opposed to just nt), and linux2 from darwin (as opposed to just posix). But if that's so, that what about the difference between sys.platform and platform.system()?

例如,哪个更好,这个:

For example, which is better, this:

import sys
if sys.platform == 'linux2':
    # Do Linux-specific stuff

还是这个?:

import platform
if platform.system() == 'Linux':
    # Do Linux-specific stuff

现在我将坚持使用 sys.platform,所以这个问题并不是特别紧急,但我会非常感谢您对此进行澄清.

For now I'll be sticking to sys.platform, so this question isn't particularly urgent, but I would be very grateful for some clarification regarding this.


解决方案

深入了解源代码.

sys.platformos.name 的输出是在编译时确定的.platform.system() 在运行时确定系统类型.

The output of sys.platform and os.name are determined at compile time. platform.system() determines the system type at run time.

  • sys.platform 在构建配置期间被指定为编译器定义.
  • os.name 检查某些特定于操作系统的模块是否可用(例如 posixnt、...)
  • platform.system() 实际上运行 uname 和可能的其他几个函数来在运行时确定系统类型.
  • sys.platform is specified as a compiler define during the build configuration.
  • os.name checks whether certain os specific modules are available (e.g. posix, nt, ...)
  • platform.system() actually runs uname and potentially several other functions to determine the system type at run time.

我的建议:

  • 使用 os.name 来检查它是否是一个 posix 兼容的系统.
  • 使用sys.platform检查是否是linux、cygwin、darwin、atheos等
  • 如果您不相信其他来源,请使用 platform.system().
  • Use os.name to check whether it's a posix-compliant system.
  • Use sys.platform to check whether it's a linux, cygwin, darwin, atheos, etc.
  • Use platform.system() if you don't believe the other sources.

相关文章