17

I'm essentially trying to achieve this:

>>>print "SOME_VERY_LONG_TEXT" | more

Of course, it doesn't work in Python 2.7(IDLE).

Also, I tried pager 1.2's page() function, but I don't know how to get it to work correctly.

Any ideas?

[UPDATE]

I found a lazy way, as follows:

import pydoc
pydoc.pager("SOME_VERY_LONG_TEXT") 
Michael
  • 8,362
  • 6
  • 61
  • 88
Matt Elson
  • 4,177
  • 8
  • 31
  • 46
  • Any reason why `python foo.py | more` wouldn't work? – Burhan Khalid Nov 05 '12 at 07:08
  • @Aesthete: probably not. `more` is a linux command line program for paging output, similar to `less` which is more popular. – aquavitae Nov 05 '12 at 08:14
  • IPython pages some output by default (like the docs when checked using `object??` syntax). However it doesn't page the expression values (they're fed through `pprint`, but don't go through the pager). – Kos Nov 05 '12 at 09:13
  • 3
    Hey man, thanks for the pydoc.pager! – Eugene Aug 14 '19 at 12:48

3 Answers3

5

Although a bit late, the following worked for me:

def less(data):
    process = Popen(["less"], stdin=PIPE)

    try:
        process.stdin.write(data)
        process.communicate()
    except IOError as e:
        pass
urban
  • 5,392
  • 3
  • 19
  • 45
  • For future readers, you may turn strings into bytes, i. e., the `data` with `bytes(string, 'utf-8')`. – scribe Jul 05 '23 at 08:30
3

You could call it as an external process. (You have to be careful with shell=True, though.)

import subprocess
longStr = 'lots of text here'
subprocess.call(['echo "'+longStr+'" | more'], shell=True)
Matthew Adams
  • 9,426
  • 3
  • 27
  • 43
  • 1
    If you are using less instead of more use less -R to get colored output. The -R option will display the "raw" control characters". – Krishnadas PC Oct 29 '17 at 07:42
3

Writing something terminal and os independent might be a bigger task.

But if you can get the height of the terminal then you can use something like this this Assuming your input is a generator/list of line seperated text, or else you can call text.split('\n') before calling this function

def pagetext(text_lined, num_lines=25):
   for index,line in enumerate(text_lined):
       if index % num_lines == 0 and index:
           input=raw_input("Hit any key to continue press q to quit")
           if input.lower() == 'q':
               break
       else:
           print line

Also there is a pager module on pypy haven't used it but the author says it was supposed to be included in the standard library.

anijhaw
  • 8,954
  • 7
  • 35
  • 36