Python Virtual Environment

In this How-To article, we will go through the basic steps for setting up a Python virtual environment using venv. Note that venv is included Python 3.4+ by default. If you are running an older version of Python, you will need to install the Python virtual environment separately via pip install virtualenv and replace python -m venv by virtualenv in the following instructions.

This article is based on Python venv: How To Create, Activate, Deactivate, And Delete.

Create Python Virtual Environment

To create a Python virtual environment, we first navigate to the desired directory (usually the project root directory) and execute the following command:

python -m venv <directory>

Thereby, we create a Python virtual environment inside a directory with the specified name. Most commonly, the environment is named venv and, hence, <directory> gets replaced by venv.

python -m venv venv

Activate Python Virtual Environment

The previously created virtual environment directory venv contains activation scripts for Windows and Linux/MacOS. Execute the command according to your operating system to activate the virtual environment:

  • Windows:
    • In cmd.exe:
      venv\Scripts\activate.bat
      
    • In PowerShell:
      venv\Scripts\Activate.psi
      
  • Linux:
    source venv/bin/activate
    

Deactivate Python Virtual Environment

To deactivate a currently activated virtual environment, call deactivate inside your terminal:

deactivate

To permanently delete a virtual environment, we simply need to remove the virtual environment directory:

rm -r ./venv/

VENV Activation Wrapper Scripts

For convenience, we can also create a shell script (Linux) to start the Python program in our virtual environment without explicitly calling the activation script. Supposing our python script is main.py, we create the file ./run with the following content:

#!/usr/bin/env bash

source ./venv/bin/activate
python ./main.py $@

Additionally, we create the installation script ./install to install libraries via pip into our virtual environment, as well as the script to uninstall libraries ./uninstall:

#!/usr/bin/env bash

source ./venv/bin/activate
pip install $@
#!/usr/bin/env bash

source ./venv/bin/activate
pip uninstall $@

To execute these scripts, we have to make them executable:

chmod u+x ./run
chmod u+x ./install
chmod u+x ./uninstall

Then, we can install/uninstall libraries and run the Python script with the following commands:

./install <library>
./run [<arg1> [<arg2> [...]]]
./uninstall <library>



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Zsh and Oh-My-Zsh Installation Guide
  • Tensorflow Tutorial: Load Custom Image Dataset
  • Tensorflow Federated Tutorial
  • GitHub SSH Key