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.
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.
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.
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.
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.
Gathering and saving module versions
So how can you keep track of module installations? pip freeze shows modules installed in your virtualenv.
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.
Deactivating Virtualenv
Deactivate the virtualenv with deactivate command once you are finished using it, and want to revert to system level installation of python3.
Leave a comment