如何找到运行我的代码的 conda 环境的名称?

2022-01-10 00:00:00 python jupyter conda anaconda env

问题描述

我正在寻找一种从正在运行的代码或交互式 python 实例中找出我所在的 conda 环境名称的好方法.

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.

用例是我正在运行 Jupyter 笔记本,同时安装了 miniconda 的 Python 2 和 Python 3 内核.默认环境是 Py3.Py2 有一个单独的环境.在笔记本文件中,我希望它尝试 conda install foo.我现在使用 subcommand 来执行此操作,因为我找不到与 pip.main(['install','foo']) 等效的编程 conda.

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']).

问题是如果 notebook 使用 Py2 内核运行,该命令需要知道 Py2 环境的名称才能在其中安装 foo.如果没有该信息,它将安装在默认的 Py3 环境中.我希望代码能够自行确定它所在的环境以及正确的名称.

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?


解决方案

你想要 $CONDA_DEFAULT_ENV$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)

在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


环境变量没有很好的记录.您可以找到此处提到的 CONDA_DEFAULT_ENV:https://www.continuum.io/blog/developer/advanced-features-conda-part-1

我能找到的关于 CONDA_PREFIX 的唯一信息是这个问题:https://github.com/conda/conda/issues/2764

The only info on CONDA_PREFIX I could find is this Issue: https://github.com/conda/conda/issues/2764

相关文章