在集群作业中激活 conda 环境

张开发
2026/4/13 22:37:13 15 分钟阅读

分享文章

在集群作业中激活 conda 环境
在 slurm 集群上提交一个任务, 如果直接激活 conda 环境, 往往会报错: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.这是因为 conda initialize 的命令位于家目录下的 .bashrc, 在你登陆 shell 时执行; 而集群的作业系统在调用 /usr/bin/bash 运行你的作业时, 不会运行 ~/.bashrc .因此, 可以直接把 ~/.bashrc 中的这部分代码提取出来, 仅在任务开始运行时执行一次, 比如, 放到 ~/.conda_init 中:# conda initialize declareCONDA_PATHconda 安装文件夹# !! Contents within this block are managed by conda init !!__conda_setup$($CONDA_PATH/bin/condashell.bashhook2/dev/null)if[$?-eq0];theneval$__conda_setupelseif[-f$CONDA_PATH/etc/profile.d/conda.sh];then.$CONDA_PATH/etc/profile.d/conda.shelseexportPATH$CONDA_PATH/bin:$PATHfifiunset__conda_setup在运行任务时, 如果设置了 -v -x 等参数, 那么 conda activate 这些操作会输出很长的信息, 可以用 conda_ 函数替换 conda:functionconda_(){declarelast_option$-;setvxudeclareargs$*echoconda${args}conda${args}foroptioninvx udoif[[$last_option*$option*]]thenset-$optionfidone}-v: 在运行命令前打印这条命令-x: 替换命令中的变量并打印替换后的命令-u: 如果管道中出错, 则报错 (如 PS1 在非交互式终端中不存在, conda initialize 试图修改于是报错)如果任务需要调用多个脚本, 每个脚本各自需要不同的 conda 环境, 又不希望多次运行 conda initialize, 那么可以在 ~/.conda_init 最前面加入这一部分:if[$(type-tconda_)function];thenechoconda initialized, skipreturn0fi最终版本: ~/.conda_initif[$(type-tconda_)function];thenechoconda initialized, skipreturn0fi# conda initialize declareCONDA_PATHconda 安装文件夹# !! Contents within this block are managed by conda init !!__conda_setup$($CONDA_PATH/bin/condashell.bashhook2/dev/null)if[$?-eq0];theneval$__conda_setupelseif[-f$CONDA_PATH/etc/profile.d/conda.sh];then.$CONDA_PATH/etc/profile.d/conda.shelseexportPATH$CONDA_PATH/bin:$PATHfifiunset__conda_setup# conda initialize functionconda_(){declarelast_option$-;setvxudeclareargs$*echoconda${args}conda${args}foroptioninvx udoif[[$last_option*$option*]]thenset-$optionfidone}

更多文章