Python: What OS am I running on?

前端 未结 26 2190
野趣味
野趣味 2020-11-22 05:44

What do I need to look at to see whether I\'m on Windows or Unix, etc?

26条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 06:27

    Short Story

    Use platform.system(). It returns Windows, Linux or Darwin (for OSX).

    Long Story

    There are 3 ways to get OS in Python, each with its own pro and cons:

    Method 1

    >>> import sys
    >>> sys.platform
    'win32'  # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc
    

    How this works (source): Internally it calls OS APIs to get name of the OS as defined by OS. See here for various OS-specific values.

    Pro: No magic, low level.

    Con: OS version dependent, so best not to use directly.

    Method 2

    >>> import os
    >>> os.name
    'nt'  # for Linux and Mac it prints 'posix'
    

    How this works (source): Internally it checks if python has OS-specific modules called posix or nt.

    Pro: Simple to check if posix OS

    Con: no differentiation between Linux or OSX.

    Method 3

    >>> import platform
    >>> platform.system()
    'Windows' # for Linux it prints 'Linux', Mac it prints `'Darwin'
    

    How this works (source): Internally it will eventually call internal OS APIs, get OS version-specific name like 'win32' or 'win16' or 'linux1' and then normalize to more generic names like 'Windows' or 'Linux' or 'Darwin' by applying several heuristics.

    Pro: Best portable way for Windows, OSX and Linux.

    Con: Python folks must keep normalization heuristic up to date.

    Summary

    • If you want to check if OS is Windows or Linux or OSX then the most reliable way is platform.system().
    • If you want to make OS-specific calls but via built-in Python modules posix or nt then use os.name.
    • If you want to get raw OS name as supplied by OS itself then use sys.platform.

提交回复
热议问题