Ruchit
Ruchit

Reputation: 356

How to get path of conda env from its name?

When I do conda info --envs, I get list of all envs and their locations like this:

# conda environments:
#
base                  *  /Users/mbp/miniconda3
myenv              /Users/mbp/miniconda3/envs/myenv

Is there a way to get the location of myenv environment from command line? May be something like conda info --envs myenv to get

/Users/mbp/miniconda3/envs/myenv

What's the use case?
I want to cache all the environment dependencies in GitHub actions. This has to happen before the environment is activated. If I know the location of the environment, I can cache all the files in it.

Upvotes: 5

Views: 13383

Answers (4)

brunobeltran0
brunobeltran0

Reputation: 74

This is an old question, but all of the responses currently rely on the format of the output of a conda command designed to be read only by humans.

You can pass --json to get machine-parseable output then use jq to extract the information you need in a reliable way.

As you can see by running conda info --json, the machine-parseable version does not actually include environment names...this is because the environment's name is defined by the name of the environment's containing folder, so you can just do something like

$ conda info --json | jq -r '.envs[] | select(. | endswith("/${YOUR_ENV_NAME}") )'
  • -r to output the raw string (not JSON)
  • .envs[] to get the list of all environment locations
  • | select( ... ) to filter our just the one you want
  • a slash before the environment name to prevent issues with environments whose names are a suffix of another environment name.

Upvotes: -1

hermidalc
hermidalc

Reputation: 568

$(conda info --base)/envs/myenv

Upvotes: 6

merv
merv

Reputation: 77098

Conda's internal function to handle prefix resolution (locate_prefix_by_name) is currently located in conda.base.context, so one could avoid listing all envs with a script like:

conda-locate.py

#!/usr/bin/env conda run -n base python

import sys
from conda.base.context import locate_prefix_by_name

print(locate_prexif_by_name(sys.argv[1]), end='')

Usage

# make executable
chmod +x conda-locate.py

./conda-locate.py jupyter
# /Users/user/miniforge/envs/jupyter

You may want to add a try..catch to handle the conda.exceptions.EnvironmentNameNotFound exception.

Upvotes: 2

Jagadeesh K
Jagadeesh K

Reputation: 886

conda info --envs | grep -Po 'myenv\K.*' | sed 's: ::g'

This bash command will retrieve all envs from conda and find the line which starts from myenv and give it to the sed command which inturn removes the spaces

surprisingly it worked for me

Upvotes: 5

Related Questions