How to create a virtual environment for your Python 3 application with python3-venv in Linux or Unix

The python3-venv module allows us to create lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Given that, we will be able to run multiple Python 3 environments with varying dependencies on the same computer.

This post shows how to create a virtual environment for your Python 3 application with python3-venv in Linux or Unix.

When you want to create a virtual environment for your Python 3 application inside ~/my_py3_venv, you can run the following command in your terminal shell:

python3 -m venv ~/my_py3_venv

After the command complete, you should be able to find the virtual environment inside the ~/my_py3_venv directory.

Getting into your Python 3 virtual environment with your terminal window

In order to get into your Python 3 virtual environment with your terminal window, you need to run the activate script. Given that, run the following command to get into your Python 3 virtual environment:

source ~/my_py3_venv/bin/activate

After the command complete, you will find that your terminal prompt is appended with (my_py3_venv). While inside this virtual environment, you can install any Python dependencies with the pip command. For example, if you wish to install Flask, you can run the following command:

pip install flask

When you had installed the necessary dependencies for your Python 3 application, you can then run your application with the python binary:

python run_your_app.py

Getting out of your Python 3 virtual environment

In order to get out of your Python 3 virtual environment, you need to run the following command:

deactivate

After the command completes, you will find that your terminal prompt is not appended with (my_py3_venv). At this point in time, whatever dependencies that you had added while inside the virtual environment will not be available.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.