我需要看些什么来确定我使用的是Windows还是Unix等等?


当前回答

一个新的答案如何:

import psutil
psutil.MACOS   #True (OSX is deprecated)
psutil.WINDOWS #False
psutil.LINUX   #False 

如果我使用MACOS,这将是输出

其他回答

试试这个:

import os

os.uname()

你可以这样做:

info=os.uname()
info[0]
info[1]

对于Jython,我发现获得操作系统名称的唯一方法是检查os.name Java属性(在WinXP上尝试使用sys, os和平台模块的Jython 2.5.3):

def get_os_platform():
    """return platform name, but for Jython it uses os.name Java property"""
    ver = sys.platform.lower()
    if ver.startswith('java'):
        import java.lang
        ver = java.lang.System.getProperty("os.name").lower()
    print('platform: %s' % (ver))
    return ver

我知道这是一个老问题,但我相信我的答案可能会对那些正在寻找一种简单易懂的python方法来检测代码中的操作系统的人有所帮助。在python3.7上测试

from sys import platform


class UnsupportedPlatform(Exception):
    pass


if "linux" in platform:
    print("linux")
elif "darwin" in platform:
    print("mac")
elif "win" in platform:
    print("windows")
else:
    raise UnsupportedPlatform
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

platform.system()的输出如下:

Linux: Linux 麦克:达尔文 Windows:

参见:平台-访问底层平台的识别数据

这个解决方案适用于python和jython。

模块os_identify.py:

import platform
import os

# This module contains functions to determine the basic type of
# OS we are running on.
# Contrary to the functions in the `os` and `platform` modules,
# these allow to identify the actual basic OS,
# no matter whether running on the `python` or `jython` interpreter.

def is_linux():
    try:
        platform.linux_distribution()
        return True
    except:
        return False

def is_windows():
    try:
        platform.win32_ver()
        return True
    except:
        return False

def is_mac():
    try:
        platform.mac_ver()
        return True
    except:
        return False

def name():
    if is_linux():
        return "Linux"
    elif is_windows():
        return "Windows"
    elif is_mac():
        return "Mac"
    else:
        return "<unknown>" 

像这样使用:

import os_identify

print "My OS: " + os_identify.name()