knktc's Notes

python, cloud, linux...

0%

Shorten Poetry Virtualenv Prompt Prefix

I recently started using Poetry for Python package management, and one small annoyance showed up immediately: the shell prompt inside the virtual environment is unnecessarily long.

For example, if the project is named test-poetry, after running poetry shell the prompt may look like this:

(test-poetry-FvrREBVp-py3.6) knktc@knktc-rmbp test_poetry %

Poetry includes both an encoded suffix and the Python version in the virtual environment name, and then uses that full directory name as the prompt prefix. On a small screen, that takes up a surprising amount of space.

Since Poetry environments are still activated through bin/activate, the easiest fix is to find that file and adjust the prompt manually.

From the project directory, as long as pyproject.toml is present, run:

1
poetry env info -p

This prints the path to the current virtual environment, for example:

1
2
(test-poetry-FvrREBVp-py3.6) knktc@knktc-rmbp test_poetry % poetry env info -p
/Users/knktc/Library/Caches/pypoetry/virtualenvs/test-poetry-FvrREBVp-py3.6

Then open the bin/activate file in that environment:

1
vim /Users/knktc/Library/Caches/pypoetry/virtualenvs/test-poetry-FvrREBVp-py3.6/bin/activate

Around line 68, you should see the logic that sets PS1. It uses the environment directory name as the prompt prefix:

1
2
3
4
5
6
7
8
9
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1-}"
if [ "x" != x ] ; then
PS1="() ${PS1-}"
else
PS1="(`basename \"$VIRTUAL_ENV\"`) ${PS1-}" # <--- this line
fi
export PS1
fi

You can replace that line with a shorter, fixed project name:

1
2
3
4
5
6
7
8
9
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1-}"
if [ "x" != x ] ; then
PS1="() ${PS1-}"
else
PS1="(test-poetry) ${PS1-}" # <--- hard-code the project name
fi
export PS1
fi

Save the file, then reactivate the environment:

1
2
3
4
5
knktc@knktc-rmbp test_poetry % poetry shell
Spawning shell within /Users/knktc/Library/Caches/pypoetry/virtualenvs/test-poetry-FvrREBVp-py3.6
Restored session: Wed Feb 9 23:12:53 CST 2022
knktc@knktc-rmbp test_poetry % . /Users/knktc/Library/Caches/pypoetry/virtualenvs/test-poetry-FvrREBVp-py3.6/bin/activate
(test-poetry) knktc@knktc-rmbp test_poetry %

Much better.

如果我的文字帮到了您,那么可不可以请我喝罐可乐?