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


当前回答

这个解决方案适用于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()

其他回答

你也可以使用sys。平台,如果你已经导入了sys,你不想导入另一个模块

>>> import sys
>>> sys.platform
'linux2'

在windows 8上的有趣结果:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'

编辑:这是一个bug

使用Python区分操作系统的示例代码:

import sys

if sys.platform.startswith("linux"):  # could be "linux", "linux2", "linux3", ...
    # linux
elif sys.platform == "darwin":
    # MAC OS X
elif os.name == "nt":
    # Windows, Cygwin, etc. (either 32-bit or 64-bit)

使用platform.system ()

返回系统/操作系统名称,例如'Linux', 'Darwin', 'Java', 'Windows'。如果无法确定该值,则返回空字符串。

import platform
system = platform.system().lower()

is_windows = system == 'windows'
is_linux = system == 'linux'
is_mac = system == 'darwin'

试试这个:

import os

os.uname()

你可以这样做:

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