Hướng dẫn python get hardware information - python lấy thông tin phần cứng

& nbsp; · 7 phút Đọc · Cập nhật tháng 6 năm 2022 · Hướng dẫn chung của Python · 7 min read · Updated jun 2022 · General Python Tutorials

Tiết lộ: Bài đăng này có thể chứa các liên kết liên kết, có nghĩa là khi bạn nhấp vào liên kết và mua hàng, chúng tôi nhận được hoa hồng.: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.

Là một nhà phát triển Python, thật tiện dụng khi sử dụng các thư viện của bên thứ ba thực hiện công việc bạn thực sự muốn, thay vì phát minh lại bánh xe mỗi lần. Trong hướng dẫn này, bạn sẽ quen thuộc với

import psutil
import platform
from datetime import datetime
4, một thư viện đa nền tảng để giám sát quy trình và hệ thống trong Python, cũng như nền tảng tích hợp & NBSP; Mô-đun để trích xuất thông tin hệ thống và phần cứng của bạn trong Python.ross-platform library for process and system monitoring in Python, as well as the built-in platform module to extract your system and hardware information in Python.

Cuối cùng, tôi sẽ chỉ cho bạn cách bạn có thể in thông tin GPU (tất nhiên là nếu bạn có thông tin).

Có các công cụ khá phổ biến để trích xuất thông tin hệ thống và phần cứng trong Linux, chẳng hạn như LSHW, Uname & NBSP; và HostNamectl. Tuy nhiên, chúng tôi sẽ sử dụng & nbsp; Thư viện

import psutil
import platform
from datetime import datetime
4 trong Python để nó có thể chạy trên tất cả các hệ điều hành và nhận được kết quả gần như giống hệt nhau.lshw, uname and hostnamectl. However, we'll be using the 
import psutil
import platform
from datetime import datetime
4 library in Python so it can run on all operating systems and get almost identical results.

Đây là bảng nội dung của hướng dẫn này:

  1. Thông tin hệ thống
  2. Thông tin CPU
  3. Sử dụng bộ nhớ
  4. Sử dụng đĩa
  5. Thông tin mạng
  6. Thông tin GPU

Liên quan: & nbsp; Cách thao tác địa chỉ IP trong Python bằng mô -đun iPaddress.How to Manipulate IP Addresses in Python using ipaddress Module.

Trước khi chúng tôi đi vào, bạn cần cài đặt

import psutil
import platform
from datetime import datetime
4:

pip3 install psutil

Mở tệp Python mới và bắt đầu, nhập các mô -đun cần thiết:

import psutil
import platform
from datetime import datetime

Chúng ta hãy tạo một hàm chuyển đổi một số lượng lớn byte thành một định dạng được chia tỷ lệ (ví dụ: bằng kilo, mega, giga, v.v.):

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

Thông tin hệ thống

Thông tin CPU

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}")

Sử dụng bộ nhớ

# Boot Time
print("="*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}")

Thông tin CPU

Sử dụng bộ nhớ

# let's print CPU information
print("="*40, "CPU Info", "="*40)
# number of cores
print("Physical cores:", psutil.cpu_count(logical=False))
print("Total cores:", psutil.cpu_count(logical=True))
# CPU frequencies
cpufreq = 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 usage
print("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()}%")

Sử dụng đĩa's

import psutil
import platform
from datetime import datetime
8 function returns number of cores, whereas
import psutil
import platform
from datetime import datetime
9 function returns CPU frequency as a
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
0 including current, min, and max frequency expressed in Mhz, you can set
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
1 to get per CPU frequency.

Thông tin mạng

Sử dụng bộ nhớ

# Memory Information
print("="*40, "Memory Information", "="*40)
# get the memory details
svmem = 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}%")

Sử dụng đĩa

Thông tin mạng

Sử dụng đĩa

# Disk Information
print("="*40, "Disk Information", "="*40)
print("Partitions and Usage:")
# get all disk partitions
partitions = 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 boot
disk_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)}")

Thông tin mạng

Thông tin mạng

# Network information
print("="*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 boot
net_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)}")

Thông tin GPU

Liên quan: & nbsp; Cách thao tác địa chỉ IP trong Python bằng mô -đun iPaddress.

======================================== System Information ========================================
System: Linux
Node Name: rockikz
Release: 4.17.0-kali1-amd64
Version: #1 SMP Debian 4.17.8-1kali1 (2018-07-24)
Machine: x86_64
Processor:
======================================== Boot Time ========================================
Boot Time: 2019/8/21 9:37:26
======================================== CPU Info ========================================
Physical cores: 4
Total cores: 4
Max Frequency: 3500.00Mhz
Min Frequency: 1600.00Mhz
Current Frequency: 1661.76Mhz
CPU 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.82GB
Available: 2.98GB
Used: 564.29MB
Percentage: 21.9%
==================== SWAP ====================
Total: 0.00B
Free: 0.00B
Used: 0.00B
Percentage: 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.38GB
Total 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:ff
Total Bytes Sent: 123.68MB
Total Bytes Received: 577.94MB

Trước khi chúng tôi đi vào, bạn cần cài đặt

import psutil
import platform
from datetime import datetime
4:

Mở tệp Python mới và bắt đầu, nhập các mô -đun cần thiết:) and also

# Boot Time
print("="*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}")
3 to get various devices' temperatures.

Thông tin GPU

Liên quan: & nbsp; Cách thao tác địa chỉ IP trong Python bằng mô -đun iPaddress.

import psutil
import platform
from datetime import datetime
0

Trước khi chúng tôi đi vào, bạn cần cài đặt

import psutil
import platform
from datetime import datetime
4:It requires the latest NVIDIA driver installed.

Mở tệp Python mới và bắt đầu, nhập các mô -đun cần thiết:

import psutil
import platform
from datetime import datetime
1

Chúng ta hãy tạo một hàm chuyển đổi một số lượng lớn byte thành một định dạng được chia tỷ lệ (ví dụ: bằng kilo, mega, giga, v.v.):

import psutil
import platform
from datetime import datetime
2

Chúng tôi sẽ cần mô -đun

import psutil
import platform
from datetime import datetime
7 tại đây:

import psutil
import platform
from datetime import datetime
3

Nhận ngày và giờ máy tính được khởi động:

Hãy lấy một số thông tin CPU, chẳng hạn như tổng số lõi, cách sử dụng, v.v.Check the documentation of the libraries we used in this tutorial:

  • Hàm
    import psutil
    import platform
    from datetime import datetime
    8 của PSUTIL trả về số lượng lõi, trong khi hàm
    import psutil
    import platform
    from datetime import datetime
    9 trả về tần số CPU dưới dạng
    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
    0 bao gồm tần số hiện tại, tối thiểu và tối đa được biểu thị bằng MHz, bạn có thể đặt
    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
    1 để có tần số CPU.
  • Phương pháp
    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
    2 Trả về một phao đại diện cho việc sử dụng CPU hiện tại theo tỷ lệ phần trăm, cài đặt
    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
    3 thành 1 (giây) sẽ so sánh thời gian CPU của hệ thống đã trôi qua trước và sau một giây, chúng tôi đặt
    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
    4 thành
    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
    5 để sử dụng CPU của mỗi lõi.
  • Phương thức
    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
    6 trả về các số liệu thống kê về sử dụng bộ nhớ hệ thống như một
    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
    0, bao gồm các trường như
    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
    8 (tổng bộ nhớ vật lý có sẵn),
    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
    9 (bộ nhớ có sẵn, tức là không được sử dụng),
    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}")
    0 và
    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}")
    1 (tức là tỷ lệ phần trăm).
    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}")
    2 giống nhau nhưng đối với bộ nhớ hoán đổi.

Chúng tôi đã sử dụng hàm

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}")
3 được xác định trước đó để in các giá trị theo cách chia tỷ lệ, vì các số liệu thống kê này được biểu thị bằng byte.monitor operating system processes, such as CPU and memory usage of each process, etc.

Như mong đợi,

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}")
4 Thống kê sử dụng đĩa trả về chức năng như một
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
0, bao gồm không gian
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
8,
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}")
0 và
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}")
8 được thể hiện bằng byte.Python For Everybody Coursera course, in which you'll learn a lot about Python, good luck!

Tìm hiểu thêm: & nbsp; Cách gửi email trong Python. How to Send Emails in Python.

Happy Coding ♥

Xem đầy đủ mã


Cũng đọc


Hướng dẫn python get hardware information - python lấy thông tin phần cứng

Hướng dẫn python get hardware information - python lấy thông tin phần cứng


Bảng bình luận