解决方案
在Anaconda3 PowerShell中运行conda init powershell
问题描述
Pycharm Terminal Windows PowerShell启动报错,无法进入项目的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原因分析
查看日志文件:PyCharm -> Help -> Show Log in File Explorer
idea.log
2025-07-08 02:28:19,043 [ 912223] INFO - #c.j.p.packaging - System conda executable is not found
2025-07-08 02:28:19,044 [ 912224] WARN - #c.i.p.t.PyVirtualEnvTerminalCustomizer - Can't find null, will not activate conda
2025-07-08 02:28:19,088 [ 912268] INFO - #o.j.p.t.LocalTerminalDirectRunner - Started com.pty4j.windows.conpty.WinConPtyProcess in 11 ms
from [C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe, -NoExit, -ExecutionPolicy, Bypass, -File,
D:\Program Files\JetBrains\PyCharm 2024.1.3\plugins\terminal\shell-integrations\powershell\powershell-integration.ps1]
in F:\work\PycharmProjects\FinRobot, [columns=305, rows=19], diff_envs={FIG_TERM=1, INTELLIJ_TERMINAL_COMMAND_BLOCKS=1,
JEDITERM_SOURCE=Failed to activate conda environment.
Please open Anaconda prompt, and run `conda init powershell` there.,
JETBRAINS_INTELLIJ_COMMAND_END_MARKER=, TERMINAL_EMULATOR=JetBrains-JediTerm, TERM_SESSION_ID=}发现System conda executable is not found,说明找不到conda的可执行文件
于是查看powershell-integration.ps1文件,发现调用了同目录下的command-block-support.ps1
powershell-integration.ps1
...
$Hooks = "$PSScriptRoot/command-block-support.ps1"
...command-block-support.ps1
...
$CondaEnv = if ($Env:CONDA_DEFAULT_ENV -ne $null) { $Env:CONDA_DEFAULT_ENV } else { "" }
...发现加载了系统环境变量CONDA_DEFAULT_ENV,于是查看系统环境变量,发现没有这个变量。
在环境变量中添加CONDA_DEFAULT_ENV为D:\Anaconda3(anaconda根目录)后,可以正常进入项目的conda虚拟环境,但是依然报错。
于是在PATH环境变量中添加condabin的路径:D:\Anaconda3\condabin,恢复正常。
总结
- 在环境变量中添加默认conda环境,
CONDA_DEFAULT_ENV=[Anaconda根目录] - 在PAHT中添加conda的bin目录,
[Anaconda根目录]\condabin
其他分析
在文档\WindowsPowerShell目录下,有PowerShell脚本profile.ps1,应该是之前安装Miniconda时运行conda init powershell生成的,尝试修改这个文件中的conda目录无效。
#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
If (Test-Path "D:\Anaconda3\Scripts、conda.exe") {
(& "D:\Anaconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | ?{$_} | Invoke-Expression
}
#endregion查看anaconda源码的initialize.py,
发现conda init powershell会生成profile.ps1文件,并且添加condabin环境变量。
nice