CuFF
CuFF

Reputation: 33

Conda Environment doesn't stay activated throughout the bash script

I'm making an installer using the below bash script. After activating the env and later on checking the active env using the conda info, it shows that No env is active. Please refer to the image

Even after installing dependencies, the packages are not installed in the env, instead it's getting installed in the base env.

The script-

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

conda create --name count python=3.7 <<< 'y'

. $(conda info --base)/etc/profile.d/conda.sh

conda activate count

conda info

#install dependencies

pip install -r requirements_count.txt

Thanks in advance for going through the query!

enter image description here

Upvotes: 1

Views: 391

Answers (1)

merv
merv

Reputation: 76700

First, iteratively using ad hoc installs is a bad pattern. Better practice is to predefine everything in the environment with a YAML. That can even include PyPI packages and requirements.txt files.

count.yaml

name: count
channels:
  - conda-forge
dependencies:
  ## Conda deps
  - python=3.9  ## change to what you want, but preferable to specify
  
  ## PyPI deps
  - pip
  - pip:
    - -r requirements_count.txt

Second, conda activate is intended for interactive shells, not scripts. One can run a bash script interactively by including an -l flag in the shebang. But better practice is to use the conda run method, which is designed for programmatic execution of commands in a specified context.

Pulling this together, the script might be:

script.sh

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

## create the environment
conda create -n count -f count.yaml

## execute a Python script in the environment
conda run -n count python my_code.py

If the code run in the environment needs to interact with a user or stream output, you may need additional flags (--no-capture-output, --live-stream). See conda run --help.

Upvotes: 2

Related Questions