0
0
PythonHow-ToBeginner · 3 min read

How to Check Operating System in Python Quickly and Easily

You can check the operating system in Python using the platform.system() function or the os.name attribute. These provide simple ways to identify if you are running on Windows, Linux, or macOS.
📐

Syntax

Use the platform.system() function to get the OS name as a string like 'Windows', 'Linux', or 'Darwin' (for macOS). Alternatively, os.name gives a shorter code like 'nt' for Windows or 'posix' for Unix-like systems.

  • platform.system(): Returns the OS name as a readable string.
  • os.name: Returns a short code identifying the OS family.
python
import platform
import os

# Get OS name using platform
os_name = platform.system()

# Get OS code using os module
os_code = os.name
💻

Example

This example shows how to print the operating system name using both platform.system() and os.name. It helps you understand which OS your Python code is running on.

python
import platform
import os

print("Using platform.system():", platform.system())
print("Using os.name:", os.name)
Output
Using platform.system(): Linux Using os.name: posix
⚠️

Common Pitfalls

Some beginners expect os.name to return full OS names like 'Windows' or 'Linux', but it returns short codes like 'nt' or 'posix'. Also, platform.system() returns 'Darwin' for macOS, which can be confusing if you expect 'macOS'.

Always check the exact string returned before using it in your code.

python
import platform

# Wrong assumption
if platform.system() == 'macOS':
    print('Running on Mac')
else:
    print('Not Mac')

# Correct check
if platform.system() == 'Darwin':
    print('Running on Mac')
else:
    print('Not Mac')
Output
Not Mac Running on Mac
📊

Quick Reference

Function/AttributeReturnsDescription
platform.system()'Windows', 'Linux', 'Darwin'Full OS name as a string
os.name'nt', 'posix', 'java'Short OS family code
sys.platform'win32', 'linux', 'darwin'Detailed platform identifier

Key Takeaways

Use platform.system() to get a readable operating system name in Python.
os.name returns a short code, not the full OS name, so use it carefully.
For macOS, platform.system() returns 'Darwin', not 'macOS'.
Always test the returned OS string before using it in conditions.
sys.platform is another option for more detailed platform info.