How do I check the operating system in Python?

PythonLinuxOperating System

Python Problem Overview


I want to check the operating system (on the computer where the script runs).

I know I can use os.system('uname -o') in Linux, but it gives me a message in the console, and I want to write to a variable.

It will be okay if the script can tell if it is Mac, Windows or Linux. How can I check it?

Python Solutions


Solution 1 - Python

You can use sys.platform:

from sys import platform
if platform == "linux" or platform == "linux2":
    # linux
elif platform == "darwin":
    # OS X
elif platform == "win32":
    # Windows...

sys.platform has finer granularity than sys.name.

For the valid values, consult the documentation.

See also the answer to “What OS am I running on?”

Solution 2 - Python

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.system function uses uname internally.

Solution 3 - Python

You can get a pretty coarse idea of the OS you're using by checking sys.platform.

Once you have that information you can use it to determine if calling something like os.uname() is appropriate to gather more specific information. You could also use something like Python System Information on unix-like OSes, or pywin32 for Windows.

There's also psutil if you want to do more in-depth inspection without wanting to care about the OS.

Solution 4 - Python

More detailed information are available in the platform module.

Solution 5 - Python

You can use sys.platform.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkolekView Question on Stackoverflow
Solution 1 - Pythonthe wolfView Answer on Stackoverflow
Solution 2 - PythonLaurent LAPORTEView Answer on Stackoverflow
Solution 3 - PythonNick BastinView Answer on Stackoverflow
Solution 4 - PythonSven MarnachView Answer on Stackoverflow
Solution 5 - PythonOndrej SlintákView Answer on Stackoverflow