Managing Virtual Environments in Python

venv are fiddly sometimes but necessary

30 Jul 2022

Reminders for managing virtual environments in Python.

Option 1

python3 -m venv venv

then

source venv/bin/activate

or

. venv/bin/activate

(same command - . is a shortcut for source)

Option 2 - with library

pip3 install virtualenv

then

virtualenv .venv

Load automatically in VS Code

in .vscode > settings.json add:

"python.terminal.activateEnvironment": true

Delete venv

`rm -rf venv`   

Troubleshooting

The venv/bin/activate file can be opened to check the Python path. This is what matters:

VIRTUAL_ENV="/Users/path/to/project/folder/venv"
export VIRTUAL_ENV

script using Python global instead of venv

Ran into the issue where the script was using the global Python instead of the venv's.

After activating my venv, the which command showed that the path is correct, double-confirmed by checking the file path in the venv/bin/activate file.

However, when running the script, it uses the global python install:

(venv) n1c@MacN imapee % which python
/Users/n1c/Python/imapee/venv/bin/python

running the script:

(venv) n1c@MacN imapee % /usr/bin/python3 /Users/n1c/Python/imapee/test.py

It appeared that the file pyvenv.cfg was messing things up - not sure how that file was generated/included. Renaming it (or deleting it) solved the issue.

have you tried turning it off and on again?

15 Aug 2022

same problem as above resurfaced with another project and pyvenv.cfg didn't help.

Deleting venv with rm -rf venv and reinstalling solved the issue.

Using

21 Jul 2023

Try to use a .env file, but simply configure launch.json to use the venv's Python path.

"envFile": "${workspaceFolder}/.env",

links

social