怎么用脚本获取内存总容量

wen 实用脚本 2

本文目录导读:

怎么用脚本获取内存总容量

  1. Python(跨平台)
  2. Bash(Linux/Mac)
  3. PowerShell(Windows)
  4. Node.js(JavaScript)
  5. Go(需要编译)
  6. 批处理(Windows CMD)
  7. 注意事项

Python(跨平台)

import psutil
# 获取内存总容量(字节)
total_memory = psutil.virtual_memory().total
# 转换为可读格式
def bytes_to_gb(bytes):
    return round(bytes / (1024**3), 2)
print(f"内存总容量: {bytes_to_gb(total_memory)} GB")
# 或直接显示字节
print(f"内存总容量: {total_memory} 字节")

安装依赖:

pip install psutil

Bash(Linux/Mac)

# 方法1:使用 /proc/meminfo
total=$(grep MemTotal /proc/meminfo | awk '{print $2}')
echo "内存总容量: $((total / 1024)) MB"
# 方法2:使用 free 命令
free -h | grep "Mem:" | awk '{print $2}'
# 方法3:使用 dmidecode(需要root权限)
sudo dmidecode -t memory | grep "Size:" | grep -v "No Module Installed" | awk '{sum+=$2} END {printf "%.2f GB\n", sum/1024}'

PowerShell(Windows)

# 方法1:使用 WMI
Get-WmiObject Win32_ComputerSystem | Select-Object TotalPhysicalMemory
# 方法2:使用 CIM
(CIM Win32_ComputerSystem).TotalPhysicalMemory
# 方法3:格式化显示
$memory = (Get-WmiObject Win32_ComputerSystem).TotalPhysicalMemory
Write-Host "内存总容量: $([math]::Round($memory/1GB, 2)) GB"

Node.js(JavaScript)

const os = require('os');
// 获取内存总容量(字节)
const totalMemory = os.totalmem();
// 转换为可读格式
function bytesToGB(bytes) {
    return (bytes / (1024 ** 3)).toFixed(2);
}
console.log(`内存总容量: ${bytesToGB(totalMemory)} GB`);
console.log(`内存总容量: ${totalMemory} 字节`);

Go(需要编译)

package main
import (
    "fmt"
    "runtime"
)
func main() {
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    totalMemory := m.TotalAlloc
    // 注意:这是Go分配的内存,要获取系统总内存需使用其他方法
    // 更好的方法使用 sysinfo(仅Linux)
    // import "golang.org/x/sys/unix"
}

批处理(Windows CMD)

@echo off
wmic memorychip get capacity /format:value

注意事项

  1. 权限问题:某些方法(如dmidecode)可能需要管理员/root权限

  2. 单位换算

    • 1 KB = 1024 字节
    • 1 MB = 1024 KB
    • 1 GB = 1024 MB
  3. 跨平台建议:Python + psutil 是最简单的跨平台方案

  4. 虚拟内存:以上获取的是物理内存,不是虚拟内存

选择适合你操作系统和需求的方法即可。

抱歉,评论功能暂时关闭!