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

发布于 2024-10-09 13:14:19 字数 986 浏览 8 评论 0原文

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

  1. os.name
  2. sys.platform
  3. platform.system()

导入或使用平台之间不同的功能时很有用(例如 Windows 上的 time.clock() 与 UNIX 上的 time.time() )。

我的问题是,为什么要采用 3 种不同的方式来做到这一点?什么时候应该使用一种方法而不是另一种方法?哪种方式是“最好的”(最面向未来或最不可能意外排除您的程序实际可以在其上运行的特定系统)?

看起来 sys.platformos.name 更具体,允许您区分 win32cygwin (而不仅仅是 nt),以及来自 darwinlinux2(而不是仅仅 posix)。但如果是这样的话,那么 sys.platformplatform.system() 之间的区别是什么?

例如,哪个更好,这个:

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

还是这个? :

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

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

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

  1. os.name
  2. sys.platform
  3. platform.system()

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).

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)?

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

or this? :

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

屌丝范 2024-10-16 13:14:19

深入研究一下源代码。

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

  • sys.platform 在构建配置期间指定为编译器定义。
  • os.name 检查某些特定于操作系统的模块是否可用(例如 posixnt、...)
  • platform.system() 实际上运行 uname 以及可能的其他几个函数来确定运行时的系统类型。

我的建议:

  • 使用 os.name 检查它是否是 posix 兼容的系统。
  • 使用 sys.platform 检查它是否是 linux、cygwin、darwin、atheos 等。
  • 如果您不相信其他来源,请使用 platform.system()

Dived a bit into the source code.

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

  • 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.

My suggestion:

  • 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.
独行侠 2024-10-16 13:14:19

platform.system()sys.platform 之间存在细微差别,有趣的是,在大多数情况下 platform.system() 退化为 < code>sys.platform

这是源代码 Python2.7\Lib\Platform.py\system 所说的内容

def system():

    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.

        An empty string is returned if the value cannot be determined.

    """
    return uname()[0]

def uname():
    # Get some infos from the builtin os.uname API...
    try:
        system,node,release,version,machine = os.uname()
    except AttributeError:
        no_os_uname = 1

    if no_os_uname or not filter(None, (system, node, release, version, machine)):
        # Hmm, no there is either no uname or uname has returned
        #'unknowns'... we'll have to poke around the system then.
        if no_os_uname:
            system = sys.platform
            release = ''
            version = ''
            node = _node()
            machine = ''

也是根据 文档

os.uname()

返回一个 5 元组,其中包含标识当前操作系统的信息。该元组包含 5 个字符串:(sysname、nodename、
版本、版本、机器)。有些系统将节点名截断为 8
字符或主导成分;更好的方法来获得
主机名是 socket.gethostname() 甚至
socket.gethostbyaddr(socket.gethostname())。

可用性:Unix 的最新版本。

There is a thin line difference between platform.system() and sys.platform and interestingly for most cases platform.system() degenerates to sys.platform

Here is what the Source Python2.7\Lib\Platform.py\system says

def system():

    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.

        An empty string is returned if the value cannot be determined.

    """
    return uname()[0]

def uname():
    # Get some infos from the builtin os.uname API...
    try:
        system,node,release,version,machine = os.uname()
    except AttributeError:
        no_os_uname = 1

    if no_os_uname or not filter(None, (system, node, release, version, machine)):
        # Hmm, no there is either no uname or uname has returned
        #'unknowns'... we'll have to poke around the system then.
        if no_os_uname:
            system = sys.platform
            release = ''
            version = ''
            node = _node()
            machine = ''

Also per the documentation

os.uname()

Return a 5-tuple containing information identifying the current operating system. The tuple contains 5 strings: (sysname, nodename,
release, version, machine). Some systems truncate the nodename to 8
characters or to the leading component; a better way to get the
hostname is socket.gethostname() or even
socket.gethostbyaddr(socket.gethostname()).

Availability: recent flavors of Unix.
温柔戏命师 2024-10-16 13:14:19

来自 sys.platform 文档

  • os.name 具有较粗的粒度
  • os.uname() 提供与系统相关的版本信息
  • platform 模块提供对系统身份的详细检查

通常是“最佳”的面向未来的方法测试某些功能是否可用只是尝试使用它并在失败时使用后备。

sys.platform 和 platform.system() 之间有什么区别?

platform.system() 返回标准化值它可能从多个来源获得:os.uname()sys.platformver 命令(在 Windows 上)。

From sys.platform docs:

  • os.name has a coarser granularity
  • os.uname() gives system-dependent version information
  • The platform module provides detailed checks for the system’s identity

Often the "best" future-proof way to test whether some functionality is available is just to try to use it and use a fallback if it fails.

what about the difference between sys.platform and platform.system()?

platform.system() returns a normalized value that it might get from several sources: os.uname(), sys.platform, ver command (on Windows).

∞觅青森が 2024-10-16 13:14:19

这取决于您是否喜欢引发异常或在未经测试的系统上尝试任何内容,以及您的代码是否级别太高或太低以至于它可以或不能在类似的未经测试的系统上工作(例如未经测试的 Mac - 'posix' 或嵌入式 ARM 系统)。更多的Pythonic是不枚举所有已知的系统,而是测试可能的相关属性。 (例如,系统的字节顺序被认为很重要,但多处理属性并不重要。)

  • os.name 是正确使用 os 模块的足够分辨率。在 Python 2.7 中,可能的值为 'posix'、'nt'、'os2'、'ce'、'java' 或 'riscos',而自 Python 3.4 起仅使用 'posix'、'nt' 和 'java'。

  • sys.platform 是一个更精细的分辨率。建议使用 if sys.platform.startswith('linux') 习惯用法,因为“linux2”表示 Linux 内核版本 2.xx 或 3。目前从未使用较旧的内核。在 Python 3.3 中,所有 Linux 系统都是简单的“linux”。

我不知道“Mac”和“Java”系统的具体情况,因此我无法使用非常好的方法 platform.system() 的结果进行分支,但我会利用 platform 的优势消息和错误记录模块。

It depends on whether you prefer raising exception or trying anything on an untested system and whether your code is so high level or so low level that it can or can't work on a similar untested system (e.g. untested Mac - 'posix' or on embedded ARM systems). More pythonic is to not enumerate all known systems but to test possible relevant properties. (e.g. it is considered important the endianess of the system but unimportant multiprocessing properties.)

  • os.name is a sufficient resolution for the correct usage of os module. Possible values are 'posix', 'nt', 'os2', 'ce', 'java' or 'riscos' in Python 2.7, while only the 'posix', 'nt' and 'java' are used since Python 3.4.

  • sys.platform is a finer resolution. It is recommended to use if sys.platform.startswith('linux') idiom because "linux2" means a Linux kernel version 2.xx or 3. Older kernels are currently never used. In Python 3.3 are all Linux systems simple 'linux'.

I do not know the specifics of "Mac" and "Java" systems and so I can not use the results of very good method platform.system() for branching, but I would use advantages of the platform module for messages and error logging.

半边脸i 2024-10-16 13:14:19

我相信平台模块可能是新代码的首选。其他人在它之前就已经存在了。这是一个演变,其他的保留是为了向后兼容。

I believe the platform module is probably preferred for new code. The others existed before it. It is an evolution, and the others remain for backwards compatibility.

独自←快乐 2024-10-16 13:14:19

sys.platform 在编译时确定,platform.system() 在运行时确定。

这意味着前一种用法能够检查语法并在 IDE 中调暗无法访问的代码块。

IMO,如果 sys.platform 可以满足您的需求并且在您的代码中运行良好,请使用它。

sys.platform is determined at compile time, platform.system() determines at run time.

This means the former usage has the ability to check syntax and dim unreachable code blocks in IDE.

IMO, if sys.platform can meet your needs and works fine in your code, use it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文