import os
import subprocess
from pathlib import Path
# 修改get_conda_envs函数中的解析方式
import json # 新增导入
def get_conda_envs():
"""获取所有conda环境路径"""
try:
result = subprocess.run(
["conda", "info", "--json"],
capture_output=True,
text=True,
check=True
)
info = json.loads(result.stdout) # 改用json解析
return info["envs"]
except json.JSONDecodeError as e:
print(f"JSON解析失败: {e}")
return []
except Exception as e:
print(f"获取conda环境失败: {e}")
return []
def get_env_versions(env_path):
"""获取指定环境的版本信息"""
versions = {"python": "N/A", "pytorch": "N/A"}
# 获取Python版本
python_exe = Path(env_path)/"bin"/"python"
if not python_exe.exists():
return versions
try:
res = subprocess.run(
[str(python_exe), "--version"],
capture_output=True,
text=True,
check=True
)
versions["python"] = res.stdout.strip().split()[-1]
except Exception as e:
print(f"获取Python版本失败: {e}")
# 获取PyTorch版本
try:
res = subprocess.run(
[str(python_exe), "-c",
"import torch; print(torch.__version__)"],
capture_output=True,
text=True,
check=True
)
versions["pytorch"] = res.stdout.strip()
except Exception as e:
versions["pytorch"] = "Not installed"
return versions
def main():
envs = get_conda_envs()
if not envs:
return
print(f"{'Environment':<25} | {'Python':<10} | {'PyTorch':<15}")
print("-" * 55)
for env_path in envs:
env_name = Path(env_path).name
versions = get_env_versions(env_path)
print(f"{env_name:<25} | {versions['python']:<10} | {versions['pytorch']:<15}")
if __name__ == "__main__":
main()
获取所有conda虚拟环境的python版本以及torch版本
最新推荐文章于 2026-01-05 11:53:02 发布
4万+

被折叠的 条评论
为什么被折叠?



