首页 文章

如何在Python中检查操作系统?

提问于
浏览
97

我想检查操作系统(在脚本运行的计算机上) .

我知道我可以在Linux中使用 os.system('uname -o') ,但它在控制台中给我一条消息,我想写一个变量 .

如果脚本可以判断它是Mac,Windows还是Linux,那也没关系 . 我怎么检查呢?

6 回答

  • 14

    更多详细信息,请参见platform module .

  • 10

    你可以使用sys.platform

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

    sys.platform 的粒度比 sys.name 更精细 .

    有关有效值,请参阅the documentation .

  • 3

    你可以使用sys.platform .

  • 7

    如果你想知道你是哪个平台:“Linux”,“Windows”或“Darwin”(Mac)没有更高的精度,你应该使用:

    >>> import platform
    >>> platform.system()
    'Linux'  # or 'Windows'/'Darwin'
    

    platform.system函数在内部使用 uname .

  • -3

    通过检查sys.platform,您可以非常了解您正在使用的操作系统 .

    获得该信息后,您可以使用它来确定调用类似os.uname()的内容是否适合收集更具体的信息 . 你也可以在类似unix的操作系统上使用类似Python System Information的东西,或者在Windows上使用pywin32 .

    如果你想进行更深入的检查而不想关心操作系统,那么还有psutil .

  • 200

    关于Windows如何识别,似乎存在一些相互矛盾的信息 . 一些消息来源称“Windows”,其他消息来源称“win32” .

    考虑到这一点...

    from sys import platform
    
    if "win" in platform.lower():
        print platform
    
    win32
    

    但在Cygwin中可能也是如此 . 但你可以随时添加一个检查,以确保“cy”不在那里 .

相关问题