How do I find the name of the conda environment in which my code is running?

后端 未结 8 1673
耶瑟儿~
耶瑟儿~ 2020-12-08 18:48

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

8条回答
  •  温柔的废话
    2020-12-08 19:20

    1. 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.

    2. 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)

    3. 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.

    4. 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 ....

    5. 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'

    6. Here we assume conda is installed on /opt/conda. For really generic solution, one can use $ conda info --root to find the installation path.

提交回复
热议问题