Python Virtual Environment

This post details the creation of Python virtual environment with the use of ‘venv’, the python build-in package, of installing specific Python version and necessary packages.

Link to venv.

Creating and Managing Virtual Environment for Python project

1. Open Terminal and create directory

1
2
3

D:\Pyproject>mkdir testing_env_project

2. cd to the directory and create virtual environment with specific Python version (here for instance using python 3.8 version)

1
2
3
D:\Pyproject>cd testing_env_project

D:\Pyproject\testing_env_project>py -3.8 -m venv my_env_name

Then you will see a new folder ‘my_env_name’ created under ‘testing_env_project’.

1
2
3
4
5
6
7
8
9
10
11
12
13
# ls to check all the folders and files created under this.
D:\Pyproject\testing_env_project> ls */*

my_env_name/pyvenv.cfg

my_env_name/Include:

my_env_name/Lib:
site-packages/

my_env_name/Scripts:
activate Activate.ps1 easy_install.exe* pip.exe* pip3.exe* pythonw.exe*
activate.bat deactivate.bat easy_install-3.8.exe* pip3.8.exe* python.exe*

3. activate the virtual environment you’ve just created by following command

1
2
3
D:\Pyproject\testing_env_project> my_env_name\Scripts\activate

(my_env_name) D:\Pyproject\testing_env_project>

4. Then using folloing command to install specific packages you want in this virtual environment

1
2
3
(my_env_name) D:\Pyproject\testing_env_project> pip install package_name
# example to install python packages numpy and pandas
(my_env_name) D:\Pyproject\testing_env_project> pip install numpy pandas

5. Open the project via VS Code Editor using following command:

1
(my_env_name) D:\Pyproject\testing_env_project> code .

6. List and save all packages installed in this virtual environment for this project to a txt file so others can replicate the same project if sharing

1
(my_env_name) D:\Pyproject\testing_env_project> pip freeze > requirements.txt

Finally, you will be able to work in this project via VS Code Editor.