帮我写成python终端指令
时间: 2025-02-25 17:32:38 浏览: 11
好的,下面是将上述方法转换成可以在Python终端中执行的指令。这些代码可以帮助你在Python环境中检测可用的GPU数量及基本信息。
方法一:使用 subprocess
模块运行 shell 命令
这种方法适合那些可以直接从shell获取信息的情况,比如使用 nvidia-smi
或者 lspci
。
import subprocess
# 获取 NVIDIA GPU 信息 (仅限于安装了 nvidia-driver 和 CUDA 的系统)
def get_nvidia_gpu_info():
try:
result = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
print(result.stdout)
else:
print("无法找到或访问 nvidia-smi")
except FileNotFoundError:
print("未发现 nvidia-smi 工具")
get_nvidia_gpu_info()
# 查找所有 VGA 兼容控制器 (适用于各种品牌的 GPU)
print("\nVGA Compatible Controllers:")
try:
result = subprocess.run(['lspci', '|', 'grep', 'VGA'], shell=True, check=True, stdout=subprocess.PIPE, text=True)
print(result.stdout)
except Exception as e:
print(f"Error occurred while running command: {e}")
方法二:使用 PyTorch 库检测 GPU (前提是已经设置了CUDA)
如果你已经在你的环境中配置好CUDA并且有相应的深度学习框架(如PyTorch),则可以更方便地查看GPU信息:
import torch
if not torch.cuda.is_available():
print("没有检测到支持 CUDA 的 GPU.")
else:
gpu_count = torch.cuda.device_count()
print(f"检测到 {gpu_count} 个可用 GPU.")
# 输出每个 GPU 的名称和其他详细信息
for i in range(gpu_count):
name = torch.cuda.get_device_name(i)
memory_allocated = round(torch.cuda.memory_allocated(i) / 1024 ** 3, 2) # 单位 GB
max_memory = round(torch.cuda.max_memory_allocated(i) / 1024 ** 3, 2) # 单位 GB
print(f"\t设备编号: {i}, 名称: {name}, 当前分配内存大小: {memory_allocated:.2f}GB, 最大可分配内存大小: {max_memory:.2f}GB")
这两种方法都可以在 Python 终端里直接复制粘贴并运行,前提是你有足够的权限去读取系统的硬件信息,并且正确设置好了相关的依赖项(例如CUDA、PyTorch 等)。希望这对您有所帮助!
--
相关推荐


















