2

I'm trying to achieve a PS1 that will output [3.6.5@BooksHerokuDjango ~]$

My .bashrc has this:

export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
if command -v pyenv 1>/dev/null 2>&1; then
  eval "$(pyenv init -)"
fi

eval "$(pyenv virtualenv-init -)"
export PYENV_VIRTUALENV_DISABLE_PROMPT='1'

function __python_prompt {
  version_number=`python -V | cut -d " " -f2-`
  version_name=`pyenv version-name`
  at='@'
  python_prompt=$version_number$at$version_name
  echo $python_prompt
}
PS1="[\$(__python_prompt) \W]\$ "
export PS1

I have the following pyenv versions:

[3.6.5@BooksHerokuDjango ~]$ pyenv versions
system
2.7.14
2.7.14/envs/HackerNewsHerokuDjango
3.2
3.2/envs/BlogHerokuDjango
3.6.5
3.6.5/envs/BooksHerokuDjango
3.6.5/envs/PortfolioDjango
BlogHerokuDjango
* BooksHerokuDjango (set by PYENV_VERSION environment variable)
HackerNewsHerokuDjango
PortfolioDjango

When I change the virtualenv like so:

[3.6.5@BooksHerokuDjango ~]$ pyenv activate HackerNewsHerokuDjango 
Python 2.7.14
[@HackerNewsHerokuDjango ~]$ 

The PS1 doesn't output like this [2.7.14@HackerNewsHerokuDjango ~]$

But then I change the virtualenv again:

Python 2.7.14
[@HackerNewsHerokuDjango ~]$ pyenv activate PortfolioDjango 
[3.6.5@PortfolioDjango ~]$

I get the PS1 output that I wanted. What am I doing wrong for it to be inconsistent?

  • Interesting, it looks like when you print the version for Python 2, it prints on stderr instead of stdout, so it isn't captured when updating your prompt. Try changing your function to use: `version_number=\`python -V |& cut -d " " -f2-\`` – 0x5453 Apr 04 '18 at 16:04
  • Great that did the trick, thank you! –  Apr 04 '18 at 16:10
  • 1
    You probably don't want to run `python -V` and `pyenv` every time the prompt is displayed, rather the python version and virtual env name should be updated (by setting environment variables) only when you actually activate a virtual env the first time. – chepner Apr 04 '18 at 16:21

0 Answers0