[Tutor] How to import a few modules when I enter python?

Steven D'Aprano steve at pearwood.info
Tue Aug 7 09:07:32 CEST 2012


On Tue, Aug 07, 2012 at 09:09:02AM +0530, Santosh Kumar wrote:
> Hello there,
> 
> I have a few scripts that I made to experiment with, I have to import
> them everytime I enter the Python shell. The scripts are in
> `/home/username/workshop/` (this directory has also some non .py
> files) directory. Is there a way I can import them as soon as I enter
> Python?
> 
> Also I am exploring the OS module, can I import them as well?

The way to do this is using Python's optional "startup file".

Using your shell, define an environment variable

PYTHONSTARTUP

set to the path to a Python script. The way you do this depends on your 
operating system, and shell. I use Linux with the bash shell, and I have 
this in my .bashrc file:

export PYTHONSTARTUP=/home/steve/python/startup.py

Then, in your startup.py file, you can add any Python code you like, and 
it will be automatically run when you use the Python interactive 
interpreter.

In your case, you can keep a list of your modules, and just import them:

import module1
import module2
# etc.

but that assumes that your /home/username/workshop/ directory is in the 
PYTHONPATH. How do you do that? Here are two ways:

1) In your startup file, start with these lines:

import sys
sys.path.append('/home/username/workshop/')

2) Add this line to your .bashrc:

export PYTHONPATH=/home/username/workshop/


Some further thoughts:

The startup file will NOT run when you run a script directly, or if you 
pass the -E command line switch:

python myscript.py
python -E 

and other Python implementations like IronPython and Jython may not 
honour the PYTHONSTARTUP variable.


Attached is my current startup file, to give you some ideas of what you 
can do.



-- 
Steven

-------------- next part --------------
###############################################################
#          P Y T H O N   S T A R T U P   S C R I P T          #
###############################################################

# Keep this module compatible with Python 2.4 and better.

from __future__ import division

# === Basic functionality ===

# Pre-import useful modules.
import math, os, sys

# Change the main prompt.
sys.ps1 = 'py> '

# Include special values. Prior to Python 2.6, this was messy, platform-
# dependent, and not guaranteed to work.
try:
    INF = float('inf')
    NAN = float('nan')
except ValueError:
    # Possibly Windows prior to Python 2.6.
    try:
        INF = float('1.#INF')
        NAN = float('1.#IND')  # Indeterminate.
    except ValueError:
        # Desperate times require desperate measures...
        try:
            INF = 1e3000  # Hopefully, this should overflow to INF.
            NAN = INF-INF  # And this hopefully will give a NaN.
        except (ValueError, OverflowError):
            pass  # Just give up.

# Bring back reload in Python 3.
try:
    reload
except NameError:
    from imp import reload

# Monkey-patch the math module *wicked grin*
try:
    math.tau
except AttributeError:
    math.tau = 2*math.pi


# === Add globbing to dir() ===
try:
    sys._getframe()
except (AttributeError, NotImplementedError):
    # Not all implementations support _getframe; in particular,
    # IronPython does not support it by default.
    print('*** warning: no frame support; globbing dir not available ***')
else:
    try:
        from enhanced_dir import globbing_dir as dir
    except ImportError:
        print('*** warning: globbing dir not available ***')


# === Simple benchmarking ===
try:
    from timer import Timer as timer
except ImportError:
    print('*** warning: timer not available ***')


# === Command line completion and history ===
try:
    from completer import completer
except ImportError:
    print('*** warning: command line completion not available ***')



print("=== startup script executed ===")



More information about the Tutor mailing list