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?
-
3possible duplicate of How can I tell What OS I am running on from Python?BoltClock– BoltClock2011年11月22日 09:52:44 +00:00Commented Nov 22, 2011 at 9:52
-
1Possible duplicate of Python: What OS am I running on?TylerH– TylerH2019年02月24日 16:43:46 +00:00Commented Feb 24, 2019 at 16:43
6 Answers 6
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?"
8 Comments
"cygwin" not "win32" as someone might expect."linux2" is no longer a possible value of platform (see the linked docs for corroboration) and so if you only need to support Python 3.3 and later you can safely delete the ` or platform == "linux2"` clause from the first condition.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.
4 Comments
Linux, Windows, Java or an empty string.devdocs.io/python~3.7/library/platform#platform.system sys.platformYou 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.
1 Comment
More detailed information are available in the platform module.
2 Comments
platform module have any advantage over sys.platform? When would I want to use which approach?platform module. Just click the link for documentation.You can use sys.platform.
Comments
I stumbled across this for all Kivy developers kivy.utils:
from kivy.utils import platform
if platform == 'linux':
do_linux_things()