python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > PyTorch、cuda 和 Python 查看版本

几种查看PyTorch、cuda 和 Python 版本方法小结

作者:王红臣同学

本文主要介绍了几种查看PyTorch、cuda 和 Python 版本方法小结,除了直接使用 torch.__version__ 和 sys.version,我们还可以通过其他方式实现相同的功能,下面就一起来了解一下

在检查 PyTorch、cuda 和 Python 版本时,除了直接使用 torch.__version__ 和 sys.version,我们还可以通过其他方式实现相同的功能

方法 1:直接访问属性(原始代码)

import torch
import sys

print("PyTorch Version: {}".format(torch.__version__))
print("Python Version: {}".format(sys.version))

特点:

方法 2:通过命令行工具

如果希望在脚本外部检查版本,可以直接使用命令行工具。

Python 版本

python --version
# 或
python -V

PyTorch 版本

python -c "import torch; print(torch.__version__)"

特点:

方法 3:使用 torch.version 模块

PyTorch 提供了一个 torch.version 模块,可以获取更详细的版本信息。

import torch
import sys

# 获取 PyTorch 版本信息
print("PyTorch Version: {}".format(torch.version.__version__))  # 或直接使用 torch.__version__
print("PyTorch CUDA Version: {}".format(torch.version.cuda))  # 获取 CUDA 版本
print("PyTorch cuDNN Version: {}".format(torch.backends.cudnn.version()))  # 获取 cuDNN 版本

# Python 版本
print("Python Version: {}".format(sys.version))

特点:

方法 4:使用 pkg_resources

pkg_resources 是 setuptools 提供的一个工具,可以查询已安装包的版本信息。

import pkg_resources

# 获取 PyTorch 版本
try:
    pytorch_version = pkg_resources.get_distribution("torch").version
    print("PyTorch Version: {}".format(pytorch_version))
except pkg_resources.DistributionNotFound:
    print("PyTorch is not installed.")

# Python 版本仍通过 sys 模块
import sys
print("Python Version: {}".format(sys.version))

特点:

方法 5:使用 platform 模块(补充 Python 信息)

虽然 sys.version 已经提供了 Python 版本信息,但 platform 模块可以提供更详细的系统信息。

import torch
import platform

print("PyTorch Version: {}".format(torch.__version__))
print("Python Version: {}".format(platform.python_version()))
print("Platform: {}".format(platform.platform()))

特点:

方法 6:结合 subprocess 调用命令行

如果需要在 Python 脚本中调用外部命令行工具,可以使用 subprocess 模块。

import subprocess

def get_python_version():
    result = subprocess.run(["python", "--version"], capture_output=True, text=True)
    return result.stdout.strip()

def get_pytorch_version():
    result = subprocess.run(["python", "-c", "import torch; print(torch.__version__)"], capture_output=True, text=True)
    return result.stdout.strip()

print("Python Version: {}".format(get_python_version()))
print("PyTorch Version: {}".format(get_pytorch_version()))

特点:

方法 7:使用 torch.utils.collect_env

PyTorch 提供了一个 torch.utils.collect_env 工具,可以收集详细的系统环境信息,包括 PyTorch、Python、CUDA、cuDNN 等。

import torch

env_info = torch.utils.collect_env()
print(env_info)

特点:

总结

方法优点缺点
直接访问属性简单直接,无需额外依赖功能有限,仅能获取基本版本信息
PyTorch
通过命令行工具适用于脚本外部检查,无需编写 Python 代码需要手动执行命令
使用 torch.version提供更详细的版本信息(CUDA、cuDNN)仅适用于
使用 pkg_resources可以查询任何已安装包的版本需要额外依赖 setuptools
使用 platform 模块提供详细的系统信息功能与 sys 模块部分重叠
结合 subprocess灵活调用外部命令行工具实现复杂,性能可能较低
使用 torch.utils.collect_env提供全面的环境信息,适合调试输出格式复杂,需要进一步处理

到此这篇关于几种查看PyTorch、cuda 和 Python 版本方法小结的文章就介绍到这了,更多相关PyTorch、cuda 和 Python 查看版本内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文