Python 如何找到运行我的代码的 conda 环境的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36539623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the name of the conda environment in which my code is running?
提问by Alnilam
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.
我正在寻找一种好方法来从正在运行的代码或交互式 python 实例中找出我所在的 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'])
.
用例是我从 miniconda 安装运行带有 Python 2 和 Python 3 内核的 Jupyter 笔记本。默认环境是 Py3。Py2 有一个单独的环境。在笔记本文件中,我希望它尝试将conda install foo
. 我现在正在使用subcommand
此方法,因为我找不到与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.
问题是foo
如果笔记本使用 Py2 内核运行,该命令需要知道 Py2 环境的名称才能安装在那里。如果没有该信息,它会安装在默认的 Py3 环境中。我希望代码能够自行确定它所处的环境以及正确的名称。
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?
有没有更直接/更合适的方法来实现这一目标?
回答by NHDaly
You want $CONDA_DEFAULT_ENV
or $CONDA_PREFIX
:
你想要$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)
In python:
在蟒蛇中:
In [1]: import os
...: print os.environ['CONDA_DEFAULT_ENV']
...:
my_env
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_DEFAULT_ENV
这里找到: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
CONDA_PREFIX
我能找到的唯一信息是这个问题:https:
//github.com/conda/conda/issues/2764
回答by Daniel Schneider
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
.
它的优点是它不假设 env 在路径中(并且嵌套在 下envs
)。此外,它不需要通过source activate
.
Edit: If you want to make sure it works on Windows, too:
编辑:如果您想确保它也适用于 Windows:
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.
澄清:sys.executable
为您提供当前 python 解释器的路径(无论激活/停用)——例如'/Users/danielsc/miniconda3/envs/nlp/bin/python'
. 其余代码只取最后一个路径段的第三个,即环境所在文件夹的名称,通常也是python环境的名称。
回答by Ivo
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]
回答by Antoine
Edit:Oops, I hadn't noticed Ivo's answer. Let's say that I am expanding a little bit on it.
编辑:糟糕,我没有注意到Ivo的回答。假设我正在扩展它。
If you run your python script from terminal:
如果您从终端运行 python 脚本:
import os
os.system("conda env list")
This will list all conda environments, as from terminal with conda env list
.
这将列出所有 conda 环境,如带有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.
该_ =
位将使调用的存在状态静音os.system
(0
如果成功),并且grep
只会打印出带有激活的 conda 环境的行。
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:
如果你不从终端运行你的脚本(例如它是通过 调度的crontab
),那么上面的内容将没有任何地方可以“打印”结果。相反,您需要使用类似 pythonsubprocess
模块的东西。最简单的解决方案可能是运行:
import subprocess
output = subprocess.check_output("conda env list | grep '*'", shell=True, encoding='utf-8')
print(output)
Namely output
is a string containing the outputof the command conda env list
, not its exit status (that too can be retrieved, see documentation of the subprocess
module).
即output
是一个包含命令输出的字符串conda env list
,而不是它的退出状态(也可以检索,请参阅subprocess
模块的文档)。
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.
现在您有一个包含激活的 conda 环境信息的字符串,您可以执行您需要的任何测试(使用正则表达式)来执行(或不执行)问题中提到的安装。
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).
评论。
当然,print(output)
如果您的脚本不是从终端运行,则上面的块将不起作用,但是如果您在从终端运行的脚本中测试该块,那么您可以验证它是否提供了您想要的。例如,您可以将此信息打印到日志文件中(logging
推荐使用该模块)。
回答by codeslord
Since similar searches related to 'how do I determine my python environment' leads to this answer I thought I will also mention a way I find out which environment I am currently running my code from. I check the location of my pipbinary which points to a locationwithin the current environment. By looking at the output of the following command you can easily determine which environment you are in. (Please note that this solution is not applicable if you have inherited pip packages from your global environment/other environment)
由于与“如何确定我的 python 环境”相关的类似搜索导致了这个答案,我想我还会提到一种方法来找出我当前正在运行我的代码的环境。我检查我的位置PIP二进制指向一个位置的内当前的环境。通过查看以下命令的输出,您可以轻松确定您所在的环境。 (请注意,如果您从全局环境/其他环境继承了 pip 包,则此解决方案不适用)
In Windowscommand prompt:
在Windows命令提示符下:
where pip
If you are inside a Jupyter Notebookadd an exclamation mark(!) before the command to execute the command in your host command prompt:
如果您在Jupyter Notebook 中,请在命令前添加感叹号 (!) 以在主机命令提示符中执行命令:
in[10]: !where pip
The output will look something like this:
输出将如下所示:
C:\Users\YourUsername\.conda\envs\YourEnvironmentName\Scripts\pip.exe
C:\ProgramData\Anaconda3\Scripts\pip.exe
YourEnvironmentNamegives out the name of your current environment.
YourEnvironmentName给出您当前环境的名称。
In Linux/Mac, you can use the which command instead of where: (Not tested).
在Linux/Mac 中,您可以使用 which 命令而不是 where:(未测试)。
For python3 environment
对于python3环境
which pip3
From Jupyter notebook:
从Jupyter 笔记本:
in[10]: !which pip3
This should directly point to the location within your current environment.
这应该直接指向您当前环境中的位置。
回答by MZB
On Windows (might work but untested on Linux):
在 Windows 上(可能工作但在 Linux 上未经测试):
import sys
import os
# e.g. c:\Users\dogbert\Anaconda3\envs\myenvironment
print( sys.exec_prefix.split(os.sep)[-1] )
Answers using environment variables or assuming the path separator is "/" didn't work in my Windows/Anaconda3 environment.
使用环境变量或假设路径分隔符为“/”的答案在我的 Windows/Anaconda3 环境中不起作用。
This assumes you are in an environment.
这假设您在一个环境中。
回答by cchung85
Several answers suggest the use of 'which pip', 'which python', or 'conda env list to grep the default'. This work if the user is doing something like: $ conda activate env_name; $ python ... or $ jupyter notebook/jupyterlab.
When a user invokes python directly without conda activate, method #1 would not work: e.g. $ /opt/conda/envs/my_env/bin/python (where my_env is the name of env)
In a more general case with jupyter notebook, one can select any one of the available conda env/kernel, and the one selected may not be the same as the default.
So the solution is to examine the executable or path of your current python, like several folks have posted before. Basically, sys.path returns the full path of executable, and one can then use split to figure out the name after envs/ which would be the env_name. The person who asked this question gave a pretty good answer, except missing this ....
I don't think any post took care of the special case of the base env. Note python from base env is just /opt/conda/bin/python. So one can simply add the following code fragment do a match if /opt/conda/bin/python in sys.path: return 'base'
Here we assume conda is installed on /opt/conda. For really generic solution, one can use $ conda info --root to find the installation path.
几个答案建议使用“which pip”、“which python”或“conda env list to grep the default”。如果用户正在执行以下操作,则此项工作: $ conda activate env_name; $ python ... 或 $ jupyter notebook/jupyterlab.
当用户在没有 conda activate 的情况下直接调用 python 时,方法 #1 将不起作用:例如 $ /opt/conda/envs/my_env/bin/python (其中 my_env 是 env 的名称)
在使用 jupyter notebook 的更一般情况下,您可以选择任何可用的 conda env/kernel,并且选择的可能与默认值不同。
所以解决方案是检查当前 python 的可执行文件或路径,就像之前几个人发布的那样。基本上, sys.path 返回可执行文件的完整路径,然后可以使用 split 找出 envs/ 之后的名称,这将是 env_name。问这个问题的人给出了很好的答案,除了错过了这个......
我认为没有任何帖子处理基础环境的特殊情况。注意来自 base env 的 python 只是 /opt/conda/bin/python。因此,如果 /opt/conda/bin/python 在 sys.path 中,可以简单地添加以下代码片段进行匹配: return 'base'
这里我们假设 conda 安装在 /opt/conda 上。对于真正通用的解决方案,可以使用 $ conda info --root 来查找安装路径。