MacOS下VSCode任务中使用conda环境报错的解决求助
MacOS下VSCode任务中正确使用Conda环境的解决方案
配置了如下tasks.json文件:
{ "version": "2.0.0", "tasks": [ { "label": "conda info", "type": "shell", "command": "type conda; which conda", }, { "label": "Activate conda envrionment: mkdocs", "type": "shell", "command": "conda", "args": [ "activate", "mkdocs" ] }, { "label": "Serve mkdocs", "type": "shell", "command": "mkdocs serve --strict --dev-addr localhost:8010", }, { "label": "run mkdocs serve in environment", "group": "test", "presentation": { "reveal": "always", "panel": "shared" }, "runOptions": { "runOn": "folderOpen" }, "dependsOrder": "sequence", "dependsOn": [ "conda info", "Activate conda envrionment: mkdocs", "Serve mkdocs" ], } ] }
运行任务时总是报错:
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
已设置"python.condaPath",conda info任务显示路径正确,且VSCode终端中可正常执行相关命令,以下是针对MacOS系统的解决方法:
解决方法
方法1:使用conda run直接在指定环境执行命令(推荐)
Conda提供的conda run命令可直接在目标环境中运行指定命令,无需单独执行conda activate,避免shell配置问题。修改后的tasks.json如下:
{ "version": "2.0.0", "tasks": [ { "label": "conda info", "type": "shell", "command": "type conda; which conda", }, { "label": "Serve mkdocs in conda env", "type": "shell", "command": "conda", "args": [ "run", "--name", "mkdocs", "mkdocs", "serve", "--strict", "--dev-addr", "localhost:8010" ] }, { "label": "run mkdocs serve in environment", "group": "test", "presentation": { "reveal": "always", "panel": "shared" }, "runOptions": { "runOn": "folderOpen" }, "dependsOrder": "sequence", "dependsOn": [ "conda info", "Serve mkdocs in conda env" ], } ] }
方法2:加载Conda初始化脚本并合并任务
VSCode任务的shell是非交互式的,不会自动加载conda配置,可先手动加载初始化脚本,再执行激活和运行命令,需将激活与运行合并为同一个任务(每个任务是独立shell进程,前一个任务的环境不会传递给后续任务):
{ "version": "2.0.0", "tasks": [ { "label": "conda info", "type": "shell", "command": "type conda; which conda", }, { "label": "Serve mkdocs", "type": "shell", // 若使用Anaconda,路径改为$HOME/anaconda3/etc/profile.d/conda.sh "command": "source $HOME/miniconda3/etc/profile.d/conda.sh && conda activate mkdocs && mkdocs serve --strict --dev-addr localhost:8010" }, { "label": "run mkdocs serve in environment", "group": "test", "presentation": { "reveal": "always", "panel": "shared" }, "runOptions": { "runOn": "folderOpen" }, "dependsOrder": "sequence", "dependsOn": [ "conda info", "Serve mkdocs" ], } ] }
方法3:配置交互式shell
让任务使用交互式shell,自动加载.zshrc或.bashrc中的conda配置,同样需要合并激活与运行命令:
{ "version": "2.0.0", "tasks": [ { "label": "conda info", "type": "shell", "command": "type conda; which conda", }, { "label": "Serve mkdocs", "type": "shell", "command": "conda activate mkdocs && mkdocs serve --strict --dev-addr localhost:8010", "options": { "shell": { "executable": "/bin/zsh", "args": ["-i", "-c"] } } }, { "label": "run mkdocs serve in environment", "group": "test", "presentation": { "reveal": "always", "panel": "shared" }, "runOptions": { "runOn": "folderOpen" }, "dependsOrder": "sequence", "dependsOn": [ "conda info", "Serve mkdocs" ], } ] }
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

