I’ve covered virtual environments before and how to set up and use them in Visual Studio. With the popularity of VS Code growing it was about time I did a quick roundup of running Python in general, and virtual environments in particular, with VS Code. If you have not used VS Code before with Python here is a quick tutorial.
First thing is to make sure you have the Microsoft Python extension for Visual Studio Code installed. There are a lot of other extensions you can add to improve productivity but this is the only one I’ll assume is installed. This extension will activate whenever you have a file open with the .py extension.
With a .py file open, you should see in the status bar along the bottom the currently selected interpreter to use if you run it that script, e.g. Python 3.8.2 64-bit – if you want to select a different interpreter click on this section of the status bar. All the Python environments VS Code can find will be listed along with the option of entering a path for an interpreter it cannot find.
There is no menu to add or create a virtual environment in VS Code like there is in Visual Studio, instead the creation must be done manually. This can either be done using pipenv or assuming you are using Python 3, from the command line with the following:
python -m venv .venv
The first line creates a folder called .venv containing all the necessary files and structure. The second line starts VS Code (assuming you have it in your path). Note the dot at the end; this sets the working directory to the current directory. Now when you open a file ending in .py, as well as activating all the extensions installed that are linked to Python it also look for any virtual environments directly off the working folder. You should see the status bar change to show the Python environment is now the version of foldername of the virtual environment, e.g. Python 3.8.2 64-bit (‘.venv’: venv) – running the Python script will automatically run inside the virtual environment without any additional steps.
Not only that, if you open a new terminal it will automatically run the script to enable the virtual environment. So to install (or add more) packages into the virtual environment you can just open a terminal and type in
pip install -r requirements.txt
That’s all there is to it. While not seamless, with a couple of commands you can be running everything in virtual environments like a pro. If you want some more extensions, check out this list.