在集群作业中激活 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 >>>
declare CONDA_PATH=<conda 安装文件夹>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$($CONDA_PATH'/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "$CONDA_PATH/etc/profile.d/conda.sh" ]; then
        . "$CONDA_PATH/etc/profile.d/conda.sh"
    else
        export PATH="$CONDA_PATH/bin:$PATH"
    fi
fi
unset __conda_setup

在运行任务时, 如果设置了 -v -x 等参数, 那么 conda activate 这些操作会输出很长的信息, 可以用 conda_ 函数替换 conda:

function conda_() {
    declare last_option=$-; set +vxu

    declare args="$*"
    echo "conda ${args}"
    conda ${args}

    for option in v x u
    do
        if [[ "$last_option" == *"$option"* ]]
        then set -"$option"
        fi
    done
}
  • -v: 在运行命令前打印这条命令
  • -x: 替换命令中的变量并打印替换后的命令
  • -u: 如果管道中出错, 则报错 (如 PS1 在非交互式终端中不存在, conda initialize 试图修改于是报错)

如果任务需要调用多个脚本, 每个脚本各自需要不同的 conda 环境, 又不希望多次运行 conda initialize, 那么可以在 ~/.conda_init 最前面加入这一部分:

if [ "$(type -t conda_)" == function ]; then
    echo "conda initialized, skip"
    return 0
fi

最终版本: ~/.conda_init

if [ "$(type -t conda_)" == function ]; then
    echo "conda initialized, skip"
    return 0
fi

# >>> conda initialize >>>
declare CONDA_PATH=<conda 安装文件夹>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$($CONDA_PATH'/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "$CONDA_PATH/etc/profile.d/conda.sh" ]; then
        . "$CONDA_PATH/etc/profile.d/conda.sh"
    else
        export PATH="$CONDA_PATH/bin:$PATH"
    fi
fi
unset __conda_setup

# <<< conda initialize <<<


function conda_() {
    declare last_option=$-; set +vxu

    declare args="$*"
    echo "conda ${args}"
    conda ${args}

    for option in v x u
    do
        if [[ "$last_option" == *"$option"* ]]
        then set -"$option"
        fi
    done
}
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值