Customise your Python Prompt

On startup, Python looks for a startup file. This startup file is pointed at by the PYTHONSTARTUP environment variable.

Lets implement tab completion in our Python prompt.

1. Navigate to your home directory (cd ~)

2. Create a file: .pythonstart / any other name you want! (nano .pythonstart)

3. Type in the following code:

import readline

import rlcompleter

import atexit

import os

readline.parse_and_bind(‘tab: complete’) 

# this binds the tab key to auto-complete

histfile = os.path.join(os.environ[‘HOME’], ‘.pythonhistory’)

# os .environ is a dictionary storing all global environment variables

# try reading history file

try:

readline.read_history_file(histfile)

except IOError:

pass

# on exiting create a history file

atexit.register(readline.write_history_file, histfile)

del os, readline, rlcompleter, histfile

4. Now we need to point the environment variable to this script

5. Make the following changes in .bash_profile and .bashrc

PYTHONSTARTUP=$HOME/.pythonstart

export PYTHONSTARTUP

6. Now launch Python and tab completion should work

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: