Python: What OS am I running on?

Tags: python

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


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

>>> import platform
>>> 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]
By : G M

Just for completeness, "OS" environment variable seems to be defined everywhere. On Windows XP/7/8/10 it is set to "Windows_NT". On Linux SuSE SP2 it is set to "x86-64 linux sles11[2]". I don't have access to OS-X or BSD machines, would be interesting to check there as well.

import os

os_name = os.getenv("OS")
if os_name == "Windows_NT":
    # Windows
elif "linux" in os_name:
    # Linux
elif ...

For the record here's the results on Mac:

>>> import os
>>> import platform
>>> platform.system()
>>> platform.release()

This video can help you solving your question :)
By: admin