Introduction:
Virtual environments are a fundamental tool that all beginner software developers should learn at some point. Virtual environments are isolated spaces generated by a computer. These spaces separate package installs from eachother. This is important because certain projects may use and require different package versions. Virtual environments prevent conflict between these versions by isolating the different versions from each other.
This tutorial will cover how to set up a virtual environment quickly in Visual Studio with the pre installed python module venv. This tutorial assumes that you know the basics of navigating Visual Studio Code and have Python installed.
Creating an environment:
In order to create a virtual environment, follow the following steps:
- Open Visual Studio Code
- Open a new terminal (Terminal -> New Terminal)
- Within that terminal, run the appropriate commands based on your operating system
MacOS/Linux:
$ Mkdir envFolder
$ cd envFolder
$ python3 -m venv .venv
Windows:
> Mkdir NameOfFolder
> cd NameOfFolder
> python3 -m venv .venv
Activating the environment:
After a virtual environment is created, it has to be activated before it is used. In order to activate the virtual environment, run the following script in your terminal:
If you're using macOS/Linux, run:
$ . . venv/bin/activate
If you’re using Windows, run:
> .venv\Scripts\activate
Note that if you tried to run the above script, you may have received an error message stating that the execution of scripts is disabled on your computer. For security purposes, some computers will disable script execution to prevent the user from running scripts that could cause harm to their system.
To temporarily bypass this restriction:
- Close Visual Studio Code
- Reopen Visual Studio Code as an administrator
- Open a new terminal
- Run the following command:
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force
This temporarily lets the user bypass the security restrictions that disable the execution of scripts
Afterwards, repeat the above steps, starting with step 5 of creating a new environment.
Conclusion:
If you successfully activated the virtual enviroment then you should see (.venv) at the start of a new line in the terminal. The virtual environment only stays activated while the terminal is open and will automatically deactivate if the terminal is ever closed.
Virtual environments should always be created if you're starting a new project that requires external libraries to be downloaded. Getting in the habit of creating virtual environments will help prevent issues in future projects that you will work on.
Top comments (0)