I would like to detect in a general way from within a Python session whether it is managed by conda.
A few ideas that are not general enough to be useful:
1: Use environment variables
As mentioned in How do I find the name of the conda environment in which my code is running?
import os
is_conda = 'CONDA_PREFIX' in os.system or 'CONDA_DEFAULT_ENV' in os.system
This seems not to work in the root conda environment, where these variables are not always defined. It also has potential false positives if conda happens to be activated while you are using another Python installation.
2: Check the executable path
import sys
is_conda = ('anaconda' in sys.executable) or ('miniconda' in sys.executable)
This will work in the case that users install anaconda/miniconda in the default path. It may fail otherwise. It's also easy to imagine false-positives.
3. Check the version info
As noted in the answers to any way to tell if user's python environment is anaconda, you can check the Python version string in some cases:
import sys
is_conda = ('Continuum Analytics' in sys.version) or ('Anaconda' in sys.version)
This works currently for Python installed from the default channel, but this is quite brittle and may break in the future, particularly with Continuum's company name change. It also probably fails if Python is installed from a third-party source like conda-forge.
4. Check the conda
import
try:
import conda
except:
is_conda = False
else:
is_conda = True
This works as long as you're in the root conda environment, but generally fails if you're in another conda env where the conda
package is not installed by default.
5: Try conda
to see if it works
Suggestion from Atto Allas below:
import subprocess
try:
retcode = subprocess.call(['conda', 'install', '-y', 'pip'])
except:
is_conda = False
else:
is_conda = (retcode == 0)
This works in the simplest cases, but fails in the common case of using multiple kernels in Jupyter, where the conda
executable may or may not be connected to the current Python kernel.
Is there any entirely general way to detect from Python whether that Python installation is managed by conda?