Question

I uses autoenv for automatic virtualenv activate. Python project's top folder has .env file with following contents

source venv/bin/activate

This command executed whenever cd to any sub folder of the project. Then throws

-bash: venv/bin/activate: No such file or directory

It failed because it is trying to execute activate relative to sub folder. Why it executes even in subfolder? How to resolve the issue?

Was it helpful?

Solution

Had this issue today. The current answer doesn't address the fact that the environment is activated every time you cd into a subfolder or back to the root folder. Solved it with the following .env script:

venv=venv
currentvenv=""

if [[ $VIRTUAL_ENV != "" ]]
then
  # Strip out the path and just leave the env name
  currentvenv="${VIRTUAL_ENV##*/}"
fi

if [[ "$currentvenv" != "$venv" ]]
then
  echo "Switching to environment: $venv"
  workon $venv
#else
#  echo "Already on environment $venv"
fi

Replace venv with the name of your environment. You can uncomment the else block to see that it doesn't try to activate the environment every time, given that the desired environment is already activated.

Note: If you're not using virtualenvwrapper then you should replace the workon command with whatever command you're using to activate your virtual environment. I do recommend using virtualenvwrapper though.

OTHER TIPS

In your workspace root, a .env containing:

test (command -v deactivate) && deactivate

and in each of your relevant project folders:

workon venv_of_project

As this person points out, it means that cding around in a project will turn the workspace on and off, but at least it is simple and very clear what is going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top