在新的 xterm 终端中激活 conda 环境

Activate conda environment within a new xterm terminal

如果我运行

xterm -hold

然后在新终端中输入

conda activate my_environment

conda环境"my_environment"确实激活了

但是,当使用 -e 标志传递此命令时,它不起作用:

xterm -hold -e "conda activate my_environment"

而是 returns 以下错误消息:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

那么,如何使用 xterm 完成此操作?或者我应该使用其他类型的外部终端?​​

背景

conda activate 命令是一个 shell 函数,在 shell 初始化期间定义。 conda init 将代码添加到初始化文件(例如,.bash_profile)到 运行 定义 conda activate shell 函数的脚本。

解决方案

可能的修复:xterm 选项

当将 -c 参数与 xterm 一起使用时,它不再是 运行 初始化脚本。因此,conda activate 永远不会被定义。对于 bash-l 告诉它 运行 初始化文件。我预计 xterm 的 -ls 参数会触发类似的行为,但它对我不起作用。也许更熟悉的人可以为您指出正确的标志。

手动 运行 Conda 脚本

否则,您只需 运行 自己的 Conda 脚本(假设它是 bash 版本)。这些都可以工作:

xterm -hold -e ". /path/to/miniconda3/etc/profile.d/conda.sh && conda activate my_environment && which python"

xterm -hold -e "$(conda shell.bash hook) && conda activate my_environment && which python"

包含 which python 只是为了表明您正在激活环境。

康达运行

另一个选项是conda run,它可以在环境下自动执行命令。以下等同于我在上一节中所做的,但不必知道 shell 我在 运行 中:

xterm -hold -e "conda run -n my_environment which python"

请注意,此功能仍在开发中。就个人而言,我发现它对于 运行 在特定环境中使用简单的脚本非常有用,并且没有 运行 遇到问题。