DEV Community


Posted on

Virtual Environment for Python

Below you learn why need a Python virtual environment and how are you can use it with Python 3 (Why Python 3?).

You should know how to run Python before setting up a virtual environment. If you use PyCharm, it sets up a virtualenv automatically.

What is Virtual Environment?

Virtual environments are particularly helpful if the program requires an individual environment, with a unique python version and specific module versions. It prevents package conflicts.

You can use virtualenv to create your isolated environment.

Why do you need a virtual environment?

The virtual environment is a way to keep the python configuration isolated from other projects.

One user has multiple virtual environments on a single computer, one for eahch project. Different libraries can be incorporated in each virtual environment.

virtual environment

How to create a virtual environment using Python3?

Step1: Install Virtual Environment

pip3 install virtualenv
Collecting virtualenv
  Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
    100% |████████████████████████████████| 1.8MB 367kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0

In python 3, you can use this command 'python3 –m venv /path/to/create/the/virtual/env'.

-bash-4.2$ python3 -m venv test_venv
-bash-4.2$ ls

Step3: Activate virtual environment

-bash-4.2$ source test_venv/bin/activate
(test_venv) -bash-4.2$

Step4: Install the required libraries, using pip

For the example below,we have used 'flask' library. Flask lets you build web apps, you can make all kinds of things or even plot

(test_venv) -bash-4.2$ pip3 install flask
Collecting flask
  Downloading (94kB)
    100% |████████████████████████████████| 102kB 3.8MB/s
Collecting Jinja2>=2.10.1 (from flask)
  Using cached
Collecting click>=5.1 (from flask)
  Using cached
Collecting itsdangerous>=0.24 (from flask)
  Using cached
Collecting Werkzeug>=0.15 (from flask)
  Using cached
Collecting MarkupSafe>=0.23 (from Jinja2>=2.10.1->flask)
  Using cached
Installing collected packages: MarkupSafe, Jinja2, click, itsdangerous, Werkzeug, flask
Successfully installed Jinja2-2.10.1 MarkupSafe-1.1.1 Werkzeug-0.16.0 click-7.0 flask-1.1.1 itsdangerous-1.1.0
 (test_venv) -bash-4.2$

More reading:

Top comments (0)