我需要看些什么来确定我使用的是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()
其他回答
在windows 8上的有趣结果:
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'
编辑:这是一个bug
使用platform.system ()
返回系统/操作系统名称,例如'Linux', 'Darwin', 'Java', 'Windows'。如果无法确定该值,则返回空字符串。
import platform
system = platform.system().lower()
is_windows = system == 'windows'
is_linux = system == 'linux'
is_mac = system == 'darwin'
下面是Mac上的测试结果:
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'
您可以查看pip-date包的一部分pyOSinfo中的代码,以获得最相关的操作系统信息,就像您的Python发行版所看到的那样。
人们检查操作系统最常见的原因之一是终端兼容性,以及某些系统命令是否可用。不幸的是,这种检查是否成功在一定程度上取决于你的python安装和操作系统。例如,uname在大多数Windows python包中是不可用的。上面的python程序将向您展示最常用的内置函数的输出,这些函数已经由os, sys, platform, site提供。
因此,只获得基本代码的最好方法是将其视为示例。(我想我可以直接粘贴在这里,但这样做就不政治正确了。)
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
platform.system()的输出如下:
Linux: Linux 麦克:达尔文 Windows:
参见:平台-访问底层平台的识别数据
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字