使用sys模块
import sys
if sys.platform.startswith("win"):
print("当前系统是Windows")
elif sys.platform.startswith("linux"):
print("当前系统是Linux")
elif sys.platform.startswith("darwin"):
print("当前系统是Mac OS")
else:
print("当前系统是其他操作系统")
sys.platform 会返回当前系统平台的标识符,Linux 是 ‘linux’、Windows 是 ‘win32’ 或者 ‘win64’、macOS 是 ‘darwin’,可以使用 startswith() 函数来进行判断。
使用platform模块
import platform
system = platform.system()
if system == "Windows":
print("当前系统是Windows")
elif system == "Linux":
print("当前系统是Linux")
elif system == "Darwin":
print("当前系统是Mac OS")
else:
print("当前系统是其他操作系统")
使用os模块
import os
system = os.name
if system == "nt":
print("当前系统是Windows")
elif system == "posix":
print("当前系统是Linux或Mac OS")
else
print("当前系统是其他操作系统")
本文介绍了如何使用Python的sys、platform和os模块来检测运行环境的系统类型,分别通过`sys.platform.startswith()`、`platform.system()`和`os.name`属性判断Windows、Linux、MacOS等不同操作系统。
176

被折叠的 条评论
为什么被折叠?



