3

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

halloleo
  • 9,216
  • 13
  • 64
  • 122

1 Answers1

3

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.

halloleo
  • 9,216
  • 13
  • 64
  • 122
Gil Forsyth
  • 398
  • 1
  • 7
  • 1
    Works a treat! Thanks. I had tried assigning a function straight to $PROMPT but didn't get to a working version with it. – halloleo Nov 09 '18 at 05:47