作为 Python 开发人员,使用第三方库来完成您真正想要的工作是很方便的,而不是每次都重新发明轮子。在本教程中,您将熟悉psutil,它是Python 中用于进程和系统监控的跨平台库,以及用于在 Python 中提取系统和硬件信息的内置平台模块。
最后,我将向您展示如何打印 GPU 信息(当然,如果您有的话)。
这是本教程的目录:
系统信息CPU信息内存使用情况磁盘使用情况网络信息图形处理器信息相关: 如何使用 ipaddress 模块在 Python 中 *** 作 IP 地址。
在我们深入研究之前,您需要安装 psutil:
pip3 install psutil
复制打开一个新的 python 文件,让我们开始,导入必要的模块:
import psutilimport platformfrom datetime import datetime
复制让我们创建一个函数,将大量字节转换为缩放格式(例如,以千、兆、千兆等为单位):
def get_size(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor
复制系统信息我们在这里需要平台模块:
print("="*40, "System information", "="*40)uname = platform.uname()print(f"System: {uname.system}")print(f"Node name: {uname.node}")print(f"Release: {uname.release}")print(f"Version: {uname.version}")print(f"Machine: {uname.machine}")print(f"Processor: {uname.processor}")
复制获取计算机启动的日期和时间:
# Boot Timeprint("="*40, "Boot Time", "="*40)boot_time_timestamp = psutil.boot_time()bt = datetime.fromtimestamp(boot_time_timestamp)print(f"Boot Time: {bt.year}/{bt.month}/{bt.day} {bt.hour}:{bt.minute}:{bt.second}")
复制cpu信息让我们获取一些 cpu 信息,例如总内核数、使用情况等:
# let's print cpu informationprint("="*40, "cpu Info", "="*40)# number of coresprint("Physical cores:", psutil.cpu_count(logical=False))print("Total cores:", psutil.cpu_count(logical=True))# cpu frequencIEscpufreq = psutil.cpu_freq()print(f"Max Frequency: {cpufreq.max:.2f}Mhz")print(f"Min Frequency: {cpufreq.min:.2f}Mhz")print(f"Current Frequency: {cpufreq.current:.2f}Mhz")# cpu usageprint("cpu Usage Per Core:")for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)): print(f"Core {i}: {percentage}%")print(f"Total cpu Usage: {psutil.cpu_percent()}%")
复制psutil的cpu_count()函数返回内核数,而cpu_freq()函数返回 cpu 频率,namedtuple
包括以 Mhz 表示的当前、最小和最大频率,您可以设置percpu=True
为获取每个 cpu 频率。
cpu_percent()方法返回一个浮点数,表示当前 cpu 利用率的百分比,设置interval
为 1(秒)将比较一秒前后经过的系统 cpu 时间,我们设置percpu
为True
以获取每个内核的 cpu 使用率。
# Memory informationprint("="*40, "Memory information", "="*40)# get the memory detailssvmem = psutil.virtual_memory()print(f"Total: {get_size(svmem.total)}")print(f"Available: {get_size(svmem.available)}")print(f"Used: {get_size(svmem.used)}")print(f"Percentage: {svmem.percent}%")print("="*20, "SWAP", "="*20)# get the swap memory details (if exists)swap = psutil.swap_memory()print(f"Total: {get_size(swap.total)}")print(f"Free: {get_size(swap.free)}")print(f"Used: {get_size(swap.used)}")print(f"Percentage: {swap.percent}%")
复制virtual_memory()方法返回有关系统内存使用情况的统计信息namedtuple
,包括(可用total
物理内存总量)、available
(可用内存,即未使用)used
和percent
(即百分比)等字段。swap_memory()是相同的,但用于交换内存。
我们使用先前定义的get_size()函数以缩放方式打印值,因为这些统计信息以字节表示。
磁盘使用情况
# disk informationprint("="*40, "disk information", "="*40)print("Partitions and Usage:")# get all disk partitionspartitions = psutil.disk_partitions()for partition in partitions: print(f"=== Device: {partition.device} ===") print(f" Mountpoint: {partition.mountpoint}") print(f" file system type: {partition.fstype}") try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: # this can be catched due to the disk that # isn't ready continue print(f" Total Size: {get_size(partition_usage.total)}") print(f" Used: {get_size(partition_usage.used)}") print(f" Free: {get_size(partition_usage.free)}") print(f" Percentage: {partition_usage.percent}%")# get IO statistics since bootdisk_io = psutil.disk_io_counters()print(f"Total read: {get_size(disk_io.read_bytes)}")print(f"Total write: {get_size(disk_io.write_bytes)}")
复制正如预期的那样,disk_usage()函数将磁盘使用统计信息返回为namedtuple
,包括total
,used
以及free
以字节表示的空间。
# Network informationprint("="*40, "Network information", "="*40)# get all network interfaces (virtual and physical)if_addrs = psutil.net_if_addrs()for interface_name, interface_addresses in if_addrs.items(): for address in interface_addresses: print(f"=== Interface: {interface_name} ===") if str(address.family) == 'AddressFamily.AF_INET': print(f" IP Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" broadcast IP: {address.broadcast}") elif str(address.family) == 'AddressFamily.AF_PACKET': print(f" MAC Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" broadcast MAC: {address.broadcast}")# get IO statistics since bootnet_io = psutil.net_io_counters()print(f"Total Bytes Sent: {get_size(net_io.bytes_sent)}")print(f"Total Bytes Received: {get_size(net_io.bytes_recv)}")
复制net_if_addrs()函数返回与系统上安装的每个网络接口卡相关联的地址。
好的,这是我个人 linux 机器的结果输出:
<span ><span ><span ><span ><code >======================================== System information ========================================System: linuxNode name: rockikzRelease: 4.17.0-kali1-amd64Version: #1 SMP Debian 4.17.8-1kali1 (2018-07-24)Machine: x86_64Processor:======================================== Boot Time ========================================Boot Time: 2019/8/21 9:37:26======================================== cpu Info ========================================Physical cores: 4Total cores: 4Max Frequency: 3500.00MhzMin Frequency: 1600.00MhzCurrent Frequency: 1661.76Mhzcpu Usage Per Core:Core 0: 0.0%Core 1: 0.0%Core 2: 11.1%Core 3: 0.0%Total cpu Usage: 3.0%======================================== Memory information ========================================Total: 3.82GBAvailable: 2.98GBUsed: 564.29MBPercentage: 21.9%==================== SWAP ====================Total: 0.00BFree: 0.00BUsed: 0.00BPercentage: 0%======================================== disk information ========================================Partitions and Usage:=== Device: /dev/sda1 === Mountpoint: / file system type: ext4 Total Size: 451.57GB Used: 384.29GB Free: 44.28GB Percentage: 89.7%Total read: 2.38GBTotal write: 2.45GB======================================== Network information =========================================== Interface: lo === IP Address: 127.0.0.1 Netmask: 255.0.0.0 broadcast IP: None=== Interface: lo ====== Interface: lo === MAC Address: 00:00:00:00:00:00 Netmask: None broadcast MAC: None=== Interface: wlan0 === IP Address: 192.168.1.101 Netmask: 255.255.255.0 broadcast IP: 192.168.1.255=== Interface: wlan0 ====== Interface: wlan0 === MAC Address: 64:70:02:07:40:50 Netmask: None broadcast MAC: ff:ff:ff:ff:ff:ff=== Interface: eth0 === MAC Address: d0:27:88:c6:06:47 Netmask: None broadcast MAC: ff:ff:ff:ff:ff:ffTotal Bytes Sent: 123.68MBTotal Bytes Received: 577.94MB</code></span></span></span></span>
复制
如果您使用的是笔记本电脑,则可以使用 psutil.sensors_battery() 获取电池信息。
另外,如果你是一个linux用户,你可以使用 psutil.sensors_fan() 来获得风扇的RPM(每分钟转数) ,也 psutil.sensors_temperatures() 来获得各种设备的温度。
图形处理器信息psutil不向我们提供 GPU 信息。因此,我们需要安装GPUtil:
pip3 install gputil
复制GPUtil是一个 Python 模块,仅用于获取 NVIDIA GPU 的 GPU 状态,它定位计算机上的所有 GPU,确定它们的可用性并返回可用 GPU 的有序列表。它需要安装最新的 NVIDIA 驱动程序。
此外,我们需要安装tabulate 模块,这将允许我们以表格方式打印 GPU 信息:
pip3 install tabulate
复制
以下代码行打印您机器中的所有 GPU 及其详细信息:
# GPU informationimport GPUtilfrom tabulate import tabulateprint("="*40, "GPU Details", "="*40)gpus = GPUtil.getGPUs()List_gpus = []for gpu in gpus: # get the GPU ID gpu_ID = gpu.ID # name of GPU gpu_name = gpu.name # get % percentage of GPU usage of that GPU gpu_load = f"{gpu.load*100}%" # get free memory in MB format gpu_free_memory = f"{gpu.memoryFree}MB" # get used memory gpu_used_memory = f"{gpu.memoryUsed}MB" # get total memory gpu_total_memory = f"{gpu.memoryTotal}MB" # get GPU temperature in Celsius gpu_temperature = f"{gpu.temperature} °C" gpu_uuID = gpu.uuID List_gpus.append(( gpu_ID, gpu_name, gpu_load, gpu_free_memory, gpu_used_memory, gpu_total_memory, gpu_temperature, gpu_uuID ))print(tabulate(List_gpus, headers=("ID", "name", "load", "free memory", "used memory", "total memory", "temperature", "uuID")))
复制这是我机器中的输出:
======================================== GPU Details ======================================== ID name load free memory used memory total memory temperature uuID---- ---------------- ------ ------------- ------------- -------------- ------------- ---------------------------------------- 0 GeForce GTX 1050 2.0% 3976.0MB 120.0MB 4096.0MB 52.0 °C GPU-c9b08d82-f1e2-40b6-fd20-543a4186d6ce
复制太好了,现在您可以将这些信息集成到您的 Python 监视器应用程序和实用程序中!
检查我们在本教程中使用的库的文档:
平台 - 访问底层平台的识别数据psutil 的官方文档GPUtil 文档
您还可以使用 psutil 来 监控 *** 作系统进程,例如每个进程的 cpu 和内存使用情况等。
总结
以上是内存溢出为你收集整理的在 Python 中获取硬件和系统信息全部内容,希望文章能够帮你解决在 Python 中获取硬件和系统信息所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)