怎么通过代码调用api获取本地电脑设备信息
时间: 2024-06-12 09:06:53 浏览: 158
用API函数获取本机IP
4星 · 用户满意度95%
获取本地电脑设备信息需要使用系统相关的API,具体实现方法会因操作系统不同而有所区别。以下是一些常见操作系统的示例代码:
Windows:
```python
import wmi
# 初始化WMI对象
w = wmi.WMI()
# 获取CPU信息
for cpu in w.Win32_Processor():
print(cpu.Name)
# 获取内存信息
for mem in w.Win32_PhysicalMemory():
print(mem.Capacity)
# 获取硬盘信息
for disk in w.Win32_DiskDrive():
print(disk.Caption)
# 获取显卡信息
for gpu in w.Win32_VideoController():
print(gpu.Description)
```
Linux:
```python
import subprocess
# 获取CPU信息
cmd = "lscpu | grep 'Model name'"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
# 获取内存信息
cmd = "grep MemTotal /proc/meminfo"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
# 获取硬盘信息
cmd = "lsblk -o NAME,SIZE,MODEL | grep disk"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
# 获取显卡信息
cmd = "lspci | grep 'VGA compatible controller'"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
```
macOS:
```python
import subprocess
# 获取CPU信息
cmd = "sysctl -n machdep.cpu.brand_string"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
# 获取内存信息
cmd = "sysctl hw.memsize"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
# 获取硬盘信息
cmd = "diskutil list | grep '128' | awk '{print $4}'"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
# 获取显卡信息
cmd = "system_profiler SPDisplaysDataType | grep Chipset | awk '{print $3,$4}'"
result = subprocess.check_output(cmd, shell=True).decode().strip()
print(result)
```
阅读全文