iPython and the less pager
October 5th, 2008
When I develop software in Python, one of the most valuable tools is iPython. Among the first functions one learns to love, there are the ? and ?? commands.
Putting a ? after an identifier, gets help for that identifier, putting ?? shows the source. Lets use a couple of examples.
It’s easy to see how this resource is invaluable for programming. You’ve got descriptions and beautifully highlighted code. But there is a problem: sometimes you have to be piped into less (or your default pager). The problem is that the default configuration of less does not understand ASCII escapes which are used to show you coloured code (and help).
In this scenario, you get a mess:
Of course, it should be possible to turn off colours in iPython. On the other hand, I find it more interesting to turn on ANSI support in less. I thought it would be quite more difficult than it actually was (and eventually I prepared for the need of using another pages, such as most – since more was the first, less the second, most is the third… one day I’ll write least).
Indeed, it was a matter of setting a flag. If you have the LESS environment variable set in your shell, the options specified in it are set by default when you call less. Good. There are a couple of nice options that turn on ANSI support in less, namely -r and -R.
I chose -R. So I opened .zshenv with vi and added
set LESS="-R"
If you still use bash, than you have to put it in your .bashrc. Change the instructions accordingly to your environment. Well… close the currently opened shell and reopen it (or manually set the LESS environment variable) and you finished.
Sometimes less -r or less -R may cause problems. In this case you should not use them. OS X Leopard with Terminal.app hasn’t issues, appearently.
I first found mention of the less trick here and then in the ipython documentation.
It should be interesting to add the options only to iPython. I actually can’t think to a good reason for doing this, but I will do it anyway. Open a shell where the LESS environment variable is not set, so you can experiment with it.
Open iPython, import os, then give the command:
os.environ.setdefault('LESS', '-R')
Ok, it worked. Now it’s a matter of adding the command to some file ipython loads when starting up. The default way should be editing ~/.ipython/ipy_user_conf.py



2 Responses to “iPython and the less pager”
1Pages tagged "python"
October 5th, 2008 @ 12:47
[...] bookmarks tagged python iPython and the less pager saved by 1 others salishna bookmarked on 10/05/08 | [...]
2custom software
November 21st, 2008 @ 21:29
im new at this whole thing so thanks for the help
Leave a Reply