어떤 OS를 사용하고 있습니까?


답변:


827
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

출력은 platform.system()다음과 같습니다.

  • 리눅스 : Linux
  • 맥: Darwin
  • 윈도우 : Windows

참조 : platform- 플랫폼의 식별 데이터를 기본에 대한 액세스


26
왜 좋아해야 platform이상 sys.platform?
— matth

40
@matth 약간 더 일관된 출력. 즉 대신을 platform.system()반환 "Windows"합니다 "win32". sys.platform또한 "linux2"이전 버전의 Python 에도 포함되어 있지만 "linux"최신 버전의 Python 에도 포함되어 있습니다. platform.system()항상 그냥 돌아 왔습니다 "Linux".
— erb

4
Mac OS X에서 platform.system ()은 항상 "Darwin"을 반환합니까? 아니면 다른 경우가 있습니까?
— baptiste chéné

4
@ baptistechéné, 나는 이것이 당신이 요청한 지 1 년이 넘었 음을 알고 있지만, 의견이 아프지 않기 때문에 나는 그것을 게시 할 것입니다 :) 그래서 그 이유는 커널 이름을 보여주기 때문입니다. 리눅스 (커널) 배포판과 같은 방식으로 많은 이름 (우분투, 아치, 페도라 등)이 있지만 커널 이름은 Linux라는 이름으로 표시됩니다. 다윈 (BSD 기반 커널)에는 주변 시스템 인 macOS가 있습니다. 애플이 다윈을 오픈 소스 코드로 공개했다고 확신하지만, 내가 아는 다윈을 달리는 다른 배포판은 없다.
— Joao Paulo Rabelo

1
@TooroSan os.uname()은 Unix 시스템에만 존재합니다. Python 3 문서 : docs.python.org/3/library/os.html Availability: recent flavors of Unix.
— Irving Moy

175

Dang-lbrandy가 나를 이길 수는 있지만 Vista의 시스템 결과를 제공 할 수는 없습니다!

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'

... 아무도 Windows 10 용으로 게시 된 사람이 없다고 믿을 수 없습니다.

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'

6
Windows 7 :platform.release() '7'
— Hugo Hugo

3
그래, 좋아, 난 그냥 도망 platform.release()내에서 윈도우 10 , 그것은 확실히 날을 주었다 '8'. 어쩌면 업그레이드하기 전에 파이썬을 설치했지만 실제로 ??
— Codesmith

2
나는 당신이 Windows 8에서 업그레이드했을 가능성이 높을 것이라고 생각했을 것입니다 (vs. 새로 설치하는 것). 그리고 레지스트리에서 파이썬이 찾거나 남은 것은 무엇입니까?
— OJFord

2
Windows에서 python에 대한 릴리스 조회는 핵심에서 Win32 API 함수 GetVersionEx를 사용하는 것으로 보입니다. 이 기능에 관한이 Microsoft 기사의 맨 위에있는 참고 사항은 관련이있을 수 있습니다. msdn.microsoft.com/en-us/library/windows/desktop/…
— theferrit32

126

기록에 대한 Mac 결과는 다음과 같습니다.

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'

1
macOS Catalina 10.15.2에서 platform.release()반환'19.2.0'
— Boris

95

파이썬을 사용하여 OS를 차별화하는 샘플 코드 :

from sys import platform as _platform

if _platform == "linux" or _platform == "linux2":
    # linux
elif _platform == "darwin":
    # MAC OS X
elif _platform == "win32":
    # Windows
elif _platform == "win64":
    # Windows 64-bit

1
이 샘플 코드는 파이썬 모듈의 코드입니까? 이것은 실제로 질문에 대답하는 유일한 대답입니다.
— kon psych

8
fuzzier 결과를 위해,``_platform.startswith ( 'linux')
— Klaatu von Schlacker

42

sys.platform이미 sys가져 왔고 다른 모듈을 가져 오지 않으려 는 경우 에도 사용할 수 있습니다

>>> import sys
>>> sys.platform
'linux2'

다른 모듈을 가져와야하는 것 외에 다른 방법으로 장점이 있습니까?
— matth

범위 지정이 주요 이점입니다. 가능한 적은 전역 변수 이름을 원합니다. 글로벌 이름으로 "sys"가 이미 있으면 다른 이름을 추가해서는 안됩니다. 그러나 "sys"를 아직 사용하지 않으면 "_platform"을 사용하는 것이 더 설명적이고 다른 의미와 충돌 할 가능성이 줄어 듭니다.
— sanderd17

33

사용자가 읽을 수 있지만 여전히 자세한 정보를 원한다면 platform.platform ()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

현재 위치를 식별하기 위해 사용할 수있는 몇 가지 다른 호출이 있습니다.

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

이 스크립트의 출력은 몇 가지 다른 시스템 (Linux, Windows, Solaris, MacOS)에서 실행되었으며 아키텍처 (x86, x64, Itanium, power pc, sparc)는 https://github.com/hpcugent/easybuild/에서 사용할 수 있습니다. wiki / OS_flavor_name_version

예를 들어 Ubuntu 12.04 서버는 다음을 제공합니다.

Python version: ['2.6.5 (r265:79063, Oct  1 2012, 22:04:36) ', '[GCC 4.4.3]']
dist: ('Ubuntu', '10.04', 'lucid')
linux_distribution: ('Ubuntu', '10.04', 'lucid')
system: Linux
machine: x86_64
platform: Linux-2.6.32-32-server-x86_64-with-Ubuntu-10.04-lucid
uname: ('Linux', 'xxx', '2.6.32-32-server', '#62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011', 'x86_64', '')
version: #62-Ubuntu SMP Wed Apr 20 22:07:43 UTC 2011
mac_ver: ('', ('', '', ''), '')

DeprecationWarning: dist() and linux_distribution() functions are deprecated in Python 3.5
— Boris

19

단편

사용하십시오 platform.system(). 그것은 반환 Windows, Linux또는 Darwin(OSX 용).

긴 이야기

파이썬에서 OS를 얻는 방법에는 각각 고유 한 장단점이있는 3 가지 방법이 있습니다.

방법 1

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

작동 방식 ( source ) : 내부적으로 OS에서 정의한대로 OS API를 호출하여 OS 이름을 가져옵니다. 다양한 OS 별 값 은 여기 를 참조 하십시오 .

장점 : 마법이없고 레벨이 낮습니다.

단점 : OS 버전에 따라 다르므로 직접 사용하지 않는 것이 가장 좋습니다.

방법 2

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

작동 원리 ) : 내부적으로 파이썬에 posix 또는 nt라는 OS 관련 모듈이 있는지 확인합니다.

Pro : POSIX OS 확인이 간단

단점 : Linux 또는 OSX간에 차이가 없습니다.

방법 3

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

작동 방식 ( source ) : 내부적으로 내부 OS API를 호출하고 'win32'또는 'win16'또는 'linux1'과 같은 OS 버전 별 이름을 가져온 다음 'Windows'또는 'Linux'와 같은보다 일반적인 이름으로 정규화합니다. 여러 휴리스틱을 적용하여 '다윈'.

프로 : Windows, OSX 및 Linux를위한 최고의 휴대용 방법.

단점 : 파이썬 사람들은 정규화 휴리스틱을 최신 상태로 유지해야합니다.

요약

  • OS가 Windows, Linux 또는 OSX인지 확인하려면 가장 안정적인 방법은 platform.system()입니다.
  • 당신이 OS 특정 통화를하려면 파이썬 모듈 내장을 통해 posix또는 nt다음 사용os.name .
  • OS 자체에서 제공 한 원시 OS 이름을 얻으려면을 사용하십시오 sys.platform.

"일을하는 한 가지 (그리고 바람직하게는 오직 한 가지) 방법이 있어야한다"라는 말이 너무나 많다. 그러나 이것이 정답이라고 생각합니다. 제목이 지정된 OS 이름과 비교해야하지만 그러한 문제는 아니며 이식성이 뛰어납니다.
— vincent-lg

16

새로운 답변은 어떻습니까?

import psutil
psutil.MACOS   #True (OSX is deprecated)
psutil.WINDOWS #False
psutil.LINUX   #False 

MACOS를 사용하는 경우 출력이됩니다.


7
psutil은 표준 라이브러리에 포함되어 있지 않습니다
— Corey Goldberg

14

다양한 모듈을 사용하여 기대할 수있는 값에 대한 좀 더 체계적인 목록을 시작했습니다 (시스템을 자유롭게 편집하고 추가하십시오).

리눅스 (64 비트) + WSL

os.name                     posix
sys.platform                linux
platform.system()           Linux
sysconfig.get_platform()    linux-x86_64
platform.machine()          x86_64
platform.architecture()     ('64bit', '')
  • archlinux와 mint로 시도했지만 동일한 결과를 얻었습니다.
  • python2에 sys.platform커널 버전, 예를 들어 접미사로되어 linux2, 다른 모든 것들 숙박 동일
  • Linux 용 Windows 서브 시스템에서 동일한 출력 (ubuntu 18.04 LTS로 시도) platform.architecture() = ('64bit', 'ELF')

WINDOWS (64 비트)

(32 비트 서브 시스템에서 32 비트 열이 실행 중)

official python installer   64bit                     32bit
-------------------------   -----                     -----
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    win-amd64                 win32
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('64bit', 'WindowsPE')

msys2                       64bit                     32bit
-----                       -----                     -----
os.name                     posix                     posix
sys.platform                msys                      msys
platform.system()           MSYS_NT-10.0              MSYS_NT-10.0-WOW
sysconfig.get_platform()    msys-2.11.2-x86_64        msys-2.11.2-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

msys2                       mingw-w64-x86_64-python3  mingw-w64-i686-python3
-----                       ------------------------  ----------------------
os.name                     nt                        nt
sys.platform                win32                     win32
platform.system()           Windows                   Windows
sysconfig.get_platform()    mingw                     mingw
platform.machine()          AMD64                     AMD64
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

cygwin                      64bit                     32bit
------                      -----                     -----
os.name                     posix                     posix
sys.platform                cygwin                    cygwin
platform.system()           CYGWIN_NT-10.0            CYGWIN_NT-10.0-WOW
sysconfig.get_platform()    cygwin-3.0.1-x86_64       cygwin-3.0.1-i686
platform.machine()          x86_64                    i686
platform.architecture()     ('64bit', 'WindowsPE')    ('32bit', 'WindowsPE')

일부 비고 :

  • distutils.util.get_platform()`sysconfig.get_platform과 동일한 것도 있습니다
  • Windows의 아나콘다는 공식 Python Windows 설치 프로그램과 동일합니다.
  • 나는 맥이나 진정한 32 비트 시스템이 없으며 온라인으로 동기를 부여받지 못했습니다.

시스템과 비교하려면이 스크립트를 실행하십시오 (없는 경우 여기에 결과를 추가하십시오).

from __future__ import print_function
import os
import sys
import platform
import sysconfig

print("os.name                      ",  os.name)
print("sys.platform                 ",  sys.platform)
print("platform.system()            ",  platform.system())
print("sysconfig.get_platform()     ",  sysconfig.get_platform())
print("platform.machine()           ",  platform.machine())
print("platform.architecture()      ",  platform.architecture())

11

weblogic과 함께 제공되는 WLST 도구를 사용하고 있으며 플랫폼 패키지를 구현하지 않습니다.

wls:/offline> import os
wls:/offline> print os.name
java 
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'

javaos.py 시스템을 패치하는 것 외에도 ( jdk1.5를 사용하여 Windows 2003에서 os.system () 문제 ) (나는 할 수 없으므로 weblogic을 즉시 사용해야합니다), 이것은 내가 사용하는 것입니다.

def iswindows():
  os = java.lang.System.getProperty( "os.name" )
  return "win" in os.lower()

9

/usr/bin/python3.2

def cls():
    from subprocess import call
    from platform import system

    os = system()
    if os == 'Linux':
        call('clear', shell = True)
    elif os == 'Windows':
        call('cls', shell = True)

3
SO에 오신 것을 환영합니다. 여기에서는 솔루션이 아닌 솔루션을 사용해야하는 이유를 설명하는 것이 좋습니다. 그렇게하면 답이 더 가치있게되고 독자가 어떻게 행동하는지 더 잘 이해할 수있게됩니다. 또한 FAQ ( stackoverflow.com/faq)를 참조하십시오 .
— ForceMagic

좋은 대답, 아마도 원래의 대답과 동등 할 수도 있습니다. 그러나 이유를 설명 할 수 있습니다.
— vgoff

9

자이 썬를 들어 내가 찾은 운영 체제 이름을 얻을 수있는 유일한 방법은 확인하는 것입니다 os.name(함께 노력 자바 속성을 sys, os그리고 platformWINXP에 자이 썬 2.5.3에 대한 모듈) :

def get_os_platform():
    """return platform name, but for Jython it uses os.name Java property"""
    ver = sys.platform.lower()
    if ver.startswith('java'):
        import java.lang
        ver = java.lang.System.getProperty("os.name").lower()
    print('platform: %s' % (ver))
    return ver

"platform.java_ver ()"를 호출하여 Jython에서 OS 정보를 추출 할 수도 있습니다.
— DocOc

8

Windows 8의 재미있는 결과 :

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'

편집 : 그건 버그입니다


7

Cygwin이있는 Windows의 위치 os.name가 어디 인지 확인하십시오 posix.

>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW

6

같은 맥락에서....

import platform
is_windows=(platform.system().lower().find("win") > -1)

if(is_windows): lv_dll=LV_dll("my_so_dll.dll")
else:           lv_dll=LV_dll("./my_so_dll.so")

9
Mac에서 platform.system ()이 "Darwin"을 반환하고 "Darwin".lower (). find ( "win") = 3을 반환하므로 Mac에있는 경우 문제가됩니다.
— mishaF

is_windows = platform.system (). lower (). startswith ( "win") 또는 False
— Corey Goldberg

6

커널 버전 등을 찾지 않고 Linux 배포판을 찾는 경우 다음을 사용할 수 있습니다.

파이썬 2.6 이상

>>> import platform
>>> print platform.linux_distribution()
('CentOS Linux', '6.0', 'Final')
>>> print platform.linux_distribution()[0]
CentOS Linux
>>> print platform.linux_distribution()[1]
6.0

파이썬 2.4에서

>>> import platform
>>> print platform.dist()
('centos', '6.0', 'Final')
>>> print platform.dist()[0]
centos
>>> print platform.dist()[1]
6.0

분명히 이것은 Linux에서 이것을 실행하는 경우에만 작동합니다. 여러 플랫폼에서보다 일반적인 스크립트를 원한다면이 코드를 다른 답변에 제공된 코드 샘플과 혼합 할 수 있습니다.


5

이 시도:

import os

os.uname()

그리고 당신은 그것을 만들 수 있습니다 :

info=os.uname()
info[0]
info[1]

1
또한 os.uname()창을 사용할 수 없습니다 : docs.python.org/2/library/os.html#os.uname의 가용성 : 유닉스의 최근의 맛.
— ccpizza

4

모듈 플랫폼으로 사용 가능한 테스트를 확인하고 시스템에 대한 답변을 인쇄하십시오.

import platform

print dir(platform)

for x in dir(platform):
    if x[0].isalnum():
        try:
            result = getattr(platform, x)()
            print "platform."+x+": "+result
        except TypeError:
            continue

4

os 모듈을 가져 오지 않고 플랫폼 모듈 만 사용하여 모든 정보를 얻을 수도 있습니다.

>>> import platform
>>> platform.os.name
'posix'
>>> platform.uname()
('Darwin', 'mainframe.local', '15.3.0', 'Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64', 'x86_64', 'i386')

이 라인을 사용하여보고 목적을위한 멋지고 깔끔한 레이아웃을 얻을 수 있습니다.

for i in zip(['system','node','release','version','machine','processor'],platform.uname()):print i[0],':',i[1]

그것은이 출력을 제공합니다 :

system : Darwin
node : mainframe.local
release : 15.3.0
version : Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64
machine : x86_64
processor : i386

일반적으로 누락 된 것은 운영 체제 버전이지만 Windows, Linux 또는 Mac을 플랫폼 독립적 인 방법으로 실행중인 경우이 테스트를 사용하는 것입니다.

In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]:
   ....:     if i[0]:
   ....:         print 'Version: ',i[0]

4

나는 이것이 오래된 질문이라는 것을 알고 있지만 내 대답은 코드에서 OS를 감지하는 쉽고 간단한 이해하기 쉬운 파이썬 방법을 찾고있는 일부 사람들에게 도움이 될 수 있다고 생각합니다. python3.7에서 테스트

from sys import platform


class UnsupportedPlatform(Exception):
    pass


if "linux" in platform:
    print("linux")
elif "darwin" in platform:
    print("mac")
elif "win" in platform:
    print("windows")
else:
    raise UnsupportedPlatform

2

macOS X를 실행하고 실행하는 경우 platform.system()macOS X가 Apple의 Darwin OS에 내장되어 있기 때문에 darwin을 얻습니다. Darwin은 macOS X의 커널이며 GUI가없는 macOS X입니다.


2

이 솔루션은 모두 작동 python및jython 됩니다.

os_identify.py 모듈 :

import platform
import os

# This module contains functions to determine the basic type of
# OS we are running on.
# Contrary to the functions in the `os` and `platform` modules,
# these allow to identify the actual basic OS,
# no matter whether running on the `python` or `jython` interpreter.

def is_linux():
    try:
        platform.linux_distribution()
        return True
    except:
        return False

def is_windows():
    try:
        platform.win32_ver()
        return True
    except:
        return False

def is_mac():
    try:
        platform.mac_ver()
        return True
    except:
        return False

def name():
    if is_linux():
        return "Linux"
    elif is_windows():
        return "Windows"
    elif is_mac():
        return "Mac"
    else:
        return "<unknown>" 

다음과 같이 사용하십시오.

import os_identify

print "My OS: " + os_identify.name()

1

다음과 같은 간단한 Enum 구현은 어떻습니까? 외부 라이브러리가 필요 없습니다!

import platform
from enum import Enum
class OS(Enum):
    def checkPlatform(osName):
        return osName.lower()== platform.system().lower()

    MAC = checkPlatform("darwin")
    LINUX = checkPlatform("linux")
    WINDOWS = checkPlatform("windows")  #I haven't test this one

간단히 Enum 값으로 액세스 할 수 있습니다

if OS.LINUX.value:
    print("Cool it is Linux")

추신 : 그것은 python3입니다


1

pip-date 패키지 pyOSinfo의 일부인 코드를 보면 Python 배포판에서 볼 수 있듯이 가장 관련성 높은 OS 정보를 얻을 수 있습니다.

사람들이 OS를 확인하려는 가장 일반적인 이유 중 하나는 터미널 호환성 및 특정 시스템 명령을 사용할 수 있는지 여부입니다. 불행히도,이 검사의 성공은 파이썬 설치 및 OS에 따라 다소 다릅니다. 예를 들어, uname대부분의 Windows python 패키지에서는 사용할 수 없습니다. 위의 파이썬 프로그램은 이미 가장 많이 사용되는 내장 함수의 출력을 보여줍니다 os, sys, platform, site.

여기에 이미지 설명을 입력하십시오

가장 좋은 방법은 필수 코드에서 찾고 얻을 그래서 그 예로서. (방금 여기에 붙여 넣을 수는 있었지만 정치적으로 정확하지는 않았을 것입니다.)


1

나는 게임에 늦었지만 누군가가 필요로하는 경우에 대비하여 Windows, Linux 및 MacO에서 실행되도록 코드를 조정하는 데 사용하는 함수입니다.

import sys
def get_os(osoptions={'linux':'linux','Windows':'win','macos':'darwin'}):
    '''
    get OS to allow code specifics
    '''   
    opsys = [k for k in osoptions.keys() if sys.platform.lower().find(osoptions[k].lower()) != -1]
    try:
        return opsys[0]
    except:
        return 'unknown_OS'
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.