Arya McCarthy
Arya McCarthy

Reputation: 8829

Create and activate Conda environment in same script

I'm trying to write an installer that uses both conda and pip. I'd like to activate the conda environment to call pip, but doing this in the same script causes problems.

#!/usr/bin/env bash
set -euo pipefail

conda create -y --name myenv python=3.6
conda init bash
conda activate myenv
# Perform pip-based installation here.

Running bash setup-environment.sh fails at the conda activate step:

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

While it's helpful to know that restarting my shell will solve the problem, I can't do that within the script. Is there a workaround?

Upvotes: 1

Views: 6019

Answers (1)

merv
merv

Reputation: 76700

Running bash in login mode should work, e.g.,

bash -l setup-environment.sh

Note, the conda init in the script is superfluous - it edits the .bash_profile but doesn't actually initialize a current bash session; it only needs to be executed once for a user. Hence, the script should be changed to

#!/usr/bin/env bash -l
set -euo pipefail

conda create -y --name myenv python=3.6 pip
conda activate myenv
# Perform pip-based installation here.

and you could just run it like ./setup-environment.sh.


Alternate Solution: Use YAML Environment Definition

Admittedly, I am missing the other parts you might have planned in your script, but everything that is shown could be more succinctly done using a Conda YAML environment definition. For example, if you write a YAML file like:

myenv.yaml

name: myenv
channels:
 - defaults
dependencies:
 - python=3.6
 - pip
 - pip:
   - some_pkg

and then run

conda env create -f myenv.yaml

it would do exactly what your script is doing, including all the pip installations. All commands that you can run in a pip requirements.txt can be included in a YAML. See the Advanced Pip Example in the Conda GitHub.

Upvotes: 3

Related Questions