何时使用os.name,sys.platform或platform.system? [英] When to use os.name, sys.platform, or platform.system?
问题描述
据我所知,Python有3种方法来找出运行什么操作系统:
As far as I know, Python has 3 ways of finding out what operating system is running on:
-
os.name
-
sys.platform
-
platform.system()
os.name
sys.platform
platform.system()
知道此信息通常在条件导入中或在不同平台之间使用不同功能(例如,Windows上的time.clock()
相对于UNIX上的time.time()
)时很有用.
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).
我的问题是,为什么要用3种不同的方式来做到这一点?什么时候应该使用一种方法而不是另一种方法?哪种方法是最好的"(最有前瞻性或最不可能偶然排除程序可以在其上实际运行的特定系统)?
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)?
似乎sys.platform
比os.name
更具体,可让您将win32
与cygwin
(与仅nt
相对)和linux2
与darwin
(与只需posix
).但是,如果是这样的话,那sys.platform
和platform.system()
之间的区别呢?
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()
?
例如,更好的方法是:
import sys
if sys.platform == 'linux2':
# Do Linux-specific stuff
还是这个? :
import platform
if platform.system() == 'Linux':
# Do Linux-specific stuff
现在我将坚持使用sys.platform
,因此这个问题并不是特别紧迫,但我将非常感谢您对此进行的澄清.
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.
推荐答案
深入研究源代码.
sys.platform
和os.name
的输出在编译时确定. platform.system()
确定运行时的系统类型.
The output of sys.platform
and os.name
are determined at compile time. platform.system()
determines the system type at run time.
-
在构建配置期间,
-
sys.platform
被指定为编译器定义. -
os.name
检查某些操作系统特定的模块是否可用(例如posix
,nt
,...) -
platform.system()
实际上运行uname
并可能运行其他几个功能来在运行时确定系统类型.
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 runsuname
and potentially several other functions to determine the system type at run time.
我的建议:
- 使用
os.name
检查它是否为posix兼容系统. - 使用
sys.platform
检查它是否是linux,cygwin,darwin,atheos等. - 如果您不相信其他来源,请使用
platform.system()
.
- Use
os.name
to check whether it's a posix-compliant system. - Use
sys.platform
to check whether it's a linux, cygwin, darwin, atheos, etc. - Use
platform.system()
if you don't believe the other sources.
这篇关于何时使用os.name,sys.platform或platform.system?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!