溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Linux Python中處理系統(tǒng)硬件信息獲取

發(fā)布時間:2024-09-12 11:58:47 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在 Linux 系統(tǒng)中,可以使用 Python 的各種庫來獲取和處理硬件信息

  1. 使用 ossubprocess 模塊執(zhí)行系統(tǒng)命令并解析輸出:
import os
import subprocess

def get_cpu_info():
    command = "lscpu"
    result = subprocess.run(command.split(), stdout=subprocess.PIPE)
    output = result.stdout.decode('utf-8')
    cpu_info = {}
    for line in output.split('\n'):
        if ':' in line:
            key, value = line.split(':', 1)
            cpu_info[key.strip()] = value.strip()
    return cpu_info

print(get_cpu_info())
  1. 使用 psutil 庫獲取系統(tǒng)和進程信息:

首先安裝 psutil 庫:

pip install psutil

然后使用以下代碼獲取 CPU、內(nèi)存和磁盤信息:

import psutil

def get_system_info():
    system_info = {
        'cpu': {
            'count': psutil.cpu_count(),
            'percent': psutil.cpu_percent()
        },
        'memory': {
            'total': psutil.virtual_memory().total,
            'available': psutil.virtual_memory().available,
            'percent': psutil.virtual_memory().percent
        },
        'disk': {
            'total': psutil.disk_usage('/').total,
            'used': psutil.disk_usage('/').used,
            'percent': psutil.disk_usage('/').percent
        }
    }
    return system_info

print(get_system_info())
  1. 使用 py-cpuinfo 庫獲取詳細的 CPU 信息:

首先安裝 py-cpuinfo 庫:

pip install py-cpuinfo

然后使用以下代碼獲取 CPU 信息:

import cpuinfo

def get_detailed_cpu_info():
    cpu_info = cpuinfo.get_cpu_info()
    return cpu_info

print(get_detailed_cpu_info())
  1. 使用 netifaces 庫獲取網(wǎng)絡接口信息:

首先安裝 netifaces 庫:

pip install netifaces

然后使用以下代碼獲取網(wǎng)絡接口信息:

import netifaces as ni

def get_network_interfaces():
    network_interfaces = {}
    for interface in ni.interfaces():
        addresses = ni.ifaddresses(interface)
        network_interfaces[interface] = {
            'ipv4': addresses.get(ni.AF_INET),
            'ipv6': addresses.get(ni.AF_INET6),
            'mac': addresses.get(ni.AF_LINK)
        }
    return network_interfaces

print(get_network_interfaces())

這些示例僅展示了如何使用 Python 獲取硬件信息。根據(jù)需要,可以結(jié)合其他庫或方法來獲取更多詳細信息。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI