developer tip

os.name, sys.platform 또는 platform.system을 언제 사용합니까?

optionbox 2020. 9. 6. 09:29
반응형

os.name, sys.platform 또는 platform.system을 언제 사용합니까?


내가 아는 한, 파이썬에는 어떤 운영 체제가 실행되고 있는지 알아내는 세 가지 방법이 있습니다.

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

이 정보를 아는 것은 종종 조건부 가져 오기 또는 플랫폼간에 다른 기능을 사용하는 데 유용합니다 (예 : time.clock()Windows 대 time.time()UNIX).

제 질문은 왜 이렇게하는 3 가지 다른 방법입니까? 한 가지 방법을 사용해야하고 다른 방법은 사용하지 않아야합니까? 어떤 방법이 '최고'입니까 (가장 미래 지향적이거나 프로그램이 실제로 실행될 수있는 특정 시스템을 실수로 제외 할 가능성이 가장 적음)?

것 같다 sys.platform보다 더 구체적입니다 os.name당신이 구별 할 수 있도록 win32에서 cygwin(단지 반대가 nt),과 linux2에서 darwin(단지 반대 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질문은 특별히 긴급하지는 않지만 이에 대한 설명에 대해 매우 감사하겠습니다.


소스 코드를 조금씩 살펴 보았습니다.

sys.platform의 출력은 os.name컴파일 타임에 결정됩니다. platform.system()런타임에 시스템 유형을 결정합니다.

  • sys.platform 빌드 구성 중에 컴파일러 정의로 지정됩니다.
  • os.name특정 OS의 특정 모듈 여부를 확인 가능하다 (예를 들면 posix, nt...)
  • platform.system()실제로 실행 uname되고 런타임에 시스템 유형을 결정하기 위해 잠재적으로 몇 가지 다른 기능이 있습니다.

나의 제안:

  • os.nameposix 호환 시스템인지 확인하는 데 사용 합니다.
  • sys.platformLinux, cygwin, darwin, atheos 등인지 확인하는 데 사용 합니다.
  • platform.system()다른 출처를 믿지 않는 경우 사용하십시오 .

사이에 얇은 라인의 차이가 platform.system()그리고 sys.platform흥미롭게도 대부분의 경우에 platform.system()로 퇴화는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 ()

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.

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


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

참고URL : https://stackoverflow.com/questions/4553129/when-to-use-os-name-sys-platform-or-platform-system

반응형