Windows 또는 Unix 등을 사용하고 있는지 확인하려면 무엇이 필요합니까?
Windows 또는 Unix 등을 사용하고 있는지 확인하려면 무엇이 필요합니까?
답변:
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
출력은 platform.system()다음과 같습니다.
LinuxDarwinWindowsplatform이상 sys.platform?
platform.system()반환 "Windows"합니다 "win32". sys.platform또한 "linux2"이전 버전의 Python 에도 포함되어 있지만 "linux"최신 버전의 Python 에도 포함되어 있습니다. platform.system()항상 그냥 돌아 왔습니다 "Linux".
os.uname()은 Unix 시스템에만 존재합니다. Python 3 문서 : docs.python.org/3/library/os.html Availability: recent flavors of Unix.
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'
platform.release() '7'
platform.release()내에서 윈도우 10 , 그것은 확실히 날을 주었다 '8'. 어쩌면 업그레이드하기 전에 파이썬을 설치했지만 실제로 ??
파이썬을 사용하여 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
sys.platform이미 sys가져 왔고 다른 모듈을 가져 오지 않으려 는 경우 에도 사용할 수 있습니다
>>> import sys
>>> sys.platform
'linux2'
사용자가 읽을 수 있지만 여전히 자세한 정보를 원한다면 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
단편
사용하십시오 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를위한 최고의 휴대용 방법.
단점 : 파이썬 사람들은 정규화 휴리스틱을 최신 상태로 유지해야합니다.
요약
platform.system()입니다.posix또는 nt다음 사용os.name .sys.platform.새로운 답변은 어떻습니까?
import psutil
psutil.MACOS #True (OSX is deprecated)
psutil.WINDOWS #False
psutil.LINUX #False
MACOS를 사용하는 경우 출력이됩니다.
다양한 모듈을 사용하여 기대할 수있는 값에 대한 좀 더 체계적인 목록을 시작했습니다 (시스템을 자유롭게 편집하고 추가하십시오).
os.name posix
sys.platform linux
platform.system() Linux
sysconfig.get_platform() linux-x86_64
platform.machine() x86_64
platform.architecture() ('64bit', '')
sys.platform커널 버전, 예를 들어 접미사로되어 linux2, 다른 모든 것들 숙박 동일platform.architecture() = ('64bit', 'ELF')(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과 동일한 것도 있습니다시스템과 비교하려면이 스크립트를 실행하십시오 (없는 경우 여기에 결과를 추가하십시오).
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())
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()
/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)
자이 썬를 들어 내가 찾은 운영 체제 이름을 얻을 수있는 유일한 방법은 확인하는 것입니다 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
같은 맥락에서....
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")
커널 버전 등을 찾지 않고 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에서 이것을 실행하는 경우에만 작동합니다. 여러 플랫폼에서보다 일반적인 스크립트를 원한다면이 코드를 다른 답변에 제공된 코드 샘플과 혼합 할 수 있습니다.
이 시도:
import os
os.uname()
그리고 당신은 그것을 만들 수 있습니다 :
info=os.uname()
info[0]
info[1]
os.uname()창을 사용할 수 없습니다 : docs.python.org/2/library/os.html#os.uname의 가용성 : 유닉스의 최근의 맛.
모듈 플랫폼으로 사용 가능한 테스트를 확인하고 시스템에 대한 답변을 인쇄하십시오.
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
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]
나는 이것이 오래된 질문이라는 것을 알고 있지만 내 대답은 코드에서 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
이 솔루션은 모두 작동 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()
다음과 같은 간단한 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입니다
pip-date 패키지 pyOSinfo의 일부인 코드를 보면 Python 배포판에서 볼 수 있듯이 가장 관련성 높은 OS 정보를 얻을 수 있습니다.
사람들이 OS를 확인하려는 가장 일반적인 이유 중 하나는 터미널 호환성 및 특정 시스템 명령을 사용할 수 있는지 여부입니다. 불행히도,이 검사의 성공은 파이썬 설치 및 OS에 따라 다소 다릅니다. 예를 들어, uname대부분의 Windows python 패키지에서는 사용할 수 없습니다. 위의 파이썬 프로그램은 이미 가장 많이 사용되는 내장 함수의 출력을 보여줍니다 os, sys, platform, site.
가장 좋은 방법은 필수 코드에서 찾고 얻을 그래서 그 예로서. (방금 여기에 붙여 넣을 수는 있었지만 정치적으로 정확하지는 않았을 것입니다.)
나는 게임에 늦었지만 누군가가 필요로하는 경우에 대비하여 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'