Search code examples
pythonxonsh

How to use {env_name} conditionally in a xonsh prompt


In the xonsh shell how can I use the name of the virtual environment I'm use as a condition in the definition of $PROMPT?

(More in detail: I have a virtual environment called 'xonsh' for the xonsh shell itself, but I do not want this venv to be shown in the prompt, but any other activated venv should be shown in the prompt.)


Solution

  • Start by looking at xonsh/prompt/env.py to see how we define the env_name function -- since you use virtualenv, you can do something like the following in your xonshrc:

    import os.path
    
    def env_name_cust(pre_chars="(", post_chars=")"):
        """Extract the current environment name from $VIRTUAL_ENV 
        """
        env_path = __xonsh__.env.get("VIRTUAL_ENV", "")
        env_name = os.path.basename(env_path)
        if env_name and env_name != 'xonsh':
            return pre_chars + env_name + post_chars
    

    Then add that function to the $PROMPT_FIELDS dictionary:

    $PROMPT_FIELDS['env_name_cust'] = env_name_cust

    Then you can use {env_name_cust} in your $PROMPT formatting string in place of the default {env_name}

    You can also use ${...} as a substitute for __xonsh__.env if you like.