Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the Python Interactive Interpreter to run a script on load?

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".

like image 574
Hubro Avatar asked Sep 25 '12 11:09

Hubro


People also ask

How do I run a python script in interactive mode?

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 .

What are two ways to run a program using the python interpreter?

There are two ways to use the python interpreter: interactive mode and script mode.

What is the difference between interactive and script mode of execution in python?

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.


1 Answers

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.

like image 70
Hubro Avatar answered Oct 23 '22 21:10

Hubro