自学内容网 自学内容网

Failed to activate conda environment

问题描述

Pycharm Terminal显示以下错误,导致无法自动激活当前项目的conda环境

Failed : 无法将“Failed”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
所在位置 行:1 字符: 1
+ Failed to activate conda environment.
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (Failed:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
Please : 无法将“Please”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
所在位置 行:2 字符: 2
+  Please open Anaconda prompt, and run `conda init powershell` there.
+  ~~~~~~
    + CategoryInfo          : ObjectNotFound: (Please:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

原因分析

查看log文件,发现真实的错误是找不到conda的路径

2024-07-25 10:35:24,316 [1553431]   INFO - #c.j.p.packaging - System conda executable is not found
2024-07-25 10:35:24,316 [1553431]   WARN - #c.i.p.t.PyVirtualEnvTerminalCustomizer - Can't find null, will not activate conda

查看github上文件对应的源代码:python/python-sdk/src/com/jetbrains/python/packaging/CondaExecutablesLocator.kt
可以发现它默认是从sdk path去找conda的可执行文件,但是由于我这里环境修改了env_dirs的存储目录,使其跟conda的安装路径不一致了,所以它找不到conda的可执行文件。
之后则去环境变量、用户的home目录找conda的可执行文件,windows是conda.bat,但是window是装在用户home目录下的AppData\Local文件夹的,所以这里找不到。

@JvmStatic
fun getCondaExecutable(sdkPath: String?): @SystemDependent String? {
  if (sdkPath != null) {
val condaPath = findCondaExecutableRelativeToEnv(Path.of(sdkPath))
if (condaPath != null) {
  LOG.info("Using $condaPath as a conda executable for $sdkPath (found as a relative to the env)")
  return condaPath.toString()
}
  }

  val preferredCondaPath = getInstance().preferredCondaPath
  if (!preferredCondaPath.isNullOrEmpty()) {
val forSdkPath = if (sdkPath == null) "" else " for $sdkPath"
LOG.info("Using $preferredCondaPath as a conda executable$forSdkPath (specified as a preferred conda path)")
return preferredCondaPath
  }

  return getSystemCondaExecutable()?.toString()
}

private const val CONDA_BAT_NAME = "conda.bat"
fun getSystemCondaExecutable(): Path? {
  val condaName = if (SystemInfo.isWindows) CONDA_BAT_NAME else CONDA_BINARY_NAME

  // TODO we need another findInPath() that works with Path-s
  val condaInPath = PathEnvironmentVariableUtil.findInPath(condaName)
  if (condaInPath != null) {
    LOG.info("Using $condaInPath as a conda executable (found in PATH)")
    return condaInPath.toPath()
  }

  val condaInRoots = getCondaExecutableByName(condaName)
  if (condaInRoots != null) {
    LOG.info("Using $condaInRoots as a conda executable (found by visiting possible conda roots)")
    return condaInRoots
  }

  LOG.info("System conda executable is not found")
  return null
}

解决方案

PATH环境变量中添加condabin的路径:C:\Users\xxx\AppData\Local\miniconda3\condabin


原文地址:https://blog.csdn.net/liuzhenghua66/article/details/140688027

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!