kolek
kolek

Reputation: 3940

How do I check the operating system in Python?

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?

Upvotes: 302

Views: 227281

Answers (6)

Robin_Pip-Slayer
Robin_Pip-Slayer

Reputation: 1

I stumbled across this for all Kivy developers kivy.utils:

from kivy.utils import platform
if platform == 'linux':
    do_linux_things()

Upvotes: 0

Nick Bastin
Nick Bastin

Reputation: 31299

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.

Upvotes: 16

the wolf
the wolf

Reputation: 35512

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?”

Upvotes: 548

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22942

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.

Upvotes: 60

Sven Marnach
Sven Marnach

Reputation: 601351

More detailed information are available in the platform module.

Upvotes: 7

Ondrej Slinták
Ondrej Slinták

Reputation: 31910

You can use sys.platform.

Upvotes: 5

Related Questions