Python - Activate conda env through shell script

前端 未结 6 982
遥遥无期
遥遥无期 2020-11-30 03:14

I am hoping to run a simple shell script to ease the management around some conda environments. Activating conda environments via conda activate in a lin

6条回答
  •  旧时难觅i
    2020-11-30 03:59

    Quick solution for bash: prepend the following init script into your Bash scripts.

    eval "$(command conda 'shell.bash' 'hook' 2> /dev/null)"
    

    Done.


    For other shells, check the init conf of your shell, copy the following content within the shell conf and prepend it into your scripts.

    # >>> conda initialize >>>
    ...
    # <<< conda initialize <<<
    

    You can also use

    conda init --all --dry-run --verbose
    

    to get the init script you need in your scripts.

    Explanation

    This is related with the introduction of conda init in conda 4.6.

    Quote from conda 4.6 release log

    Conda 4.4 allowed “conda activate envname”. The problem was that setting up your shell to use this new feature was not always straightforward. Conda 4.6 adds extensive initialization support so that more shells than ever before can use the new “conda activate” command. For more information, read the output from “conda init –help”

    After conda init is introduced in conda 4.6, conda only expose command conda into the PATH but not all the binaries from "base". And environment switch is unified by conda activate env-name and conda deactivate on all platforms.

    But to make these new commands work, you have to do an additional initialization with conda init.

    The problem is that your script file is run in a sub-shell, and conda is not initialized in this sub-shell.

    References

    • Conda 4.6 Release
    • Unix shell initialization
    • Shell startup scripts

提交回复
热议问题