Python PDM package manager: How to enable virtual environment autodetection?

2.8k views Asked by At

Python PDM Project

https://pdm.fming.dev/latest/

https://github.com/pdm-project/pdm

My Problem

In context below I want to activate the in-project virtual environment automatically whenever the directory changes to inclued the path ~/pydev/pdm-test.

Tree View of PDM Test Folder

$ tree ~/pydev/pdm-test -aL 2
/home/joe/pydev/pdm-test
├── 0000-proj0000
│   ├── main.py
│   └── __pycache__
├── 0005-proj0005
├── 0010-proj0010
├── pdm.lock
├── .pdm.toml
├── pyproject.toml
└── .venv
    ├── bin
    ├── .gitignore
    ├── lib
    └── pyvenv.cfg

Manual Activation of Virtual Environment (this works)

$ eval $(pdm venv activate in-project)

Virtual Environment Autodetection

https://pdm.fming.dev/latest/usage/venv/

When no interpreter is stored in the project config or PDM_IGNORE_SAVED_PYTHON env var is set, PDM will try to detect possible virtualenvs to use:

  • venv, env, .venv directories in the project root
  • The currently activated virtualenv

Question - Where is the "project config" file and how do I edit this file or use a pdm command to enable virtual environment autodetection?

2

There are 2 answers

0
Frost Ming On

The python path is stored in the project config file .pdm.toml, view it and remove the corresponding line to clear the python path. You can also do it with command line: pdm config -ld python.path

1
omars On

I don't know a straight forward way to auto-activate the venv in the current shell.

Where is the "project config" file

.pdm-python Inside the project root

how do I edit this file or use a pdm command to enable virtual environment autodetection?

auto-detection works by default, what is meant by auto-detection is that if you run any pdm command, it will use that venv, which is normally .venv in the project root, auto-activation is a different topic.

Update: Auto-Activation in ~/.bashrc, ~/.zshrc

function cd {
    builtin cd "$@"
    # bash regex pdm-test / conditionally activate the venv in the current shell
    if [[ "$PWD" =~ pdm-test ]]
    then
        eval $(pdm venv activate)
    fi
}

Hope that helps