Skip to content

Commit d23bee0

Browse files
authored
Use environment variable to identify conda / mamba (ipython#14515)
Conda and mamba both set an environment variable which refers to the base environment's executable path, use that in preference to less reliable methods, but fall back on the other approaches if unable to locate the executable this way. Additionally, change the search to look for the bare command name rather than the command within the top level of the active environment, I'm dubious this approach works with any current conda / mamba version which usually place their executable links in a `condabin` directory or elsewhere not at the same level as the Python executable. I believe this will also address ipython#14350, which I'm also seeing in a Windows context where the regex fails to parse and causes a traceback.
2 parents e77bdfa + 4c03ef3 commit d23bee0

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

IPython/core/magics/packaging.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#-----------------------------------------------------------------------------
1010

1111
import functools
12+
import os
1213
import re
1314
import shlex
1415
import sys
@@ -41,17 +42,29 @@ def _get_conda_like_executable(command):
4142
executable: string
4243
Value should be: conda, mamba or micromamba
4344
"""
45+
# Check for a environment variable bound to the base executable, both conda and mamba
46+
# set these when activating an environment.
47+
base_executable = "CONDA_EXE"
48+
if "mamba" in command.lower():
49+
base_executable = "MAMBA_EXE"
50+
if base_executable in os.environ:
51+
executable = Path(os.environ[base_executable])
52+
if executable.is_file():
53+
return str(executable.resolve())
54+
4455
# Check if there is a conda executable in the same directory as the Python executable.
4556
# This is the case within conda's root environment.
4657
executable = Path(sys.executable).parent / command
4758
if executable.is_file():
4859
return str(executable)
4960

5061
# Otherwise, attempt to extract the executable from conda history.
51-
# This applies in any conda environment.
62+
# This applies in any conda environment. Parsing this way is error prone because
63+
# different versions of conda and mamba include differing cmd values such as
64+
# `conda`, `conda-script.py`, or `path/to/conda`, here use the raw command provided.
5265
history = Path(sys.prefix, "conda-meta", "history").read_text(encoding="utf-8")
5366
match = re.search(
54-
rf"^#\s*cmd:\s*(?P<command>.*{executable})\s[create|install]",
67+
rf"^#\s*cmd:\s*(?P<command>.*{command})\s[create|install]",
5568
history,
5669
flags=re.MULTILINE,
5770
)

0 commit comments

Comments
 (0)