macos 如何使用 Python 检测 Mac OS 版本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1777344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect Mac OS version using Python?
提问by Chris Long
My application is assumed to be running on a Mac OS X system. However, what I need to do is figure out what version of Mac OS (or Darwin) it is running on, preferably as a number. For instance,
假设我的应用程序在 Mac OS X 系统上运行。但是,我需要做的是弄清楚它正在运行的 Mac OS(或 Darwin)版本,最好是一个数字。例如,
- "10.4.11" would return either 10.4 or 8
- "10.5.4" would return 10.5 or 9
- "10.6" would return 10.6 or 10
- “10.4.11”将返回 10.4 或 8
- “10.5.4”将返回 10.5 或 9
- “10.6”将返回 10.6 或 10
I found out that you could do this, which returns "8.11.0" on my system:
我发现你可以这样做,它在我的系统上返回“8.11.0”:
import os
os.system("uname -r")
Is there a cleaner way to do this, or at least a way to pull the first number from the result? Thanks!
有没有更简洁的方法来做到这一点,或者至少有一种方法可以从结果中提取第一个数字?谢谢!
回答by Alex Martelli
>>> import platform
>>> platform.mac_ver()
('10.5.8', ('', '', ''), 'i386')
As you see, the first item of the tuple mac_ver
returns is a string, not a number (hard to make '10.5.8' into a number!-), but it's pretty easy to manipulate the 10.x.y
string into the kind of numbers you want. For example,
如您所见,元组mac_ver
返回的第一项是字符串,而不是数字(很难将 '10.5.8' 变成数字!-),但是很容易将10.x.y
字符串处理为您想要的数字类型。例如,
>>> v, _, _ = platform.mac_ver()
>>> v = float('.'.join(v.split('.')[:2]))
>>> print v
10.5
If you prefer the Darwin kernel version rather than the MacOSX version, that's also easy to access -- use the similarly-formatted string that's the third item of the tuple returned by platform.uname()
.
如果您更喜欢 Darwin 内核版本而不是 MacOSX 版本,这也很容易访问——使用类似格式的字符串,它是platform.uname()
.
回答by dingus9
If you are already using os, you might want to use os.uname()
如果你已经在使用 os,你可能想使用 os.uname()
import os
os.uname()
回答by Abeltang
platform.mac_ver() will return a tuple (release, versioninfo, machine
platform.mac_ver() 将返回一个元组(发布、版本信息、机器
So get mac version by code
所以通过代码获取mac版本
>>> platform.mac_ver()[0]
'10.8.4'
this method is easy
这个方法很简单
回答by agregtheitroade
You could parse the output of the /usr/bin/sw_vers command.
您可以解析 /usr/bin/sw_vers 命令的输出。
回答by Shane C. Mason
If you want to run a command - like 'uname' - and get the results as a string, use the subprocess module.
如果您想运行一个命令——比如“uname”——并以字符串形式获取结果,请使用subprocess 模块。
import subprocess
output = subprocess.Popen(["uname", "-r"], stdout=subprocess.PIPE).communicate()[0]