Python Virtual Environments
Visit dataquest for a more in-depth overview of what python virtual environments are, as well as what advantages they promise.
Creating a Python Virtual Environment (Windows)
py -m venv ['/path/to/new/virtual/environment']Activating a Python Virtual Environment
['/path/to/new/virtual/environment']\scripts\activateInstalling Packages in a Python Virtual Environment
By default, only pip and setup tools are initially installed. To check the pre-installed packages:
pip listTo upgrade pip:
py -m pip install --upgrade pipTo install new packages:
py -m pip install pandasReproducing a Python Virtual Environment
You first need to list all the dependencies installed. Export the package list into a requirements.txt file
pip freeze > requirements.txtCreate a virtual environment, activate it, and then run:
pip install -r requirements.txtNote:
If you’re going to add your project to a Git repository, never add its virtual environment folder to the repository. The only thing you need to add is the requirements.txt file.
A Python project folder contains source code that runs in a virtual environment. On the other hand, a virtual environment is a folder that contains the Python interpreter, packages, and tools like pip. So, the best practice is to keep them separate and never put your project files in a virtual environment folder.
Deactivating a Python Virtual Environment
deactivateDeleting a Python Virtual Environment
If you want to delete a virtual environment, you can simply delete its folder, no uninstall required
rm -rf ['/path/to/new/virtual/environment']Use Python Virtual Environments in Visual Studio Code
First, ensure you have created and activated a virtual environment.
Then navigate to your project folder in the terminal
and run the following command:
code .The command above will open the project folder in VS Code. If the command above doesn’t work, open VS code, press command + shift + P, to open the Command Palette, type shell command and select Install ‘code’ command in PATH. Now, create a Python file, and name it my_script.py. The last step is to select the virtual environment using the Python: Select Interpreter command from the Command Palette. To do so, press Command + shift + P, and type Python, and choose Select Interpreter. The Python: Select Interpreter command displays all available environments.