Python内置模块之platform详细功能介绍及示例
模块是获取系统信息的利器,特别适用于编写跨平台脚本或需要适配不同环境的程序。通过上述方法,开发者可以轻松获取操作系统、硬件架构、Python版本等关键信息,从而优化代码逻辑或生成详细报告。模块提供了多种方法用于获取与系统、硬件和Python解释器相关的详细信息。
·
Python的platform模块提供了多种方法用于获取与系统、硬件和Python解释器相关的详细信息。以下是该模块的主要方法及其说明和示例:
1. platform.system()
- 作用: 返回操作系统的名称(如
Windows,Linux,Darwin)。 - 示例:
import platform print(platform.system()) # 输出: 'Windows'、'Linux' 或 'Darwin'
2. platform.platform()
- 作用: 返回详细的系统标识字符串,包含版本和硬件信息。
- 参数:
aliased: 显示别名(如将Win版本转为易读名称)。terse: 简化输出。
- 示例:
print(platform.platform(aliased=True)) # 输出(Windows): Windows-10-10.0.19041-SP0 # 输出(Linux): Linux-5.15.0-56-generic-x86_64-with-glibc2.35
3. platform.machine()
- 作用: 返回机器架构类型(如
x86_64,arm64)。 - 示例:
print(platform.machine()) # 输出: 'x86_64'(Intel/Mac)或 'AMD64'(Windows)
4. platform.processor()
- 作用: 返回处理器型号(不同平台结果差异较大)。
- 示例:
print(platform.processor()) # 输出(Windows): Intel64 Family 6 Model 142 Stepping 12, GenuineIntel # 输出(Linux): Intel(R) Core(TM) i7-8650U CPU
5. platform.node()
- 作用: 返回计算机的网络名称(可能被用户修改过)。
- 示例:
print(platform.node()) # 输出: 'MyLaptop' 或类似主机名
6. platform.version()
- 作用: 返回操作系统版本号(如Windows的构建版本)。
- 示例:
print(platform.version()) # 输出(Windows): 10.0.19045
7. platform.release()
- 作用: 返回操作系统的发布信息(如Linux内核版本)。
- 示例:
print(platform.release()) # 输出(Linux): 5.15.0-56-generic
8. platform.architecture()
- 作用: 返回Python解释器的位数和文件格式。
- 示例:
print(platform.architecture()) # 输出: ('64bit', 'WindowsPE') 或 ('64bit', 'ELF')
9. platform.python_version()
- 作用: 返回Python版本字符串(如
3.9.7)。 - 示例:
print(platform.python_version()) # 输出: '3.11.4'
10. platform.python_compiler()
- 作用: 返回编译Python解释器所用的编译器信息。
- 示例:
print(platform.python_compiler()) # 输出: GCC 9.4.0(Linux)或 MSC v.1935 64 bit (AMD64)(Windows)
11. platform.uname()
- 作用: 返回包含系统信息的元组(类似
os.uname())。 - 返回值:
(system, node, release, version, machine, processor)。 - 示例:
print(platform.uname()) # 输出(Windows): uname_result(system='Windows', node='DESKTOP-ABC', release='10', version='10.0.19045', machine='AMD64', processor='Intel64 Family 6 Model 142 Stepping 12, GenuineIntel')
12. platform.python_implementation()
- 作用: 返回Python实现名称(如
CPython,PyPy)。 - 示例:
print(platform.python_implementation()) # 输出: 'CPython'
使用场景示例
-
跨平台兼容性检查:
if platform.system() == 'Linux': print("Running on Linux!") elif platform.system() == 'Windows': print("Hello Windows user!") -
生成系统报告:
print(f""" System Report: OS: {platform.system()} {platform.release()} Architecture: {platform.machine()} Python Version: {platform.python_version()} """)
总结
platform模块是获取系统信息的利器,特别适用于编写跨平台脚本或需要适配不同环境的程序。通过上述方法,开发者可以轻松获取操作系统、硬件架构、Python版本等关键信息,从而优化代码逻辑或生成详细报告。
更多推荐



所有评论(0)