seo优化网站快速排名,新乡哪里做网站,海安县住房和城乡建设局网站,网站开发实战教程本文介绍 Python 判断操作系统的3种方法。以下的方法将分为这几部分#xff1a;
Python os.namePython sys.platformPython platform.system()
Python os.name
Python 判断操作系统的方法可以使用 os.name#xff0c;这里以 Python 3 为例#xff0c;os.name 会返回 posi…本文介绍 Python 判断操作系统的3种方法。以下的方法将分为这几部分
Python os.namePython sys.platformPython platform.system()
Python os.name
Python 判断操作系统的方法可以使用 os.name这里以 Python 3 为例os.name 会返回 posix、nt、java 这几种结果。使用前需要先 import os。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
print(os.name)# 在 Ubuntu 16.04 上的输出如下
# posix# 在 MacOS 10.15.7 上的输出如下
# posix# 在 Windows 10 上的输出如下
# nt在 os 模块下还有另一个 uname() 函数可以使用uname() 会返回操作系统相关的版本信息。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
print(os.uname())# 在 Ubuntu 16.04 上的输出如下
# sysnameLinux, nodenameshengyu, release4.10.0-40-generic, version#44~16.04.1-Ubuntu SMP Thu Nov 9 15:37:44 UTC 2017, machinex86_64# 在 MacOS 10.15.7 上的输出如下
# posix.uname_result(sysnameDarwin, nodenameshengyudeMacBook-Pro.local, release19.6.0, versionDarwin Kernel Version 19.6.0: Thu Sep 16 20:58:47 PDT 2021; root:xnu-6153.141.40.1~1/RELEASE_X86_64, machinex86_64)# Windows 下没有 os.uname()sys.platform 有更细的分类下一节会介绍。
Python sys.platform
sys.platform 返回的结果有以下几种情况
AIX: aixLinux: linuxWindows: win32Windows/Cygwin: cygwinmacOS: darwin
如果要用 sys.platform 判断操作系统可以使用 startswith()像 linux 与 linux2 的情况就可以被包含在以 linux 开头的字符串写在同一个条件式里。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sysif sys.platform.startswith(linux):print(Linux)
elif sys.platform.startswith(darwin):print(macOS)
elif sys.platform.startswith(win32):print(Windows)Python platform.system()
Python 判断操作系统的方法可以使用 platform.system() 函数platform.system() 会返回操作系统的名称例如Linux、Darwin、Java、Windows 这几种。如果无法判断操作系统的话会返回空字符串。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import platformprint(platform.system())
print(platform.release())# 在 Ubuntu 16.04 上的输出如下
# Linux
# 4.10.0-40-generic# 在 MacOS 10.15.7 上的输出如下
# Darwin
# 19.6.0# 在 Windows 10 上的输出如下
# Windows
# 10