使用Python检测操作系统

11

我在寻找解决我的问题的方法,最好的方法是这个:

from sys import platform
if platform == "linux" or platform == "linux2":
    # linux
elif platform == "darwin":          
    # OS X
elif platform == "win32":             
    # Windows...

有没有人知道如何区分Linux PC和基于Linux的Android设备。如果有可能,如何区分Mac OS和iOS。

4个回答

15

使用platform模块:

import platform
print(platform.system())
print(platform.release())
print(platform.version())
请注意,运行在Mac上的系统将返回platform.system()的值为'Darwin'。 platform.platform()将返回非常详细的数据,例如
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

11

你可以查看我的 GitHub 存储库 https://github.com/sk3pp3r/PyOS 并使用 pyos.py 脚本

import platform 
plt = platform.system()

if plt == "Windows":
    print("Your system is Windows")
    # do x y z
elif plt == "Linux":
    print("Your system is Linux")
    # do x y z
elif plt == "Darwin":
    print("Your system is MacOS")
    # do x y z
else:
    print("Unidentified system")

2
如果您想使用标准库,我建议您查看https://docs.python.org/3/library/sys.html#sys.platform
示例:
import sys

if sys.platform.startswith('linux'):
    # Linux specific procedures
elif sys.platform.startswith('darwin'):
    # MacOs specific procedures
elif sys.platform.startswith('win32'):
    # Windows specific procedures

2

根据我的个人经验,os.uname() 一直是我最喜欢的函数之一。这个 uname 函数实际上只存在于基于 Linux 的系统中。使用类似这样的方法调用该函数,是检测您是否正在运行 Windows 系统的好方法:

import os

try:
    test = os.uname()
    if test[0] == "Linux":
        do something here.
execpt AttributeError:
    print("Assuming windows!")
    do some other stuff here.


我希望这可以帮到您!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接