Skip to content

[VS Code] Activate the Python Virtual Environment in the Project

Last Updated on 2022-07-14 by Clay

Recently I moved some private projects to VS Code from PyCharm, but I encountered a problem: the Python parsing that VS Code supports by default is based on the global environment, and I am used to enabling different virtual environment in different Python project.

What's wrong with this? To put it simply, suppose I installed the gdown package in project A, but not in the global environment. Once I want to use the automatic completion of related functions in gdown, that will be not found.


Enable virtual environment method

If the virtual environment has not been enabled in your project, you can create a virtual environment; but I already have the relevant virtual environment folder venv in the project, so the fastest way is re-create the same virtual environment.

If you don't have any virtual environment in your project, you can start from Step 1.


Step 0: (optional) Backup virtual environment data

pip3 freeze > requirements.txt



Step 1: Install VS Code Python Extensions

If installed, you can skip this step. Open Extensions in the sidebar, search for python and install it.



Step 2: Create Virtual Environment

First open VS Code and open the project (you need to open VS Code to detect the new environment), then open the terminal, whether you use an external terminal or the terminal field of the VS Code editor.

Go to the top level of your project, and use the following commands for creating (you can refer: https://docs.python.org/3/tutorial/venv.html)

python3 -m venv venv
source venv/bin/activate


Then you will see the message pop-up at the right-bottom.

Select Yes, and your project code will parsed by current virtual environment.

If you need to restore the original backup working environment, you can use the following command:

pip3 install requirements.txt 



In my case, I will find that the gdown package has changed from "warning" to a normal color in the project, indicating that VS Code has captured the package from the virtual environment.


References


Read More

Leave a Reply