据我所知,Python有三种方法来查找运行什么操作系统:
os.namesys.platformplatform.system()了解这些信息通常在条件导入中很有用,或者使用不同平台的功能(例如WindowsV.S.UNIX上的time.clock()。time.time() )。
我的问题是,为什么有三种不同的方法?什么时候应该使用一种方式而不是另一种方式?哪种方式是“最好的”(最适合将来使用,或者最不可能意外地排除程序实际运行的特定系统)?
sys.platform似乎比os.name更具体,它允许您区分win32与cygwin (相对于仅nt),以及linux2与darwin (与posix相反)。但如果是这样,那sys.platform和platform.system()之间的区别呢?
例如,更好的是:
import sys
if sys.platform == 'linux2':
# Do Linux-specific stuff还是这个?
import platform
if platform.system() == 'Linux':
# Do Linux-specific stuff现在我将坚持使用sys.platform,所以这个问题并不是特别紧迫,但是我非常感谢您对此作出一些澄清。
发布于 2012-07-26 17:43:48
深入到源代码中。
在编译时确定sys.platform和os.name的输出。platform.system()在运行时确定系统类型。
sys.platform在编译过程中被指定为编译器定义,用于检查某些os特定模块是否可用(例如,posix、nt、...)platform.system()实际上运行uname,以及在运行时可能运行几个其他函数来确定系统类型。我的建议:
os.name检查它是否符合posix标准,sys.platform检查它是否是linux、cygwin、达尔文、无神论等等。platform.system() (如果你不相信其他来源)。H 226f 227发布于 2013-01-13 05:58:35
platform.system()和sys.platform之间有细微的差别,有趣的是,在大多数情况下,platform.system()退化为sys.platform。
以下是源Python2.7\Lib\Platform.py\system所说的
def system():
""" Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined.
"""
return uname()[0]
def uname():
# Get some infos from the builtin os.uname API...
try:
system,node,release,version,machine = os.uname()
except AttributeError:
no_os_uname = 1
if no_os_uname or not filter(None, (system, node, release, version, machine)):
# Hmm, no there is either no uname or uname has returned
#'unknowns'... we'll have to poke around the system then.
if no_os_uname:
system = sys.platform
release = ''
version = ''
node = _node()
machine = ''也是根据documentation
os.uname()
返回一个包含标识当前操作系统的信息的5元组。元组包含5个字符串:(sysname、nodename、release、version、machine)。有些系统将节点名截断为8个字符或前面的组件;获得主机名的更好方法是socket.gethostname(),甚至是socket.gethostbyaddr(socket.gethostname())。
可用性: Unix.的最新版本
发布于 2012-07-26 15:21:32
来自sys.platform docs
os.name有一个更粗的granularityos.uname()给出了依赖于系统的版本informationplatform模块提供了对系统标识的详细检查。
通常,测试某些功能是否可用的“最好的”未来验证方法就是尝试使用它,如果失败了就使用备用。
sys.platform和platform.system()之间的区别是什么?
platform.system()返回一个规范化值,它可能从几个来源获得:os.uname()、sys.platform、ver命令(在Windows上)。
https://stackoverflow.com/questions/4553129
复制相似问题