[Tutor] Pager in Python?

Alan G alan.gauld at freenet.co.uk
Mon Jul 18 13:02:51 CEST 2005

> Is there a command like more(1) or less(1) in python to display
> the output of a command (e.g. dir()) one page at a time?

First define a "page".
A page is effectively a screenful, but screens differ in capacity,
especially when users can control font sizes etc.

And what about teletype interfaces that have no screen, what size
is a page there? Maybe the distance between paper perforations?
But some paper rolls have no perforations. (And before anyone
shouts, I do have one system that still uses teletypes as their
only output - albeit not written in Python!)

You can certainly write a paging function that will break up a
long string into sections of N length - especially now that we
have generators, but the function would need to take account of
terminal capabilities. Most folks find it easier to write
their own simplied version, something like:

def page(str, lines=25):
   text = str.split('\n')
   for linenum in range(len(text)):
       print text[linenum]
       if linenum % (lines - 1) == 0
          key = raw_input('Hit any key to continue...')
          if key == 'q' : break

For full less/more equivalence you would need to parse the raw_input
value and take appropriate action... For OS indepencence you should
split by linesep etc too...

Writing a fully fledged OS/terminal independant pager with
backward/forward scrolling etc would be a useful and potentially
challenging beginners project if anyone has the time and inclination!



Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list