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

后端 未结 8 1688
耶瑟儿~
耶瑟儿~ 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:28

    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.

    Edit: If you want to make sure it works on Windows, too:

    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.

提交回复
热议问题