Skip to content Skip to sidebar Skip to footer

Make Curses Program Output Persist In Terminal Scrollback History After Program Exits

I'm quite new to curses, so I'm trying out some different things in python. I've initialized the window and set scrollok for the window object. I can add strings, and the scrollin

Solution 1:

For this task, I would suggest that you use a pad (http://docs.python.org/2/library/curses.html#curses.newpad):

A pad is like a window, except that it is not restricted by the screen size, and is not necessarily associated with a particular part of the screen. [...] only a part of the window will be on the screen at one time. [...]

In order to leave the contents of the pad on the console after you have finished using curses, I would read the contents back in from the pad, end curses and write the contents to the standard output.

The following code achieves what you describe.

#!/usr/bin/env python2import curses
import time

# Create curses screen
scr = curses.initscr()
scr.keypad(True)
scr.refresh()
curses.noecho()

# Get screen width/height
height,width = scr.getmaxyx()

# Create a curses pad (pad size is height + 10)
mypad_height = height + 10
mypad = curses.newpad(mypad_height, width);
mypad.scrollok(True)
mypad_pos = 0
mypad_refresh = lambda: mypad.refresh(mypad_pos, 0, 0, 0, height-1, width)
mypad_refresh()

# Fill the window with text (note that 5 lines are lost forever)for i inrange(0, height + 15):
    mypad.addstr("{0} This is a sample string...\n".format(i))
    if i > height: mypad_pos = min(i - height, mypad_height - height)
    mypad_refresh()
    time.sleep(0.05)

# Wait for user to scroll or quit
running = Truewhile running:
    ch = scr.getch()
    if ch == curses.KEY_DOWN and mypad_pos < mypad_height - height:
        mypad_pos += 1
        mypad_refresh()
    elif ch == curses.KEY_UP and mypad_pos > 0:
        mypad_pos -= 1
        mypad_refresh()
    elif ch < 256andchr(ch) == 'q':
        running = False# Store the current contents of pad
mypad_contents = []
for i inrange(0, mypad_height):
    mypad_contents.append(mypad.instr(i, 0))

# End curses
curses.endwin()

# Write the old contents of pad to consoleprint'\n'.join(mypad_contents)

Post a Comment for "Make Curses Program Output Persist In Terminal Scrollback History After Program Exits"