问题描述
据我所知,Python 有 3 种方法可以找出正在运行的操作系统:
As far as I know, Python has 3 ways of finding out what operating system is running on:
操作系统名称sys.platformplatform.system()
了解这些信息在条件导入或使用不同平台的功能时通常很有用(例如,Windows 上的 time.clock() 与 time.time() 上UNIX).
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),以及来自 darwin 的 linux2(而不是仅仅 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()?
例如,哪个更好,这个:
For example, which is better, this:
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.platformis specified as a compiler define during the build configuration.os.namechecks whether certain os specific modules are available (e.g.posix,nt, ...)platform.system()actually runsunameand 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.nameto check whether it's a posix-compliant system. - Use
sys.platformto 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)