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".
Asked
Active
Viewed 515 times
1 Answers
6
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.

Hubro
- 56,214
- 69
- 228
- 381
-
1There is also the ``PYTHONSTARTUP`` environment variable. I use this to setup a pythonic calculator by importing sympy et al. Also useful to [add tab completion](http://docs.python.org/library/rlcompleter.html). – Jonas Schäfer Sep 25 '12 at 11:13
-
@JonasWielicki: Cool! Added it to the answer. – Hubro Sep 25 '12 at 11:27