pdm icon indicating copy to clipboard operation
pdm copied to clipboard

Friendly PS1 prompt when activating virtual environment

Open borice opened this issue 3 years ago • 1 comments

Thanks for the great work on PDM - I just discovered it and would like to switch to it from Poetry, but am missing a much-needed feature:

It would be very helpful for situations when working on several Python projects, each with its own virtual environment, to be able to easily tell which virtual environment is currently activated in the various Terminal tabs. The easiest way (and most popular way) is to modify PS1 when a venv is activated to indicate the name of the venv. While this might work for centrally-managed venvs, many of us prefer to use venv.in_project = True. Unfortunately, in this scenario, the source .venv/bin/activate results in a generic (.venv) prefix added to PS1 which isn't very helpful since it's the same across all projects and can't be used to tell them apart.

Poetry has found a way to make this work, for venvs created by Poetry, by modifying the .venv/bin/activate at the time of venv creation to set PS1 in line 66

  63   │ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
  64   │     _OLD_VIRTUAL_PS1="${PS1-}"
  65   │     if [ "xproject-name-py3.10" != x ] ; then
  66   │         PS1="(project-name-py3.10) ${PS1-}"
  67   │     else
  68   │         PS1="(`basename \"$VIRTUAL_ENV\"`) ${PS1-}"
  69   │     fi
  70   │     export PS1
  71   │ fi

which, for the above, results in a (project-name-py3.10) PS1 prefix. The "project-name-py3.10" PS1 prefix was the result of virtualenvs.prompt = "{project_name}-py{python_version}" setting in Poetry config, where {project_name} is the actual name of the project set in pyproject.toml (and asked for when doing poetry init -- incidentally I think this is a good thing to add to pdm init as well) and {python_version} is the actual python version used in the venv.

To fully explain what Poetry is doing I should mention that they store the actual prompt value in .venv/pyvenv.cfg like so:

...
prompt = project-name-py3.10

borice avatar Aug 21 '22 04:08 borice

Good to have, care to implement it via a PR?

frostming avatar Aug 27 '22 08:08 frostming

Implemented by #1390

frostming avatar Sep 27 '22 02:09 frostming