我需要看些什么来确定我使用的是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()

其他回答

如果你运行macOS X并运行platform.system(),你会得到darwin 因为macOS X是基于苹果的达尔文操作系统构建的。Darwin是macOS X的内核,本质上是没有GUI的macOS X。

/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)

有很多方法可以找到这个最简单的方法就是使用OS包

import os 
print(os.name)

这个解决方案适用于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()
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'

platform.system()的输出如下:

Linux: Linux 麦克:达尔文 Windows:

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