問題描述
我正在尋找一種從正在運行的代碼或交互式 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
這篇關于如何找到運行我的代碼的 conda 環境的名稱?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!