How to create a virtual environment with Python

How to create a virtual environment with Python

How to create a virtual environment with Python

When setting up a virtual environment for Python3, it is best to use the following command line as a universal standard.

create a venv

python -m venv venv

activate it

.\venv\Scripts\activate

install requirements

pip install -r requirements.txt

run the program

python program.py

( [ Python 3.x ] [ virtual environment ] [ Python command line setup ] )

It is important to understand the use of a virtual environment and the main reason is so when you are developing locally on your PC this means that you are able to use all the packages/modules.  That also means that what you do is you are building a little environment to wrap up your packages in otherwise python will not find the packages with tries to run.

More technical explanation

A Python virtual environment allows you to create and activate an isolated Python environment for a project. This does not replace the global Python installation, which is used by Python's standard library and various other Python programs on your computer.

Instead, Python virtual environments are a way of specifying an alternate Python installation - that may be identical to the global Python installation - for use on a per-project basis. For Python 2.x the command is slightly different:

python2 -m venv my_env

Then activate it by typing the following command in your shell:

source my_env/bin/activate  (this is for git bash)

and install Python dependencies with pip :

pip install -r requirements.txt

At this point, your virtual Python environment is ready to use:

python program.py

Python 3 virtual environment Python command line setup Python 2 -m venv

Python virtual environment Python 3 Python 2 virtual environment Python 2 Python 3 Python 3.x Python command line setup