How do I find the name of the conda environment in which my code is running?
Solution 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
The environment variables are not well documented. You can find CONDA_DEFAULT_ENV
mentioned here:
https://www.continuum.io/blog/developer/advanced-features-conda-part-1
The only info on CONDA_PREFIX
I could find is this Issue:
https://github.com/conda/conda/issues/2764
Solution 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.
Solution 3
conda info
directly lists all the information where in the first lines you can see the
active environment: (some name)
active env location: (location of active environment)
I guess this is the most clear way.
In an interactive environment like Jupyter Notebook or Jupyter Lab, you should use % before typing the commands, like the following,
%conda info
Solution 4
Edit: Oops, I hadn't noticed Ivo's answer. Let's say that I am expanding a little bit on it.
If you run your python script from terminal:
import os
os.system("conda env list")
This will list all conda environments, as from terminal with conda env list
.
Slightly better:
import os
_ = os.system("conda env list | grep '*'")
The _ =
bit will silence the exist status of the call to os.system
(0
if successful), and grep
will only print out the line with the activated conda environment.
If you don't run your script from terminal (e.g. it is scheduled via crontab
), then the above won't have anywhere to "print" the result. Instead, you need to use something like python's subprocess
module. The simplest solution is probably to run:
import subprocess
output = subprocess.check_output("conda env list | grep '*'", shell=True, encoding='utf-8')
print(output)
Namely output
is a string containing the output of the command conda env list
, not its exit status (that too can be retrieved, see documentation of the subprocess
module).
Now that you have a string with the information on the activated conda environment, you can perform whichever test you need (using regular expressions) to perform (or not) the installs mentioned in your question.
Remark.
Of course, print(output)
in the block above will have no effect if your script is not run from terminal, but if you test the block in a script which you run from terminal, then you can verify that it gives you what you want. You can for instance print this information into a log file (using the logging
module is recommended).
Solution 5
very simply, you could do
envs = subprocess.check_output('conda env list').splitlines()
active_env = list(filter(lambda s: '*' in str(s), envs))[0]
env_name = str(active_env).split()[0]
Alnilam
Updated on July 05, 2022Comments
-
Alnilam almost 2 years
I'm looking for a good way to figure out the name of the conda environment I'm in from within running code or an interactive python instance.
The use-case is that I am running Jupyter notebooks with both Python 2 and Python 3 kernels from a miniconda install. The default environment is Py3. There is a separate environment for Py2. Inside the a notebook file, I want it to attempt to
conda install foo
. I'm usingsubcommand
to do this for now, since I can't find a programmatic conda equivalent ofpip.main(['install','foo'])
.The problem is that the command needs to know the name of the Py2 environment to install
foo
there if the notebook is running using the Py2 kernel. Without that info it installs in the default Py3 env. I'd like for the code to figure out which environment it is in and the right name for it on its own.The best solution I've got so far is:
import sys def get_env(): sp = sys.path[1].split("/") if "envs" in sp: return sp[sp.index("envs") + 1] else: return ""
Is there a more direct/appropriate way to accomplish this?
-
Alnilam about 8 yearsI get an error running this unless I put the command as a list --
['conda','env','list']
-- and then I get the same answer (root) whether I run this using a Py2 or a Py3 kernel. Examining thesys.path
, however, shows different results for each. -
Antoine almost 5 yearsHow does this give the name of the conda environment?
-
Christopher Barber almost 5 yearsThis is incorrect if you are running a python that is not from the active environment.
-
Triamus over 4 yearsfor me it's
Path(sys.executable).as_posix().split('/')[-2]
-
Textcape about 4 yearsPython solution doesn't work for py3 because... parentheses... For py3:
-
Textcape about 4 yearsprint(os.environ['CONDA_DEFAULT_ENV'])
-
norman123123 almost 4 yearsExcelent. I just want to add that
source deactivate
is deprecated, now you have to useconda deactivate
. -
sonictl almost 3 yearsThis answers my confusion. I installed jupyter notebook with
pip3 install
and the jupyter notebook will run in the environment given by pip3 instead of conda. I have conda installed but Anaconda is not installed on my CentOS linux. -
Charlie Parker almost 3 yearsbut this doesn't the entire path, just the name of the head....something like this
/home/miranda9/miniconda3/envs/metalearning
is what I want. So doimport os; print(os.environ["CONDA_PREFIX"])