pythonspyder

How can I show the conda environment name in the IPython console?


Context

I would like to show the conda environment name in the IPython console of Spyder, so I know which environment I'm running in.
While this information is available in the status bar, it sometimes just shows conda instead of the actual environment name:

enter image description here

What I've tried

Printing it at startup

Spyder allows one to run code at the start of a console. However, it seems print statements are suppressed as I've added import sys; print(sys.executable):

enter image description here

Unfortunately nothing is shown (besides the default banner) when I create a new console.

Changing the input prompt

Spyder allows one to customize the input/output prompts in the console. However, I can't figure out how to let it evaluate code instead of writing it as text:

enter image description here

Question

How to show the name of the active conda environment in the IPython console of Spyder?


Solution

  • The suggestion to look at the relevant issue (this comment in particular) has brought me the following solution:

    import sys; 
    env_path = sys.executable
    start_env = env_path.rfind('\\', 0, len(env_path) - 12) 
    end_env = env_path.rfind('\\')
    env_name = env_path[start_env+1:end_env]
    get_ipython().banner1=f"\nCurrent conda environment: {env_name}"
    

    By saving above in a file and setting it as the python startup file in the Spyder settings:

    enter image description here

    I now get a nice message informing me of the conda environment that is used:

    enter image description here