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


当前回答

我在游戏中迟到了,但是,以防有人需要它,这是一个我用来调整我的代码的函数,所以它可以在Windows, Linux和MacOs上运行:

import sys
def get_os(osoptions={'linux':'linux','Windows':'win','macos':'darwin'}):
    '''
    get OS to allow code specifics
    '''   
    opsys = [k for k in osoptions.keys() if sys.platform.lower().find(osoptions[k].lower()) != -1]
    try:
        return opsys[0]
    except:
        return 'unknown_OS'

其他回答

使用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)

使用模块平台检查可用的测试,并打印出适合您系统的答案:

import platform

print dir(platform)

for x in dir(platform):
    if x[0].isalnum():
        try:
            result = getattr(platform, x)()
            print "platform."+x+": "+result
        except TypeError:
            continue

在windows 8上的有趣结果:

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

编辑:这是一个bug

/usr/bin/python3.2

def cls():
    from subprocess import call
    from platform import system

    os = system()
    if os == 'Linux':
        call('clear', shell = True)
    elif os == 'Windows':
        call('cls', shell = True)

Dang -路易斯白兰地打败了我的拳头,但这并不意味着我不能提供你的系统结果为Vista!

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

...我不敢相信居然没有人发布Windows 10的版本:

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