/ tuesdaytooling

Tooling Tuesday - Late Edition: virtualenv

Sorry this is late, Tuesday was a busy family day.

For this post we take a look at virtualenv which is a great tool to use with Python 3, especially if you don't want to mess up your operating system's Python install.

So what is it?

Virtualenv creates a virtual environment into which we can install Python packages in isolation. This means that anything we install in a virtual environment will not interfere with the Python install for your operating system.

So why should I use it?

If you are testing new Python packages, want to create projects using exotic libraries etc. Then you really don't want to mix these libraries with your core Python install. Especially if you are using a Linux operating system as Python is used extensively behind the scenes.

So how do I use it?

First we need to install virtualenv and we can do that via the terminal.
Here we update the list of repositories that we can install from. Then we install virtualenv for Python2 and Python3. Lastly we ensure that the Python3 package manager, pip is installed.

$ sudo apt update
$ sudo apt install virtualenv python3-virtualenv python3-pip

To create a virtual environment called blogtest for Python3 we need to type the following into the terminal.

$ virtualenv -p python3 blogtest

Why use -p python3?
If your system only has Python 3 installed, then you can just use virtaulenv blogtest to create a virtual environment as it will use the default Python installation for your system. But if you have Python2 as well, then the -p switch enables us to choose the Python for the the virtual environment. This would also be useful if you are seeking to test a package in a specific version of Python3.

So now that we have a virtual environment we now need to activate it to use it. To do this use the following command in the terminal. Note that you can change blogtest to match the name of your environment.

$ source blogtest/bin/activate

Screenshot-from-2019-04-03-11-18-44
The terminal will change slightly, and we can see the name of the virtual environment at the start of a line, followed by our username, and the name of the machine we are using.

So now that we are in the virtual environment we can install packages from pip just for this environment.

So here I install pyjokes which are a series of programmer jokes.

$ pip3 install pyjokes

Then I can run pyjokes by typing the following to get a Chuck Norris joke.

$ pyjoke -c chuck

Screenshot-from-2019-04-03-11-28-06

So how do I quit the virtual environment?

From the terminal type

deactivate

and this will end the virtual environment session.

Can I still run the Chuck Norris joke?

The short answer...No!
Screenshot-from-2019-04-03-11-32-38

As we are no longer inside the virtual environment we cannot access the libraries that are installed in there. Which is a good thing if you need to make sure that your libraries are isolated.

Happy Hacking!