Python Virtual Environments

Update: November 2022

In Ethical Hacking Python is a very popular programming language. Many tools are built based on different versions of Python and packages version. Thus, being able to manage Python virtual environments comes quickly an handy skill to have.

Why using virtual environments?

To be able to make coexist different Python versions and packages on a same system for our different and independent projects. A virtual environment works independently and is isolated.

Installing virtualenv

sudo apt install virtualenv

Create a Python3 virtual environment

# Linux

virtualenv myprojectA

# I can also specify an already existing directory to set up a virtual environment within that directory.
virtualenv /home/amandine/myprojectB

# Windows
python3 -m venv .\DachshundAD\

Activate the virtual environment

# Linux
source path/to/virtualenv/bin/activate

# Being at the root of my virtual environment I can just type
source bin/activate


# Windows
PS C:\Users\aghebert\Desktop\DachshundAD> .\Scripts\activate

Deactivate a virtual environment

source path/to/virtualenv/bin/deactivate

# Sometime just type "deactivate" works 
deactivate

Create a virtual environment using a specific version of Python

First, we have to check where our Python binary is located. For example, if I want to create a virtual environment with Python2, I have to check where my Python2 binary is.

find / -name python2 2</dev/null

Then, I can create my virtual environment using this binary with the -p flag. If myprojectA folder does not exist it will create it.

virtualenv -p /usr/bin/python2 /home/amandine/myprojectA

List all packages within that environment

# Having the virtual environment activate

pip list

Last updated