如何找到我的代码在其中运行的conda环境的名称? [英] How do I find the name of the conda environment in which my code is running?

查看:723
本文介绍了如何找到我的代码在其中运行的conda环境的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种很好的方法,可以从运行代码或交互式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.

用例是我正在从miniconda安装中同时运行带有Python 2和Python 3内核的Jupyter笔记本.默认环境是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']).

问题在于,如果笔记本计算机正在使用Py2内核运行,则该命令需要知道Py2环境的名称才能在其中安装foo.如果没有该信息,它将安装在默认的Py3 env中.我想让代码自己弄清楚它所处的环境,并为其正确地命名.

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


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


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

我可以找到的关于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

这篇关于如何找到我的代码在其中运行的conda环境的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆