Search code examples
pythonlinuxoperating-system

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?


Solution

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