Python: Creating a virtual environment (ubuntu)

This post will detail how to install a python3 virtual environment. These are useful if you want to isolate your python module installations on a project level from your system, and are highly recommended when working on python projects.

Installation

I start in a folder called ‘project-2’. The first step is in creating the virtual environment. This can be done with the following command. The virtualenv command followed by the path of the python bin file, followed by the name of the virtualenv folder. In this example im creating a python version 3 virtualenv.

Screen Shot 2019-03-19 at 3.22.17 pm.png

Versioning

What if I want to use a different version of python for my venv? This shouldn’t be a problem. Simply type which python if you want to use a python 2 virtual environment. Take note of the path and replace it in the –python parameter of the virtualenv command.

Screen Shot 2019-03-19 at 3.20.42 pm.png

So in this case if I wanted to make a python2 virtualenv instead of python3 I would type:

virtualenv --python=/usr/bin/python name-of-python2-env

Activating virtualenv

In order to use a virtual environment you must first activate it. By using the source command pointing to the activate file within the virtualenvs bin folder. This is different on a windows system, I believe the file on Windows is called activate.bat. Notice the virtual env name will show up in parenthesis to the left upon activation.

Screen Shot 2019-03-19 at 2.57.07 pm

Accessing the interpreter from virtual environment

Simply type python and you will enter the interpreter. Notice the version is 3.6.7 because we used the python3 bin file when creating the virtualenv. You can type exit() to exit interpreter.

Screen Shot 2019-03-19 at 3.28.25 pm.png

Installing modules

In this step I installed a few modules (pandas, requests, xlrd, django) using the standard pip install command. Alternatively, if you have a requirements.txt file you can use pip install requirements.txt, granted the file is in the same directory.

Screen Shot 2019-03-19 at 2.57.33 pm

Gathering and saving module versions

So how can you keep track of module installations? pip freeze shows modules installed in your virtualenv.

Screen Shot 2019-03-19 at 2.57.50 pm

If you need to save these modules and their corresponding versions you can do so with the following command. This will add the libraries to a file called requirements.txt. Which can later be used to reinstall modules from a container or new machine.

Screen Shot 2019-03-19 at 2.58.22 pm

Screen Shot 2019-03-19 at 2.58.37 pm

Deactivating Virtualenv

Deactivate the virtualenv with deactivate command once you are finished using it, and want to revert to system level installation of python3.

Screen Shot 2019-03-19 at 2.58.55 pm

Leave a comment

Website Built with WordPress.com.

Up ↑