Saturday, June 8, 2013

Python autocompletion and virtualenv

In this short tutorial I'll show how to:

1) Set up Python command auto completion feature (tab).

2) Set up Virtual Environment - which basically allow us to have multiple versions of Python on the machine each with different sets of libraries.

Let's get started!

Enable Auto Completion:

Create a .pythonrc file 
$ vi ~/.pythonrcAdd:

import rlcompleter
import readline
readline.parse_and_bind("tab: complete")

The following environment variable will tell Python to import our .pythonrc file upon it's startup:

$vi ~/.bashrc
Add:
export PYTHONSTARTUP="$HOME/.pythonrc"

Load the environment variable from .bashrc:
$source ~/.bashrc
Test:
$ python

Python 2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os

>>> os.
Display all 249 possibilities? (y or n)
os.EX_CANTCREAT             os.execv(
os.EX_CONFIG                os.execve(


Enable Virtual Environment: 

Install python-virtualenv package:

$sudo apt-get install python-virtual-env -y

Create a directory for your virtual environemnt test:
$ mkdir ~/virtual-env-test

Enable the virtual environment:

$ virtualenv ~/virtual-env-test
New python executable in virtual-env-test/bin/python
Installing setuptools.............done.
Installing pip...............done.


Activate the virtual environment (notice the prompt change):
$ . ~/virtual-env-test/bin/activate
(virtual-env-test)$

Let's install some package such as 'boto' (Python interface for AWS):
(virtual-env-test)$pip install boto

Test:
(virtual-env-test)$python
>>> import boto
>>> boto.
boto.BUCKET_NAME_RE              boto.connect_elastictranscoder(
boto.BotoConfigLocations         boto.connect_elb(


 Once you are done testing - deactivate virtual environment:
(virtual-env-test)$ deactivate
$

No comments: