Question

When working on a project my scripts often have some boiler-plate code, like adding paths to sys.path and importing my project's modules. It gets tedious to run this boiler-plate code every time I start up the interactive interpreter to quickly check something, so I'm wondering if it's possible to pass a script to the interpreter that it will run before it becomes "interactive".

Was it helpful?

Solution

That can be done using the -i option. Quoting the interpreter help text:

-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x

So the interpreter runs the script, then makes the interactive prompt available after execution.

Example:

$ python -i boilerplate.py
>>> print mymodule.__doc__
I'm a module!
>>>

This can also be done using the environment variable PYTHONSTARTUP. Example:

$ PYTHONSTARTUP=boilerplate.py python
Python 2.7.3 (default, Sep  4 2012, 10:30:34) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print mymodule.__doc__
I'm a module!
>>>

I personally prefer the former method since it doesn't show the three lines of information, but either will get the job done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top