Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

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

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 using subcommand to do this for now, since I can't find a programmatic conda equivalent of pip.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...