正如标题所说,如何在python中找到当前的操作系统?


https://docs.python.org/library/os.html

为了补充Greg的文章,如果你使用的是posix系统,包括MacOS、Linux、Unix等,你可以使用os.uname()来更好地了解它是什么类型的系统。

import os
print(os.name)

这将为您提供通常需要的基本信息。为了区分不同版本的Windows,您必须使用特定于平台的方法。

我通常使用sys。平台获得平台。sys。平台将区分linux,其他unix和OS X,而OS .name为“posix”。

要获得更详细的信息,请使用平台模块。它有跨平台的功能,会给你关于机器架构、操作系统和操作系统版本、Python版本等的信息。它还具有特定于操作系统的函数来获取特定的linux发行版之类的东西。

大致如下:

import os
if os.name == "posix":
    print(os.system("uname -a"))
# insert other possible OSes here
# ...
else:
    print("unknown OS")

如果你想要用户可读的数据但仍然是详细的,你可以使用platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

平台还有其他一些有用的方法:

>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'

这里有一些不同的调用,你可以通过它们来确定你的位置,linux_distribution和dist似乎已经从最近的python版本中消失了,所以它们在这里有一个包装器函数。

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

def dist():
  try:
    return platform.dist()
  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(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

Solaris在sparc上给出:

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')