Python이 실행되고 있는 OS를 식별하는 방법
Windows인지 Unix인지 확인하려면 무엇을 살펴야 합니까?
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
의 출력은 다음과 같습니다.
- Linux:
Linux - Mac:
Darwin - Windows:
Windows
참고 항목: — 기반 플랫폼의 식별 데이터에 대한 액세스
Windows 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'
참고로 Mac에 대한 결과는 다음과 같습니다.
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'
Python을 사용하여 운영 체제를 차별화하는 샘플 코드:
import sys
if sys.platform.startswith("linux"): # could be "linux", "linux2", "linux3", ...
# linux
elif sys.platform == "darwin":
# MAC OS X
elif os.name == "nt":
# Windows, Cygwin, etc. (either 32-bit or 64-bit)
단편소설
platform.system()돌아오다Windows,Linux ★★★★★★★★★★★★★★★★★」Darwin(OS X 우 ( 。
긴 이야기
Python에서 OS를 얻는 방법에는 세 가지가 있으며 각각 장단점이 있습니다.
방법 1
>>> import sys
>>> sys.platform
'win32' # could be 'linux', 'linux2, 'darwin', 'freebsd8' etc
구조(출처):내부적으로 OS API를 호출하여 OS에 정의된 OS 이름을 가져옵니다.OS 고유의 다양한 값에 대해서는, 여기를 참조해 주세요.
찬성: 마법은 없고, 낮은 레벨.
단점: OS 버전에 따라 다르므로 직접 사용하지 않는 것이 좋습니다.
방법 2
>>> import os
>>> os.name
'nt' # for Linux and Mac it prints 'posix'
구조(출처):내부적으로 Python에 posix 또는 nt라는 OS 전용 모듈이 있는지 확인합니다.
장점: POSIX OS인지 확인하는 것은 간단합니다.
단점: Linux와 OS X의 차이는 없습니다.
방법 3
>>> import platform
>>> platform.system()
'Windows' # For Linux it prints 'Linux'. For Mac, it prints `'Darwin'
구조(출처):내부적으로는 최종적으로 내부 OS API를 호출하여 'win32' 또는 'win16' 또는 'linux1'과 같은 OS 버전 고유의 이름을 얻은 후 몇 가지 휴리스틱스를 적용하여 'Windows' 또는 'Linux' 또는 'Darwin'과 같은 보다 일반적인 이름으로 정규화할 수 있습니다.
장점: Windows, OS X 및 Linux에 최적인 휴대용 방법.
반대: Python 사용자는 정규화 휴리스틱을 최신 상태로 유지해야 합니다.
요약
- X인지 확인하는 가장 할 수 있는 은 OS Windows, Linux OS X입니다.
platform.system(). - Python 로 OS 콜을 발신하는 .
posix★★★★★★★★★★★★★★★★★」nt, 을 사용합니다.os.name. - 자체에서 하십시오.
sys.platform.
다양한 모듈을 사용하여 기대할 수 있는 값을 좀 더 체계적으로 나열했습니다.
Linux(64비트)+WSL
x86_64 aarch64
------ -------
os.name posix posix
sys.platform linux linux
platform.system() Linux Linux
sysconfig.get_platform() linux-x86_64 linux-aarch64
platform.machine() x86_64 aarch64
platform.architecture() ('64bit', '') ('64bit', 'ELF')
- Arch Linux와 Linux Mint를 사용해 봤지만 같은 결과가 나왔습니다.
- 2, Python 2의
sys.platform는 커널 버전에 의해 접미사가 붙습니다.linux2외 - Linux용 Windows 서브시스템(Ubuntu 18.04(Bionic Beaver) LTS로 시도)에서도 동일한 출력이 출력됩니다.단, 단,
platform.architecture() = ('64bit', 'ELF')
Windows(64비트)
(32비트 서브시스템에서 32비트 컬럼을 실행 중)
Official Python installer 64 bit 32 bit
------------------------- ----- -----
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 64 bit 32 bit
----- ----- -----
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 64 bit 32 bit
------ ----- -----
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의 Anaconda는 Python Windows의 공식 설치 프로그램과 동일합니다.
- Mac도 없고 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())
이미 Import한 경우에도 사용할 수 있습니다.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'
현재 위치를 식별하기 위해 발신할 수 있는 몇 가지 다른 콜을 다음에 나타냅니다.최신 Python 버전에서는 linux_distribution 및 dist가 삭제되어 있습니다.
import platform
import sys
def linux_distribution():
try:
return platform.linux_distribution()
except:
return "N/A"
def dist():
try:
return platform.dist()
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(dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))
이 스크립트의 출력은 몇 가지 다른 시스템(Linux, Windows, Solaris 및 macOS)에서 실행되며 아키텍처(x86, x64, Itanium, PowerPC 및 SPARC)는 OS_flavor_name_version에서 구할 수 있습니다.
예를 들어 Ubuntu 12.04 서버(Precision Pangolin)는 다음을 제공합니다.
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: ('', ('', '', ''), '')
용도:
import psutil
psutil.MACOS # True ("OSX" is deprecated)
psutil.WINDOWS # False
psutil.LINUX # False
macOS 를 사용하고 있는 경우의 출력입니다.
platform.system() 사용
'Linux', 'Darwin', 'Java', 'Windows'와 같은 시스템/OS 이름을 반환합니다.값을 확인할 수 없는 경우 빈 문자열이 반환됩니다.
import platform
system = platform.system().lower()
is_windows = system == 'windows'
is_linux = system == 'linux'
is_mac = system == 'darwin'
Web Logic에 부속되어 있는 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(JDK 1.5를 탑재한 Windows Server 2003의 os.system()의 문제)에 패치를 적용하는 것 외에 다음과 같이 사용하고 있습니다.
def iswindows():
os = java.lang.System.getProperty( "os.name" )
return "win" in os.lower()
Jython의 경우 OS 이름을 얻을 수 있는 방법은os.name 속성(Java로 했습니다)sys,os ★★★★★★★★★★★★★★★★★」platformWindows XP의 Jython 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
하고 있는 의 Cygwin 를 사용해 주세요.os.nameposix.
>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW
#!/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)
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'
그건 벌레야.
여기에서는 OS를 코드로 검출하는 간단하고 알기 쉬운 방법을 소개합니다.Python 3.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
커널 버전 등을 찾는 것이 아니라 Linux 디스트리뷰션을 찾는 경우 다음을 사용할 수 있습니다.
Python 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
Python 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 모듈을 Import하지 않고 플랫폼모듈만 사용하여 모든 정보를 얻을 수도 있습니다.
>>> 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]
같은 맥락에서...
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")
모듈 플랫폼에서 사용 가능한 테스트를 확인하고 시스템에 대한 답변을 출력합니다.
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
Mac OS X를 실행하고 있는 경우platform.system()Mac OS X는 Apple의 Darwin OS를 기반으로 하기 때문에 Darwin이 됩니다.Darwin은 Mac OS X의 커널이며 기본적으로 GUI가 없는 Mac OS X입니다.
이 솔루션은 Python과 Jython 모두에서 작동합니다.
모듈 os_module.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 tested this one
단순히 Enum 값을 사용하여 액세스할 수 있습니다.
if OS.LINUX.value:
print("Cool. It is Linux")
추신: Python 3 입니다.
이걸 찾는 방법은 여러 가지가 있어요.가장 쉬운 방법은 os 패키지를 사용하는 것입니다.
import os
print(os.name)
Windows, Linux 및 MacOS에서 실행되도록 코드를 조정할 때 사용하는 기능입니다.
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'
pip-date 패키지의 일부인 코드를 보면 Python 배포판에서 볼 수 있듯이 가장 관련성이 높은 OS 정보를 얻을 수 있습니다.
OS를 체크하는 가장 일반적인 이유 중 하나는 단말기 호환성과 특정 시스템명령어를 사용할 수 있는지 여부입니다.유감스럽게도 이 체크의 성공 여부는 Python 설치와 OS에 따라 달라집니다.예를 들어, 는 대부분의 Windows Python 패키지에서는 사용할 수 없습니다.위의 Python 프로그램은 가장 일반적으로 사용되는 임베디드 함수의 출력을 보여줍니다.os, sys, platform, site.
따라서 필수 코드만 얻는 가장 좋은 방법은 예를 들어 보는 것입니다.
언급URL : https://stackoverflow.com/questions/1854/how-to-identify-which-os-python-is-running-on
'programing' 카테고리의 다른 글
| 영구 PowerShell 별칭 생성 방법 (0) | 2023.04.19 |
|---|---|
| 변수의 전체 유형 결정 (0) | 2023.04.19 |
| SQL Server에서 사용자를 생성한 후 로그인할 수 없음 (0) | 2023.04.19 |
| 조건부 바인딩: if let error – 조건부 바인딩 이니셜라이저에는 옵션 유형이 있어야 합니다. (0) | 2023.04.19 |
| 부트스트랩3의 sr-only는 무엇입니까? (0) | 2023.04.19 |
