Virtual environment for Python 3.X in Ubuntu 18.04

One of the popular ways to create and activate Python virtual environments is `conda` or `Anaconda` in Windows. You can find more information about them, here (https://zolanvari.com/conda).
However, if you use Linux and especially if you would like to work with containers (e.g. Docker), I would recommend using `virtualenv`:
Step 1. Update your repositories:
$ sudo apt-get update
Step 2. Install pip for Python 3:

$ sudo apt-get install build-essential libssl-dev libffi-dev python-dev
$ sudo apt install python3-pip

Step 3. Use pip to install virtualenv:
$ sudo pip3 install virtualenv

Step 4. Define which version of Python 3 you would like to have for your virtual environment. Also, choose a simple name for your virtual environment. I selected env:
$ virtualenv -p python3 env

*Useful tip: alternatively, you can also specify the exact version of Python by:

$ virtualenv env --python=python3.7

Step 5. Activate your new Python 3 environment. There are two ways to do this:
$ source env/bin/activate

You should see now the(env)at the beginning of the terminal line.

To make sure that you are now working with the correct version of the Python:
$ python -- version
$ which python
$ which pip

Step 7. Finally, if you would like to leave the virtual environment
$ deactivate

Step 8. Additionally, if you would like to save all packages with the exact version in the local env, you can run this command in the env and it will save it in the requirements.txt file:

(env)[email protected]:/path/to/your/current/directory$
pip freeze -l > requirements.txt

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.