获得硬件信息的最优雅的方法是什么,比如GPU名称、CPU名称、nim中的RAM?我还没有找到一个库,也不太确定如何从纯nim实现它
发布于 2022-11-05 23:10:31
当您想要搜索Nim包时,您应该首先查看:
nimble search功能。例句:nimble search hardware cpu,我找到了pkg/sysinfo包和pkg/psutil-nim,它们可能做你想做的事。Shell脚本通常更快,更适合这类应用程序。有许多CLI应用程序可以直接调整或利用。在Linux上,您可以使用hostnamectl获取主机名和模型信息。还有其他聚合硬件信息的实用程序,最著名的可能是neofetch.它有许多变体,请参阅:https://alternativeto.net/software/neofetch/
基于新获取,我编写了一个只在Linux上工作的小脚本:
import std/[strutils, strformat, osproc]
type
MyComputerInfo = object
os: string
host: string
kernel: string
cpu: string
gpu: string
proc cacheUnameInfo(): tuple[os: string, host: string, kernel: string] =
## Only defined for posix systems
when defined(posix):
let (output, errorCode) = execCmdEx("uname -srm")
if errorCode != 0:
echo fmt"`uname -srm` command failed, with Error code: {errorCode}"
quit(2)
let
outSeq: seq[string] = output.split(' ')
os = outSeq[0]
host = outSeq[1]
kernel = outSeq[2]
return (os, host, kernel)
proc getGpuInfo(): string =
when defined(posix):
var (gpu_driver_name, exitCode) = execCmdEx("""lspci -nnk | awk -F ': ' \ '/Display|3D|VGA/{nr[NR+2]}; NR in nr {printf $2 ", "; exit}'""")
if exitCode == 0:
gpu_driver_name = gpu_driver_name.split(",")[0]
if gpu_driver_name == "nvidia":
var (gpu_name, exitCodeSmi) = execCmdEx("nvidia-smi --query-gpu=name --format=csv,noheader")
if exitCodeSmi != 0:
echo "nvidia-smi command failed with exit code: {exitCodeSmi}"
quit(2)
return gpu_name
return gpu_driver_name.toUpperAscii()
else:
echo fmt"GpuInfo error code: {exitCode}"
quit(2)
proc getCpuInfo(): string =
when defined(posix):
let filename = "/proc/cpuinfo"
var (cpu_name, exitCode) = execCmdEx("""cat /proc/cpuinfo | awk -F '\\s*: | @' '/model name|Hardware|Processor|^cpu model|chip type|^cpu type/ { cpu=$2; if ($1 == "Hardware") exit } END { print cpu }' "$cpu_file" """)
return cpu_name
proc `$`(mci: MyComputerInfo): string =
## Nice Output of a `MyComputerInfo` object
for name, val in fieldPairs(mci):
if $val != "":
result.add name.capitalizeAscii()
result.add ": "
result.add ($val).strip(leading=false, chars = {'\n'})
result.add "\n"
result.strip(leading=false, chars = {'\n'})
when isMainModule:
var mci: MyComputerInfo
(mci.os, mci.host, mci.kernel) = cacheUnameInfo()
mci.gpu = getGpuInfo()
mci.cpu = getcpuInfo()
echo mci在我的电脑上,我得到:
Os: Linux
Host: 6.0.2-zen1-1-zen
Kernel: x86_64
Cpu: 11th Gen Intel(R) Core(TM) i5-11400F
Gpu: NVIDIA GeForce RTX 3070为了获得更高的Nim纯度,我们可以用Nim解析过程代替execCmdEx中的awk调用。我们可以添加一个配置器(带有CLI解析器或DSL),这样用户就可以选择他想打印出来的选项。剩下的就交给你了。
https://stackoverflow.com/questions/74320430
复制相似问题