import os
import subprocess
from pathlib import Path
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)
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_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}")
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()