What OS am I running on?

What do I need to look at to see whether I'm on Windows or Unix, etc?

5.08.2008 03:23:18
see (bugs.python.org/issue12326) for details!
arnkore 18.01.2012 09:34:03
Here's a related question: Check linux distro name.
blong 8.12.2015 19:00:53
25 ОТВЕТОВ
РЕШЕНИЕ
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

The output of platform.system() is as follows:

  • Linux: Linux
  • Mac: Darwin
  • Windows: Windows

See: platform — Access to underlying platform’s identifying data

804
27.12.2019 04:51:44
Why should I prefer platform over sys.platform?
matth 7.11.2016 14:25:30
@matth Slightly more consistent output. i.e. platform.system() returns "Windows" instead of "win32". sys.platform also contains "linux2" on old versions of Python while it contains just "linux" on newer ones. platform.system() has always returned just "Linux".
erb 9.06.2017 10:22:38
On mac os X, platform.system() always return "Darwin"? or is there other case possible?
baptiste chéné 12.01.2018 13:35:19
@baptistechéné, I know this has over an year since you asked, but as a comment won't hurt, I'll post it anyways :) So, the reason behind it is because it shows the kernel name. The same way Linux (the kernel) distros have many names (Ubuntu, Arch, Fedora among others), but it'll present itself as the kernel name, Linux. Darwin (a BSD-based Kernel), has its surrounding system, the macOS. I'm pretty sure apple did release Darwin as an open source code, but there's no other distro running over Darwin that I know of.
Joao Paulo Rabelo 30.01.2019 12:05:33
@TooroSan os.uname() only exists for Unix systems. The Python 3 docs: docs.python.org/3/library/os.html Availability: recent flavors of Unix.
Irving Moy 22.03.2020 21:49:06

Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!

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

...and I can’t believe no one’s posted one for Windows 10 yet:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'
173
5.04.2017 19:32:14
Windows 7: platform.release() '7'
Hugo 20.04.2015 12:27:35
So, yeah, I just ran platform.release() on my Windows 10, and it definitely just gave me '8'. Maybe I installed python before upgrading, but really??
Codesmith 8.06.2017 13:35:13
I'd have thought it's more likely you upgraded from Windows 8 (vs. it being a clean install) and whatever Python looks up in the registry or whatever was left behind?
OJFord 30.01.2018 20:53:04
The release lookup for python on Windows appears to use the Win32 api function GetVersionEx at its core. The notes at the top of this Microsoft article about that function could be relevant: msdn.microsoft.com/en-us/library/windows/desktop/…
theferrit32 22.03.2018 20:13:42

For the record here's the results on Mac:

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'
124
18.08.2015 10:01:22
On macOS Catalina 10.15.2, platform.release() returns '19.2.0'
Boris 27.12.2019 04:55:58

You can also use sys.platform if you already have imported sys and you don't want to import another module

>>> import sys
>>> sys.platform
'linux2'
42
28.10.2019 10:18:14
Does on of the approaches have any advantages, besides having to or not to import another module?
matth 7.11.2016 14:41:31
Scoping is the main advantage. You want as few global variable names as possible. When you already have "sys" as a global name, you shouldn't add another one. But if you don't use "sys" yet, using "_platform" might be more descriptive and less likely to collide with another meaning.
sanderd17 21.12.2016 09:01:30

I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package.

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

Apart from patching the system javaos.py (issue with os.system() on windows 2003 with jdk1.5) (which I can't do, I have to use weblogic out of the box), this is what I use:

def iswindows():
  os = java.lang.System.getProperty( "os.name" )
  return "win" in os.lower()
11
26.11.2014 17:08:24

in the same vein....

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")
6
28.09.2011 17:54:43
This is problematic if you are on a Mac since platform.system() returns "Darwin" on a Mac and "Darwin".lower().find("win") = 3.
mishaF 19.04.2013 15:10:31
is_windows = platform.system().lower().startswith("win") or False
Corey Goldberg 29.03.2018 02:05:17

/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)
9
10.10.2011 01:40:54
Welcome on SO, here, it is a good practice to explain why to use your solution and not just how. That will make your answer more valuable and help further reader to have a better understanding of how you do it. I also suggest that you have a look on our FAQ : stackoverflow.com/faq.
ForceMagic 9.11.2012 22:03:26
Good answer, maybe even on par with the original answer. But you could explain why.
vgoff 9.11.2012 22:04:17

For Jython the only way to get os name I found is to check os.name Java property (tried with sys, os and platform modules for Jython 2.5.3 on WinXP):

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
9
9.01.2013 08:47:48
You can also call "platform.java_ver()" to extract OS information in Jython.
DocOc 3.10.2018 16:08:26

If you want user readable data but still detailed, you can use platform.platform()

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

Here's a few different possible calls you can make to identify where you are

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

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

Ubuntu 12.04 server for example gives:

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: ('', ('', '', ''), '')
33
22.05.2019 15:53:05
DeprecationWarning: dist() and linux_distribution() functions are deprecated in Python 3.5
Boris 27.12.2019 04:57:22

Interesting results on windows 8:

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

Edit: That's a bug

8
14.02.2013 22:44:56

If you not looking for the kernel version etc, but looking for the linux distribution you may want to use the following

in 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

in python2.4

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

Obviously, this will work only if you are running this on linux. If you want to have more generic script across platforms, you can mix this with code samples given in other answers.

5
28.03.2013 06:30:17

Sample code to differentiate OS's using python:

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
91
3.01.2020 18:41:00
Is this sample code from any python module? This is the only answer that in fact answers the question.
kon psych 15.01.2015 19:22:44
For fuzzier results, ``_platform.startswith('linux')
Klaatu von Schlacker 8.02.2016 03:51:05

Check the available tests with module platform and print the answer out for your system:

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
30.10.2014 00:43:08

try this:

import os

os.uname()

and you can make it :

info=os.uname()
info[0]
info[1]
5
16.01.2015 18:13:11
Also os.uname() is not available on windows: docs.python.org/2/library/os.html#os.uname Availability: recent flavors of Unix.
ccpizza 24.10.2017 20:26:46

Watch out if you're on Windows with Cygwin where os.name is posix.

>>> import os, platform
>>> print os.name
posix
>>> print platform.system()
CYGWIN_NT-6.3-WOW
7
8.07.2015 14:46:49

You can also use only platform module without importing os module to get all the information.

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

A nice and tidy layout for reporting purpose can be achieved using this line:

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

That gives this output:

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

What is missing usually is the operating system version but you should know if you are running windows, linux or mac a platform indipendent way is to use this test:

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

How about a new answer:

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

This would be the output if I was using MACOS

15
13.10.2018 16:47:16
psutil is not part of standard lib
Corey Goldberg 29.03.2018 02:09:18

If you are running macOS X and run platform.system() you get darwin because macOS X is built on Apple's Darwin OS. Darwin is the kernel of macOS X and is essentially macOS X without the GUI.

2
13.01.2018 22:16:08

How about a simple Enum implementation like the following? No need for external libs!

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

Simply you can access with Enum value

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

P.S It is python3

1
29.09.2018 14:03:50

This solution works for both python and jython.

module 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>" 

Use like this:

import os_identify

print "My OS: " + os_identify.name()
2
29.01.2019 13:06:52

You can look at the code in pyOSinfo which is part of the pip-date package, to get the most relevant OS information, as seen from your Python distribution.

One of the most common reasons people want to check their OS is for terminal compatibility and if certain system commands are available. Unfortunately, the success of this checking is somewhat dependent on your python installation and OS. For example, uname is not available on most Windows python packages. The above python program will show you the output of the most commonly used built-in functions, already provided by os, sys, platform, site.

enter image description here

So the best way to get only the essential code is looking at that as an example. (I guess I could have just pasted it here, but that would not have been politically correct.)

1
7.02.2019 21:16:16

I started a bit more systematic listing of what values you can expect using the various modules (feel free to edit and add your system):

Linux (64bit) + WSL

os.name                     posix
sys.platform                linux
platform.system()           Linux
sysconfig.get_platform()    linux-x86_64
platform.machine()          x86_64
platform.architecture()     ('64bit', '')
  • tried with archlinux and mint, got same results
  • on python2 sys.platform is suffixed by kernel version, e.g. linux2, everything else stays identical
  • same output on Windows Subsystem for Linux (tried with ubuntu 18.04 LTS), except platform.architecture() = ('64bit', 'ELF')

WINDOWS (64bit)

(with 32bit column running in the 32bit subsystem)

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

Some remarks:

  • there is also distutils.util.get_platform() which is identical to `sysconfig.get_platform
  • anaconda on windows is same as official python windows installer
  • I don't have a Mac nor a true 32bit system and was not motivated to do it online

To compare with your system, simply run this script (and please append results here if missing :)

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
2.03.2019 00:35:12

I am late to the game but, just in case anybody needs it, this a function I use to make adjustments on my code so it runs on Windows, Linux and 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'
1
22.05.2019 14:04:19

Short Story

Use platform.system(). It returns Windows, Linux or Darwin (for OSX).

Long Story

There are 3 ways to get OS in Python, each with its own pro and cons:

Method 1

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

How this works (source): Internally it calls OS APIs to get name of the OS as defined by OS. See here for various OS-specific values.

Pro: No magic, low level.

Con: OS version dependent, so best not to use directly.

Method 2

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

How this works (source): Internally it checks if python has OS-specific modules called posix or nt.

Pro: Simple to check if posix OS

Con: no differentiation between Linux or OSX.

Method 3

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

How this works (source): Internally it will eventually call internal OS APIs, get OS version-specific name like 'win32' or 'win16' or 'linux1' and then normalize to more generic names like 'Windows' or 'Linux' or 'Darwin' by applying several heuristics.

Pro: Best portable way for Windows, OSX and Linux.

Con: Python folks must keep normalization heuristic up to date.

Summary

  • If you want to check if OS is Windows or Linux or OSX then the most reliable way is platform.system().
  • If you want to make OS-specific calls but via built-in Python modules posix or nt then use os.name.
  • If you want to get raw OS name as supplied by OS itself then use sys.platform.
14
11.12.2019 12:33:32
So much for "There should be one (and preferably only one) way to do things". However I believe this is the right answer. You would need to compare with titled OS names but it's not such an issue and will be more portable.
vincent-lg 13.04.2020 10:00:41

I know this is an old question but I believe that my answer is one that might be helpful to some people who are looking for an easy, simple to understand pythonic way to detect OS in their code. Tested on 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
4
22.01.2020 15:30:51