在PS1中显示pipenv虚拟环境

3

Pipenv 是一个相对较新的打包工具,涵盖了 "Pipfile, Pip, and Virtualenv"。我已经对我的 .bashrc 进行了简化,但现在发现我需要我的 PS1 来告诉我何时正在使用我的 virtualenv。

当前的 PS1:

PS1='\w $ '

从下面可以看出,我的提示脚本没有任何提示告诉我是否正在使用虚拟环境:
~ $ cd workspace/myproject/
~/workspace/myproject $ pipenv shell
Launching subshell in virtual environment. Type 'exit' or 'Ctrl+D' to return.
~/workspace/marcus_project $ 

我经常弄错PS1,希望有一个简单的解决方法,让虚拟环境中的提示显示为:(my-env) ~ $

2个回答

5
根据文档,在您的项目中创建一个名为.env的文件,并将其内容放入其中。
export PS1='(myenv) \w $ '

或者其他你想要的。使用pipenv shell将加载它。

(注意:我自己没有尝试过pipenv。今天我才知道它的存在! :))

修改后

如果你的.bashrc.profile(或其他启动文件)设置了PS1,你可以对其进行修改。

  • Put export PIPENV_PS1='(myenv) \w $ ' in your .env. (The name PIPENV_PS1 isn't anything special — I just picked something I thought made sense.)
  • At the end of your .bashrc, add:

    if [[ $PIPENV_PS1 ]]; then
        export PS1="$PIPENV_PS1"
    fi
    

这样你的.bashrc文件将会复制你在.env文件中设置的值。


嗯,似乎没有任何作用。我的bashrc中的PS1是否会覆盖.env - Max

3
如果您已安装virtualenv,则此行为可以通过pipenv轻松实现。但我遇到的问题是,pipenv shell混淆了我定义的自定义PS1。我在这里回答是因为在搜索时,这个问题与我的问题最相似。
为了解决这个问题,我需要进入vim ~/.virtualenvs/环境名称/bin/activate文件中。在那里,我更改了定义PS1的代码,将其替换为我在.bash_profile中使用的PS1。现在,pipenv shell使用if [ "x(data-load) " != x ] ; then语句内部的PS1。
我相信可能有更好的方法来修复这个问题,而不需要重新定义文件中的PS1并使用.bash_profile里的PS1。但我不想再花更多的时间在这个问题上。
...

if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
    # add this line to get original PS1 prompt
    PS1=ORIGINAL PS1 in .bash_profile
    if [ "x(data-load) " != x ] ; then
        # here add the name of the virtual env, and some color if in the mood
        PS1="\[\033[39m\](myenv) ${PS1-}"
    else
        PS1="(`basename \"$VIRTUAL_ENV\"`) ${PS1-}"
    fi
    export PS1
fi

...

感谢您发布这篇文章。很遗憾我们无法设置一个环境变量来使 activate 忽略在我们的 shell 中设置或覆盖 PS1。我正在使用一个自定义的 git 提示符,但这会将其覆盖掉。 - Felipe Alvarez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接