本文修改自:Using Python Virtual Environment in VSCode - Tech Inscribed
Install Virtualenv
We will be using virtualenv to create our python virtual environments. We will use pip to install it.
Install virtualenv using pip:
pip install virtualenv
Check your installation:
virtualenv --version
Create a Virtual Environment
First, let us create a folder .virtualenvs in the home directory. This is where we will keep all our virtual environments.
cd ~
mkdir .virtualenvs
cd .virtualenvs
From inside the .virtualenvs directory, create a new virtual environment using virtualenv
virtualenv venv
Now, let us activate the virtual environment
source venv/bin/activate
We will install a package in the virtual environment so that we can test if the setup is working as expected.
pip install excel
VSCode Setup
At first, if you open the test.py file, assuming you have Python linter extension installed, VSCode will show an error like this.
This is because VSCode is not using the correct python interpreter. There are two ways in which you can fix this.
1. Update Venv Path Settings in VSCode
Open VSCode preferences (Ctrl + ,) and search for “venv”. Add ~/.virtualenvs to the “Venv Path” settings
2. Add the Virtual Environment Folder to VSCode
Add the folder that contains the virtual environment to VSCode, in our case, it is the ~/.virtualenv folder. Once added, you will be able to select the interpreter by clicking on the interpreter version displayed on the left-bottom corner.
3. Set Default interpreter
pen VSCode preferences (Ctrl + ,) and search for "defaultpath"