質問

Windows を使用しているのか Unix を使用しているのかなどを確認するには、何を確認する必要がありますか?

役に立ちましたか?

解決

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

の出力 platform.system() 以下のとおりであります:

  • Linux: Linux
  • マック: Darwin
  • ウィンドウズ: Windows

見る: プラットフォーム — 基盤となるプラットフォームの識別データへのアクセス

他のヒント

くそ -- 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'

記録のために、Mac での結果は次のとおりです。

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

Python を使用して 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 をインポートしていて、別のモジュールをインポートしたくない場合は、sys.platform を使用することもできます。

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

ユーザーが読み取り可能なデータが必要だが詳細なデータが必要な場合は、次のように使用できます。 プラットフォーム.プラットフォーム()

>>> 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: ('', ('', '', ''), '')

私はこれをします

import sys
print sys.platform

ドキュメントはこちら: システムプラットフォーム.

必要なものはすべて sys モジュールにあると思われます。

私は 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()

新しい答えはどうでしょうか。

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

MACOS を使用している場合、これは出力になります。

>>> import platform
>>> platform.system()

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

Jythonの場合、私が見つけたOS名を取得する唯一の方法は、チェックすることです os.name Java プロパティ (試してみた) sys, os そして platform WinXP 上の 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

さまざまなモジュールを使用して期待できる値を、もう少し体系的にリストしてみました (システムを自由に編集して追加してください)。

Linux (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 上の 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())

Windows 8 での興味深い結果:

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

編集: それは バグ

Cygwin を搭載した Windows を使用している場合は注意してください。 os.nameposix.

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

同じように....

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 ディストリビューションを探している場合は、次のコマンドを使用するとよいでしょう。

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

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

モジュール プラットフォームで利用可能なテストを確認し、システムの答えを出力します。

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]

macOS X を実行している場合は、次のコマンドを実行します。 platform.system() Macos XはAppleのDarwin OSに構築されているため、ダーウィンを取得します。Darwin は macOS X のカーネルであり、本質的には GUI を除いた macOS X です。

このソリューションは両方に機能します 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()
import sys
import platform

# return a platform identifier
print(sys.platform)

# return system/os name
print(platform.system())

# print system info
# similar to 'uname' command in unix
print(platform.uname())

使用 import os そして os.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")

P.S それはpython3です

コードは次のとおりです。 pyOSinfo の一部です ピップ日付 パッケージを使用して、Python ディストリビューションから確認できる最も関連性の高い OS 情報を取得します。

OS をチェックする最も一般的な理由の 1 つは、端末の互換性と、特定のシステム コマンドが使用できるかどうかです。残念ながら、このチェックが成功するかどうかは、Python のインストールと OS に多少依存します。例えば、 uname ほとんどの Windows Python パッケージでは使用できません。上記の Python プログラムは、すでに提供されている最も一般的に使用される組み込み関数の出力を表示します。 os, sys, platform, site.

enter image description here

したがって、重要なコードのみを取得する最良の方法は、 それ 例として。(ここに貼り付けることもできたと思いますが、それは政治的に正しくありません。)

私は遅れていますが、誰かが必要とする場合に備えて、これは 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'
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top