Home:ALL Converter>Python - Activate conda env through shell script

Python - Activate conda env through shell script

Ask Time:2019-04-04T11:46:33         Author:user9074332

Json Formatter

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 linux os works fine in the shell but is problematic within a shell script. Could someone point me into the right direction as to why this is happening?

Example to repeat the issue:

# default conda env
$ conda info | egrep "conda version|active environment"
     active environment : base
          conda version : 4.6.9

# activate new env to prove that it works
$ conda activate scratch
$ conda info | egrep "conda version|active environment"
     active environment : scratch
          conda version : 4.6.9

# revert back to my original conda env
$ conda activate base 

$ cat shell_script.sh
#!/bin/bash
conda activate scratch

# run shell script - this will produce an error even though it succeeded above
$ ./shell_script.sh

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'.

Author:user9074332,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55507519/python-activate-conda-env-through-shell-script
Wasim Khan :

I also had the exact same error when trying to activate conda env from C++ or Python file. I solved it by bypassing the conda activate statement and using the absolute path of the specific conda env.\nFor me, I set up an environment called "testenv" using conda.\nI searched all python environments using\nwhereis python | grep 'miniconda'\n\nIt returned a list of python environments. Then I ran my_python_file.py using the following command.\n~/miniconda3/envs/testenv/bin/python3.8 my_python_file.py\n\nYou can do the same thing on windows too but looking up for python and conda python environments is a bit different.",
2020-08-05T18:26:30
Oresto :

This answer from Github worked for me (I'm using Ubuntu so it's not for Windows only):\neval "$(conda shell.bash hook)"\nconda activate my_env\n",
2021-12-24T14:45:46
Hernán Quiroz :

I just followed a similar solution like the one from hong-xu\nSo to run a shell command that calls the script with arguments and using a specific conda environment:\nfrom a jupyter cell, goes like this :\np1 = <some-value>\nrun = f"conda run -n {<env-name>} python {<script-name>.py} \\\n --parameter_1={p1}"\n\n!{run}\n",
2021-07-21T01:38:47
Eamonn Kenny :

I didn't find any of the above scripts useful. These are fine if you want to run conda in non-interactive mode, but I'd like to run it in interactive mode. If I run:\nconda activate my_environment \n\nin a bash script it just runs in the script.\nI found that creating an alias in .bashrc is all that is required to change directory to a particular project I'm working on, and set up the correct conda environment for me. So I included in .bashrc:\nalias my_environment="cd ~/subdirectory/my_project && conda activate my_environment"\n\nand then:\nsource ~/.bashrc\n\nThen I can just type at the command line:\nmy_environment\n\nto change to the correct project and correct environment everytime I want to work on a different project.",
2021-10-22T08:56:19
qidong :

I use 'source command' to run the shell script, it works:\n\nsource shell_script.sh\n",
2019-07-02T12:53:55
Brent :

This answer is similar to @Lamma answer. This worked for me ->\n(1) I defined several variables; the conda activate function, environments directory and environment\nconda_activate=~/anaconda3/bin/activate\nconda_envs_dir=~/anaconda3/envs\nconda_env=<env name>\n\n(2) I source conda activate with the environment\nsource ${conda_activate} ${conda_envs_dir}/${conda_env}\n\n(3) then you can run your python script\npython <path to script.py>\n\nThis bypasses the conda init requirement. my .bashrc already was initialized and sourcing the .bashrc file didn't work for me. @Lamma's answer worked for me as well as the above code.",
2021-05-23T23:29:50
Niayesh Isky :

The error message is rather helpful - it's telling you that conda is not properly set up from within the subshell that your script is running in. To be able to use conda within a script, you will need to (as the error message says) run conda init bash (or whatever your shell is) first. The behaviour of conda and how it's set up depends on your conda version, but the reason for the version 4.4+ behaviour is that conda is dependent on certain environment variables that are normally set up by the conda shell itself. Most importantly, this changelog entry explains why your conda activate and deactivate commands no longer behave as you expect in versions 4.4 and above.\n\nFor more discussion of this, see the official conda issue on GitHub. \n\n\n\nEdit: Some more research tells me that the conda init function mentioned in the error message is actually a new v4.6.0 feature that allows a quick environment setup so that you can use conda activate instead of the old source activate. However, the reason why this works is that it adds/changes several environment variables of your current shell and also makes changes to your RC file (e.g.: .bashrc), and RC file changes are never picked up in the current shell - only in newly created shells. (Unless of course you source .bashrc again). In fact, conda init --help says as much:\n\n\n IMPORTANT: After running conda init, most shells will need to be closed and restarted for changes to take effect\n\n\nHowever, you've clearly already run conda init, because you are able to use conda activate interactively. In fact, if you open up your .bashrc, you should be able to see a few lines added by conda teaching your shell where to look for conda commands. The problem with your script, though, lies in the fact that the .bashrc is not sourced by the subshell that runs shell scripts (see this answer for more info). This means that even though your non-login interactive shell sees the conda commands, your non-interactive script subshells won't - no matter how many times you call conda init. \n\nThis leads to a conjecture (I don't have conda on Linux myself, so I can't test it) that by running your script like so:\n\nbash -i shell_script.sh\n\n\nyou should see conda activate work correctly. Why? -i is a bash flag that tells the shell you're starting to run in interactive mode, which means it will automatically source your .bashrc. This should be enough to enable you to use conda within your script as if you were using it normally.",
2019-04-04T04:39:17
ntg :

The problem is that when you run the bash script, a new (linux) shell environment is created that was not initialized properly. If your intention is to activate a conda environment, and then run python through the script, you can properly initialize the created shell\nenvironment as discussed in the accepted solution.\nIf however you want to have the conda environment active after you finish this script, then this will not work because the conda environment has changed on the new shell and you exit that shell when you finish the script. Think of this as running bash, then conda activate... then running exit to exit that bash... More details in How to execute script in the current shell on Linux?:\nTL;DR:\n\nAdd the line #!/bin/bash as the first line of the script\nType the command source shell_script.sh or . shell_script.sh\n\nNote: . in bash is equivalent to source in bash.",
2022-09-26T10:24:44
Simba :

Quick solution for bash: prepend the following init script into your Bash scripts.\n\neval \"$(command conda 'shell.bash' 'hook' 2> /dev/null)\"\n\n\nDone.\n\n\n\nFor other shells, check the init conf of your shell, copy the following content within the shell conf and prepend it into your scripts.\n\n# >>> conda initialize >>>\n...\n# <<< conda initialize <<<\n\n\nYou can also use \n\nconda init --all --dry-run --verbose\n\n\nto get the init script you need in your scripts.\n\nExplanation\n\nThis is related with the introduction of conda init in conda 4.6.\n\nQuote from conda 4.6 release log\n\n\n 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” \n\n\nAfter conda init is introduced in conda 4.6, conda only expose command \n 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. \n\nBut to make these new commands work, you have to do an additional initialization with conda init.\n\nThe problem is that your script file is run in a sub-shell, and conda is not initialized in this sub-shell.\n\nReferences\n\n\nConda 4.6 Release\nUnix shell initialization\nShell startup scripts\n",
2019-09-24T13:37:15
marquitobb :

$ conda activate scratch\n\nor\n$ source activate scratch\n",
2021-11-19T00:10:13
Lamma :

Using conda activate or source activate in shell scripts does not always work and can throw errors like this. An easy work around it to place source ~/miniconda3/etc/profile.d/conda.sh above any conda activate command in the script:\nsource ~/miniconda3/etc/profile.d/conda.sh # Or path to where your conda is\nconda activate some-conda-environment\n\nThis is the solution that has worked for me and will also work if sharing scripts. This also gets around having to use conda init as on some clusters I have worked with the system is initialised but conda activate still won't work in a shell script.",
2020-03-04T09:45:02
hong xu :

if you want to use the shell script to run the other python file in the other conda env, just run the other file via the following command.\nos.system('conda run -n <env_name> python <path_to_other_script>')\n",
2020-12-14T12:48:08
HAltos :

What is the problem with simply doing something like this in your shell: \n\nsource /opt/conda/etc/profile.d/conda.sh \n\n(The conda init is still marked as Experimental, and thus not sure if it is a good idea to use it yet).",
2019-10-23T19:17:30
yy