skip to Main Content

I’m trying to automatically activate the virtual environment .venv in the terminal whenever I open vscode workspace. i have Python installed via pyenv.

I tried adding the following in both the user settings JSON file and the workspace settings JSON

"python.terminal.activateEnvInCurrentTerminal": true,
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",

but that did not work, I still need to run source .venv/bin/activate in the terminal whenever I launch the workspace to activate the virtual environment

I use pip -V in the terminal to verify which Python interpreter is being used like follows:
enter image description here

I want pip -V to point to my virtual environment every time I open up vscode without the need to run source .venv/bin/activate

2

Answers


  1. This setting works if you have created virtual environments for each workspace. But for the python executable in the virtual environment folder, the path should be "${workspaceFolder}\.venv\Scripts\python". there is no bin folder in the virtual environment folder.

    Also, in the previous update, a new terminal automatically activates the environment, but the environment name is not displayed in front of the terminal directory.

    enter image description here

    Login or Signup to reply.
  2. You can create a custom task that will run source .venv/bin/activate whenever you open a folder.

    To do that you can go File -> Preferenses -> User Tasks and there add a new custom task like this:

        {
            "label": "Virtual Environment Activation",
            "type": "shell",
            "command": "source",
            "args": [
                ".venv\Scripts\python",
            ],
            "runOptions": {
                "runOn": "folderOpen"
            }
        },
    

    Now, the task will automatically be sent to the shell whenever you open a folder. You can obviously tweak this task according to your own preferences, but this simple one should do the job.

    Also, note that your "args": might need to be .venv/bin/activate with single slashes instead of \. I just don’t know how it better works on Mac

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search