Begoodpy
Begoodpy

Reputation: 1094

How to create and activate conda env in one line?

It often happens that when I create a conda environment, I forgot about activating it, despite the clear conda message. And I end up installing my packages in the conda base environment. (yeah... I'm a bit of a dreamer)

My questions are:

  1. Are there use cases where you create a conda environment but don't activate it right after?
  2. How to create a conda environment and activate it in a single line? (in a Linux prompt shell, and non-interactive)

Upvotes: 3

Views: 1712

Answers (1)

einfeyn496
einfeyn496

Reputation: 121

As a concrete example in answer to your first question, I have used conda as a way to wrap a disposable build environment in some Makefile targets, i.e., I create the environment, and then subsequent commands or targets may make use of the environment via conda run.

Adapting a snippet from one Makefile, you could create a function in a bash startup file:

    conda_create_and_run() {
        ENV_NAME=$1
        CONDA_PY_VER=$2
        . ${CONDA_ENV_FILE}
        conda config --append envs_dirs ${CONDA_DIR}
        conda create -p ${CONDA_DIR}/${ENV_NAME} python=${CONDA_PY_VER} -y
        conda activate ${ENV_NAME}
    }

Here CONDA_PY_VER is the non-default python version you want the environment to possibly be created with, and CONDA_DIR and CONDA_ENV_FILE are, respectively, the location where conda keeps its environments and the conda environment file you need to source (or have part of your shell init) in order to have the conda commands available.

You would then use it as:

conda_create_and_run myenv 3.8

to create an environment for python3.8 named myenv.

Upvotes: 2

Related Questions