The key of interactive programming is "declarative programming", which can be expressed as following principles:
-
Try to write all business logic in functions or classes, instead of procedures;
-
Express the result as return values of functions, instead of printing them to console;
Then you store these functions or classes in your files. Then you start the REPL shell, load your function file, declare your inputs, run your functions with the inputs, evaluate the output; modify the function in file, reload your file in shell, run your functions again, reevaluate the output, continue this loop, until you get the expected output.
Between these loops, you have 2 window: an editor and a shell, the former for write "real" production code, the latter for loading file and doing some experiments, while switching between them with Alt-Tab. You only declare inputs once. Using shortcuts (Ctrl-p) to reload function file and re-test your function. So the loop will be very fast, and you can concentrate on the business logic itself.
emacs-for-python and IPython are the preferred editor and shell, both have powerful code completion functionality.
Linux Shell
Save some fundamental functions in a python file, say "myfunc.py". Then use "python -i myfunc.py" to load all functions in myfunc.py and enter interactive shell.
Python Console
"execfile('filename.py')" to load (or reload) file;
"dir()" to list all variables;
"del(variable)" to clear a variable;
C-p, C-n to traverse in command history;
IPython
Tab autocompletion is awesome in ipython.
Installation
sudo apt-get install ipython-notebook
Command history traverse and back reference
History inputs: all in dictionary "In", use "%hist -n" list all previous command;
Output: all in dictionary Out
, _1
, _2
, ...
C-p, C-n, %rep
While all shortcuts supported by bash are available in IPython (See Command Line Shortcuts in Linux Shell for details).
Command
To line magic command, "%" can be omitted.
%pwd: pwd
!
%run
%reset: clear all user defined variables;
%pycat
%edit
%pdb or %run -d
log utility
%logstate: get the current state of log: on/off
%logstart -o
%logstop
Emacs
Difference between "import" and "run"
You can put some code after
if __name__ == '__main__':
in a python file "test.py". Then if you want run these codes, use "run test.py" in ipython or "execfile('test.py')" in python shell. If you don't want to run these code, use "import test". But this is not a best practice. Try to put all things in functions and classes.