Thursday, October 9, 2008

How to automatically include modules in your python shell

1. Create a environmental variable in your shell config PYTHONSTARTUP that contains a full path to a python script which we're about to create. For bashrc, this looks like:

export PYTHONSTARTUP="/home/nick/.pythonstart.py"

This file will be executed every time you start a python shell (but not every time you execute  a  script).

2. In the python file we specified put import statements including whatever modules you want. Mine looks like:

import os, sys, re 
from pprint import pprint
from datetime import datetime
from math import *

Every time you start an interactive session these modules will be automatically included and you won't need to bother importing them.

You can see the official docs on the PYTHONSTARTUP variable in the manual.

No comments: