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?
conda install x
will install into whatever the current environment is: so if the notebook is in the Python 2 environment then it will install into that environment. – Zeeba!conda env list
in one cell andimport subprocess; print(subprocess.check_output(['conda','env', 'list']).decode())
in another. Both show the default env as being active whether I run the notebook in Py2 or Py3, so it may be that commands being issued against the os operate in whatever env the jupiter server was launched using. – Victualconda env list
and the*
points to the current turned on env. Reason I do this is despite the name appearing on the terminal name prompt, I've had issues when the prompt does not match the env I'm using (e.g. using vscode). – Vitreous$ echo $CONDA_PREFIX
see output:/home/miranda9/miniconda3/envs/metalearning
– Vitreousimport os; print(os.environ["CONDA_PREFIX"])
print/Users/miranda9/.conda/envs/synthesis
– Vitreous