The execution of curses program output is saved in the terminal scroll history after the program exits

I am new to curses, so in python I am testing several different things.

I initialized the window and set scrollok for the window object. I can add lines, and scrolling works so that addstr () has no errors at the end of the window.

What I would like to have is the ability to scroll back in the program output in my terminal program (tmux or KDE Konsole, in this case) after the program terminates.

In my code, I can at least see the output if I miss the endwin () call, but for this the terminal needs a reset call to get back to work.

Also, even when the program is running, after scrolling through the curse window, I cannot scroll back to Konsole to see the original output.

#!/usr/bin/env python2 import curses import time win = curses.initscr() win.scrollok(True) (h,w)=win.getmaxyx() h = h + 10 while h > 0: win.addstr("[h=%d] This is a sample string. After 1 second, it will be lost\n" % h) h = h - 1 win.refresh() time.sleep(0.05) time.sleep(1.0) curses.endwin() 
+7
source share
1 answer

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

A pad is similar to a window, except that it is not limited by the size of the screen and is not necessarily associated with a specific part of the screen. [...] only one part of the window will be displayed on the screen at a time. [...]

To leave the contents of the pad on the console after you finish using curses, I would read the contents back from the pad, finish the curses and write the contents to standard output.

The following code provides what you are describing.

 #!/usr/bin/env python2 import 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 in range(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 = True while 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 < 256 and chr(ch) == 'q': running = False # Store the current contents of pad mypad_contents = [] for i in range(0, mypad_height): mypad_contents.append(mypad.instr(i, 0)) # End curses curses.endwin() # Write the old contents of pad to console print '\n'.join(mypad_contents) 
+7
source

All Articles