scroll page by page or line by line using python curses

后端 未结 2 1761
天涯浪人
天涯浪人 2021-01-25 16:11

Using python curses I am trying to write some text in to window. But when I reach end of window i get addstr() returned ERR

how to scroll the output page by

2条回答
  •  猫巷女王i
    2021-01-25 16:46

    The problem is that your calls to screen.addstr have asked for a line number past the end of the screen. Taking into account the box which you have drawn on the screen, a better approach would be to create a new window just inside the box (using curses.newwin for example) and write the addstr calls within that window.

    Your example does not compile as given. Here is a working example:

    import curses
    import logging
    import subprocess
    import sys
    
    command = "ls -l /bin"
    try:
        screen = curses.initscr()
        screen.immedok(True)
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
        screen.bkgd(curses.color_pair(2))
        screen.border(0)
        boxed = curses.newwin(curses.LINES - 2, curses.COLS - 2, 1, 1)
        boxed.scrollok(1)
    
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        linenumber = 1
        for line in output.split("\n"):
            if linenumber <= 2:
                # First two lines are header, mark bold
                boxed.addstr(line, curses.color_pair(1)|curses.A_BOLD)
            else:
                boxed.addstr(line)
            boxed.addch("\n")
            linenumber += 1
            boxed.getch()
    
        screen.getch()
        curses.endwin()
    
    except Exception, e:
        print "\n\033[1;91m[FAILED]\033[0m  Interrupt  ", e
        logging.error(e, exc_info=True)
    

提交回复
热议问题