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".
A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .
There are two ways to use the python interpreter: interactive mode and script mode.
Difference between Interactive mode and Script modeThe program is compiled in the command prompt, The interactive mode is more suitable for writing very short programs. Script mode is more suitable for writing long programs. Editing of code can be done but it is a tedious task.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With