Getting (venv) working in Python3

In the hopes of future proofing my development projects I've been making an effort to use Python 3 for any new work. While this has generally been a good experience, I initially found it difficult to get virtual environments running on Python 3.4.

After some digging through the Python 3 docs <https://docs.python.org/3.4/library/venv.html> and reading through a few Ask Ubuntu and StackOverflow pages I wanted to publish the shell scripts that I found to work.

These comands show how I configured a virtual environment in my /home/matt folder called "venv-test". Let's run the following lines from the terminal and explore the benefits.

$ python3 -m venv venv-test

Which came back with an error I found weird.

The virtual environment was not created successfully because ensurepip is not available.
On Debian/Ubuntu systems, you need to install the python3-venv package using the following command.
apt-get install python3-venv
You may need to use sudo with that command.  After installing the python3-venv package, recreate your virtual environment.

I had expected that Python 3.4 would come with venv configured, but let's install it anyway.

$ apt-get install python3-venv

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python3-venv

Well that wasn't what I expected. As it turns out the easier way to configure the virtual environment is to initialize the venv "without pip", install pip within the virtual environment, and then restart the virtual environment.

$ python3 -m venv venv-test --without-pip
$ source venv-test/bin/activate
(venv-test) $ curl https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py | python
(venv-test) $ deactivate
$ source venv-test/bin/activate
(venv-test) $ pip freeze

wheel==0.26.0

Perfect, we've configured a virtual environment with a clean set of dependencies, and there is a further bonus:

(venv-test) $ python
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> phrase = "Virtual environment working"
>>> print (phrase)
Virtual environment working

Running the tradionally 2.7 command "python" now drops us into a Python 3.4 shell.

In order to use your new virtual environment go ahead and use "pip install" as you otherwise would to install packages into your new Python 3.4 environment.

social