Python command line = Linux Bash command line
Some of our technical staff are doing a fair amount of Python coding and also are preparing for the Linux Certification (LPIC-1) exam.
One of the first topics we have been studying is the Linux bash command line, command history and command editing.
Guess what, you may be surprised that modern Python interpreters use the GNU readline library… in plain English: you should be able to practice the skills you’ve gained during your Linux study sessions whenever you work with your Python interpreter, i.e.:
* Line editing
* History substitution
This requires you to:
1) Add line to your bash start up script ~/.bashrc (or your ~/.bash_profile):
(changing /home/user to your home directory, e.g. /home/mtarruella)
2) create the file: .pystartup (see below) in your home directory
Python will execute the contents of a file identified by the PYTHONSTARTUP
environment variable when you start an interactive interpreter.
How do you use it ?
i) use the Emacs key bindings you learnt for bash
e.g. CTRL-A moves the cursor to the beginning of the line.
However, if you are more inclined to the Vim key bindings
you will need to configure readline placing the command:
set editing-mode vi
in the file ~/.inputrc
ii) Retrieve commands from your history by using CTRL-P (Previous command) and
CTRL-N (Next command) or the useful ‘reversy’: CTRL-R (search command backwards).
iii) Start using command completion as if you were in the Linux bash command line e.g. start typing imp and press <Tab> you should then see:
The whole word “import” should be auto-completed.
More detailed information on the topic: Python interactive
Happy Linux! and now Happy Python too!
Note that this is valid for *nix and Mac’s too.
By: Marcos Tarruella
An example of .pystartup file:
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.
historyPath = os.path.expanduser("~/.pyhistory")
del os, atexit, readline, rlcompleter, save_history, historyPath