【发布时间】:2010-09-11 17:47:34
【问题描述】:
【问题讨论】:
-
Windows:
os.name == 'nt'。 Mac/Linux/BSD:os.name == 'posix'.
标签: python cross-platform platform-specific
【问题讨论】:
os.name == 'nt'。 Mac/Linux/BSD:os.name == 'posix'.
标签: python cross-platform platform-specific
如果你想要用户可读的数据但仍然很详细,你可以使用platform.platform()
>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'
platform还有一些其他有用的方法:
>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'
您可以拨打以下几种不同的电话来确定您的位置
import platform
import sys
def linux_distribution():
try:
return platform.linux_distribution()
except:
return "N/A"
print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))
此脚本的输出可在几个不同的系统(Linux、Windows、Solaris、MacOS)和架构(x86、x64、Itanium、power pc、sparc)上运行:https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version
例如sparc 上的 Solaris 给出:
Python version: ['2.6.4 (r264:75706, Aug 4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')
或 M1 上的 MacOS
Python version: ['2.7.16 (default, Dec 21 2020, 23:00:36) ', '[GCC Apple LLVM 12.0.0 (clang-1200.0.30.4) [+internal-os, ptrauth-isa=sign+stri']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: Darwin
machine: arm64
platform: Darwin-20.3.0-arm64-arm-64bit
uname: ('Darwin', 'Nautilus.local', '20.3.0', 'Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101', 'arm64', 'arm')
version: Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101
mac_ver: ('10.16', ('', '', ''), 'arm64')
我通常使用sys.platform (docs) 来获取平台。 sys.platform 将区分 linux、其他 unix 和 OS X,而 os.name 对于所有这些都是“posix”。
如需更多详细信息,请使用platform module。它具有跨平台功能,可为您提供有关机器架构、操作系统和操作系统版本、Python 版本等的信息。此外,它还具有特定于操作系统的功能,可以获取特定的 linux 发行版等信息。
【讨论】:
platform.system()。看到这个答案:stackoverflow.com/a/58071295/207661。
import os
print os.name
这为您提供了您通常需要的基本信息。例如,要区分不同版本的 Windows,您必须使用特定于平台的方法。
【讨论】:
https://docs.python.org/library/os.html
为了补充 Greg 的帖子,如果您使用的是 posix 系统,包括 MacOS、Linux、Unix 等,您可以使用 os.uname() 来更好地了解它是什么类型的系统。
【讨论】:
类似的东西:
import os
if os.name == "posix":
print(os.system("uname -a"))
# insert other possible OSes here
# ...
else:
print("unknown OS")
【讨论】: