user1427661
user1427661

Reputation: 11774

Creating "Scrollable" Output in Command Line Programs

I have a program that outputs anywhere from 300-1000 lines of data. Rather than have it all output at once, I'd like it to have a manpages-like interface where it will display the first 50 or so lines of input and then the user can press 'f' or 'b' to navigate through the pages. Is there a way to do this in Python?

Note: I want to distribute the program, and I don't want to force users to pipe the output to less/more. Moreover, the output occurs in the middle of the program and is not the only output of the program, so I'm not sure if that would work any way.

Upvotes: 5

Views: 1571

Answers (3)

markemus
markemus

Reputation: 1804

Elaborating on @JaceBrowning's answer:

def display_long_text(text, n=20):
        """Used to display long text blobs."""
        lines = text.splitlines()
        while lines:
            print("\n".join(lines[:n]))
            lines = lines[n:]
            if lines:
                input("")

This gave me the same output as plain print(). less did not work for me since I had non-standard characters in my text blob.

Upvotes: 0

Jace Browning
Jace Browning

Reputation: 12662

You could do something very rudimentary like:

# pseudocode 
def display_text(text):
    lines = text.splitlines()
    while lines remaining:
        display next N lines
        wait for key press

To "wait for key press", you could do something like this: http://www.daniweb.com/software-development/python/threads/123777/press-any-key-to-continue

Upvotes: 3

Robᵩ
Robᵩ

Reputation: 168616

Note: I would never do this, and I think it is very bad UIX, but ...

pager = subprocess.Popen(['less'], stdin=subprocess.PIPE)

Then write all of your command's output to the file-like object: pager.stdin

Upvotes: 2

Related Questions