close

How do I find the name of the conda environment in which my code is running?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I find the name of the conda environment in which my code is running in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I find the name of the conda environment in which my code is running?

  1. How do I find the name of the conda environment in which my code is running?

    it has the advantage that it doesn't assume the env is in the path (and is nested under envs). Also, it does not require the environment to be activated via source activate.

  2. find the name of the conda environment in which my code is running

    it has the advantage that it doesn't assume the env is in the path (and is nested under envs). Also, it does not require the environment to be activated via source activate.

Method 1

You want $CONDA_DEFAULT_ENV or $CONDA_PREFIX:

$ source activate my_env
(my_env) $ echo $CONDA_DEFAULT_ENV
my_env

(my_env) $ echo $CONDA_PREFIX
/Users/nhdaly/miniconda3/envs/my_env

$ source deactivate
$ echo $CONDA_DEFAULT_ENV  # (not-defined)

$ echo $CONDA_PREFIX  # (not-defined)

In python:

In [1]: import os
   ...: print (os.environ['CONDA_DEFAULT_ENV'])
   ...:
my_env

for the absolute entire path which is usually more useful:

Python 3.9.0 | packaged by conda-forge | (default, Oct 14 2020, 22:56:29) 
[Clang 10.0.1 ] on darwin
import os; print(os.environ["CONDA_PREFIX"])
/Users/miranda9/.conda/envs/synthesis

Method 2

I am using this:

import sys
sys.executable.split('/')[-3]

it has the advantage that it doesn’t assume the env is in the path (and is nested under envs). Also, it does not require the environment to be activated via source activate.

Edit: If you want to make sure it works on Windows, too:

import sys
from pathlib import Path
Path(sys.executable).as_posix().split('/')[-3]

To clarify: sys.executable gives you the path of the current python interpreter (regardless of activate/deactivate) — for instance '/Users/danielsc/miniconda3/envs/nlp/bin/python'. The rest of the code just takes the 3rd from last path segment, which is the name of the folder the environment is in, which is usually also the name of the python environment.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read