As far as I know, Python has 3 ways of finding out what operating system is running on:
os.name
sys.platform
platform.system()
Knowing this information is often useful in conditional imports, or using functionality that differs between platforms (e.g. time.clock()
on Windows v.s. time.time()
on UNIX).
My question is, why 3 different ways of doing this? When should one way be used and not another? Which way is the 'best' (most future-proof or least likely to accidentally exclude a particular system which your program can actually run on)?
It seems like sys.platform
is more specific than os.name
, allowing you to distinguish win32
from cygwin
(as opposed to just nt
), and linux2
from darwin
(as opposed to just posix
). But if that's so, that what about the difference between sys.platform
and platform.system()
?
For example, which is better, this:
import sys
if sys.platform == 'linux2':
# Do Linux-specific stuff
or this? :
import platform
if platform.system() == 'Linux':
# Do Linux-specific stuff
For now I'll be sticking to sys.platform
, so this question isn't particularly urgent, but I would be very grateful for some clarification regarding this.
Dived a bit into the source code.
The output of sys.platform
and os.name
are determined at compile time. platform.system()
determines the system type at run time.
sys.platform
is specified as a compiler define during the build configuration.os.name
checks whether certain os specific modules are available (e.g. posix
, nt
, ...)platform.system()
actually runs uname
and potentially several other functions to determine the system type at run time.My suggestion:
os.name
to check whether it's a posix-compliant system.sys.platform
to check whether it's a linux, cygwin, darwin, atheos, etc.platform.system()
if you don't believe the other sources.