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


当前回答

我正在使用weblogic附带的WLST工具,它没有实现平台包。

wls:/offline> import os
wls:/offline> print os.name
java 
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'

除了修补系统javaos.py(问题与os.system()在windows 2003与jdk1.5)(我不能这样做,我必须使用weblogic开箱即用),这是我使用的:

def iswindows():
  os = java.lang.System.getProperty( "os.name" )
  return "win" in os.lower()

其他回答

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

您可以查看pip-date包的一部分pyOSinfo中的代码,以获得最相关的操作系统信息,就像您的Python发行版所看到的那样。

人们检查操作系统最常见的原因之一是终端兼容性,以及某些系统命令是否可用。不幸的是,这种检查是否成功在一定程度上取决于你的python安装和操作系统。例如,uname在大多数Windows python包中是不可用的。上面的python程序将向您展示最常用的内置函数的输出,这些函数已经由os, sys, platform, site提供。

因此,只获得基本代码的最好方法是将其视为示例。(我想我可以直接粘贴在这里,但这样做就不政治正确了。)

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

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

对于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和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()