In the Setting up Virtual Development Environments for Python post, we discussed the use of pythonbrew for managing Python versions and their related virtualenvs. If you do enjoy pythonbrew, then be sure to check out pythonz which is now the active fork of the original project and has resolved almost all issues that I had originally reported.
However, there is another alternative called pyenv which has several significant advantages. Probably one of the biggest is the fact that pyenv doesn’t depend on Python 2.6+ to be installed. Many OSs (e.g. SLES 10 and CentOS 5) come with Python 2.4 pre-installed. In addition, pyenv implements automatic switching of Python version or virtualenv based on the directory you’re in.
So let’s get started!
If you’re using CentOS, install all build dependencies as follows:
Firstly, ensure you install EPEL if you’re on CentOS 5.x:
Now install the build dependencies:
If you’re using Ubuntu Server, install all build dependencies like this:
Now install pyenv as a regular user:
Once installation completes, you’ll be presented with some code that should be added to your ~/.bashrc file:
Simply add this code to the end of your ~/.bashrc and then source your profile to have these additions loaded.
On Ubuntu Server:
Note: pyenv fully supports bash completion, so be sure to use your tab key when typing commands to help auto-complete them.
To list all available Python versions, use:
To install a Python version, use:
To list the installed Python versions, use:
Note: Virtual environments will also show up as versions after they’re added.
To set the global Python version used for your account, use:
Creating virtualenvs is also easy and extremely well integrated into pyenv:
You may activate and de-activate virtualenvs using:
To see all the virtualenvs you have created, you may use:
OK here comes the great part. Suppose we’re working on a project which we know always uses a virtualenv called project123. While in the root of the project directory, you may set the appropriate Python environment that should always be used while in the project directory.
Now each time you enter this directory, the chosen virtualenv or Python version will be activated automatically! The file that is creatied and specifies the appropriate environment is named .python-version and should be added to your repository.
At any time, you may view the Python environment being used:
Finally, you can remove a Python version or virtualenv using the uninstall commend:
Let’s walk through an entire example using my Flaskage project.
This is definitely the way I’ll be managing my Python environment from now on as it’s definitely the most elegant solution I have found to date. Enjoy! :)