在 Windows 上安装 Miniforge 后一般需要在 Miniforge Prompt(开始菜单内快捷方式)中运行 conda init
才能在默认的 Powershell 中使用 conda/mamba。
但是,Conda 24.11 版本存在一个 Bug,在 Powershell 7.5 以上版本中,conda init 命令会出现异常。表现为 conda activate base
出现以下报错:
usage: conda-script.py [-h] [-v] [--no-plugins] [-V] COMMAND ...
conda-script.py: error: argument COMMAND: invalid choice: '' (choose from 'activate', 'deactivate', 'clean', 'compare', 'config', 'create', 'env', 'export', 'info', 'init', 'install', 'list', 'notices', 'package', 'remove', 'uninstall', 'rename', 'run', 'search', 'update', 'upgrade', 'build', 'content-trust', 'convert', 'debug', 'develop', 'doctor', 'index', 'inspect', 'metapackage', 'render', 'repoquery', 'skeleton', 'server', 'token', 'repo', 'pack')
Invoke-Expression: Cannot bind argument to parameter 'Command' because it is an empty string.
由于最新版(25/02/06)的 Miniforge 自带的 Conda 仍然停留在 Conda 24.11 版本,所以需要手动更新,解决上述兼容性问题。
更新 Conda
在 Miniforge Prompt 中使用以下命令强制更新 conda 到 25.1 之后的版本:
conda install -n base conda=25.1.1 -c conda-forge --override-channels --yes
更新后,先使用以下命令清理 profile(如果已经安装):
conda init --reverse
然后重新安装 conda profile。
conda init
修复 Oh-My-Posh
很多朋友都在 Windows 上使用了 Oh-My-Posh 进行终端美化。但是,Oh-My-Posh 可能需要经过一些设置才能正确显示 Conda 环境标识。
Segment
在 Oh-My-Posh 中,Conda 环境标识(包括 venv
虚拟环境标识)都是由主题的 Segment 配置定义的,具体文档参考:Python | Oh My Posh。
如果你使用的主题中没有设置 Python 相关的 Segment,也就无法显示 Conda 环境。
检查主题配置
要检查当前 Powershell 使用的 Oh-My-Posh 主题,可以查看 Profile 文件:
notepad $PROFILE
文件内容可能为:
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/ys.omp.json" | Invoke-Expression
以上输出表明当前使用的主题配置是:$env:POSH_THEMES_PATH/ys.omp.json
。
找到该文件,打开后检查配置文件中是否有含有 "type": "python"
的 segment。以下是我的主题配置节选:
"segments": [
{
"foreground": "white",
"properties": {
"fetch_version": false,
"fetch_virtual_env": true,
"home_enabled": true,
"display_mode": "environment"
},
"style": "plain",
"template": "({{ if .Error }}{{ .Error }}{{ else }}{{ if .Venv }}{{ .Venv }}{{ end }}{{ .Full }}{{ end }})",
"type": "python"
}
],
如果你的主题中没有 "type": "python"
相关配置,说明该主题不支持显示 Conda 环境。你可以选择换一个主题,或者找一个支持 Conda 环境的主题,将其配置拷贝到你的主题配置中。
如果你的主题中有该配置,但仍然没有显示 Conda 环境标识,这种情况需要调整 properties
配置。
调整 Conda 环境标识
具体而言,你需要检查 properties
配置中的以下三个选项:
fetch_virtual_env
:是否获取虚拟环境名称,显然应该设置为 true。home_enabled
:是否在所有目录下都尝试显示 Python 虚拟环境名称。在系统上安装 Conda 后也建议设置为 true。display_mode
:建议设置为environment
,通过检查特定环境变量判断是否显示虚拟环境标识。
总的来说,新增/修改 Oh-My-Posh 的 Segment 配置后,Powershell 应该能够自动显示 Conda 虚拟环境的名称了。
感谢,原来是 minifoge 自带的 conda 没有更新
十分感谢,解决了!
帮大忙了!!!