python - 如何在 Python 中找到当前的操作系统?

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

最佳答案

如果您想要用户可读的数据但仍然很详细,您可以使用 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'

这里有几个不同的可能的调用,你可以用它来识别你的位置,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

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

https://stackoverflow.com/questions/110362/

相关文章:

linux - 在 Bash 中循环文件的内容

linux - 如何将包含文件的文件夹复制到 Unix/Linux 中的另一个文件夹?

python - 如何禁用 Pylint 警告?

linux - 使用 `find` 时如何排除目录?

python - 用一个空格替换非 ASCII 字符

linux - 如何删除导出的环境变量?

python - 如果键存在,则删除字典项

python - 子进程中 'shell=True'的实际含义

python - 网址在 Python 中解码 UTF-8

linux - 如何在 Linux shell 脚本中提示是/否/取消输入?