使用Python平臺模組獲取硬體和系統資訊。


Python 是一種通用的指令碼語言,用途廣泛。因此,可以完成許多自動化任務以及指令碼編寫。獲取系統資訊在許多應用(例如機器學習、深度學習等)中成為一項重要任務,因為硬體在其中扮演著至關重要的角色。Python 提供了幾種方法來收集有關作業系統和硬體的資訊。

獲取整體系統配置

Python 中的 platform 模組提供了一種以獨立於平臺的方式獲取整體系統配置的方法。因此,我們可以在不知道平臺的情況下執行相同的方法來獲取系統配置。system 方法允許我們獲取有關作業系統的 資訊,例如“Windows”、“Linux”或“Darwin”(對於 macOS)。該方法還會返回系統版本和發行日期。

示例

import platform
system_info = platform.uname()
print("System Info:", system_info)

輸出

System Info: uname_result(system='Linux', node='asifr-Nitro-AN515-45', release='5.19.0-43-generic', version='#44~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Mon May 22 13:39:36 UTC 2', machine='x86_64')

獲取系統資訊

平臺是我們用來執行所有應用程式的作業系統。這可以是 Linux、Windows、Mac OS 等。我們可以使用 platform 庫來獲取名稱、發行日期、機器等資訊。此類資訊有助於獲取系統資訊及其功能。這在機器學習等領域至關重要,在機器學習中,硬體對於加速過程具有重要意義。

示例

import platform
system_name = platform.system()
system_release = platform.release()
system_architecture = platform.machine()
system_aliases = platform.platform()
print("The system details are as follows:")
print("Operating System:", system_name)
print("Release Version:", system_release)
print("System Architecture:", system_architecture)
print("Systemaliases:", system_aliases)

輸出

The system details are as follows:
Operating System: Linux
Release Version: 5.19.0-43-generic
System Architecture: x86_64
Systemaliases: Linux-5.19.0-43-generic-x86_64-with-glibc2.35

獲取CPU資訊

platform 模組還允許我們獲取有關處理器的資訊。但是,該模組無法提供有關處理器的詳細資訊,例如時鐘速度等。它只能提供諸如設計架構之類的資訊。

示例

在下面的程式碼中,我們首先匯入了 platform 模組。接下來,我們建立了函式 get_cpu_info。該函式使用 platform 模組的 process 方法獲取 CPU 資訊並將其返回。接下來,我們呼叫該函式並列印結果。

import platform
def get_cpu_info():
    cpu_info = platform.processor()
    return cpu_info
cpu = get_cpu_info()
print("CPU Information:")
print("Processor:", cpu)
print("Architecture:", platform.machine())

輸出

CPU Information:
Processor: x86_64
Architecture: x86_64

結論

在本文中,我們瞭解瞭如何使用 Python 庫獲取系統和硬體資訊。Python 是一種通用的指令碼語言,它提供了多種與硬體和軟體互動的方式。Python 中有多個庫,例如 psutil、GPUtil 等,可以用來獲取系統和硬體資訊。

更新於:2023年7月18日

瀏覽量:585

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.