如何处理比Python中的Curses窗口更长的行?

时间:2015-05-17 20:22:45

标签: python curses

我希望我的curses应用程序显示当它迭代时正在使用的当前文件的绝对路径。这些可以比窗口更长,进入下一行。如果下一个文件路径较短,则不会覆盖长度差异,从而导致字符串损坏。解决这个问题的最佳做法是什么?

编辑:Mac OS X上的Python 3示例代码

from os import walk
import curses
from os import path

stdscr = curses.initscr()
curses.noecho()
for root, dirs, files in walk("/Users"):
    for file in files:
        file_path = path.join(root, file)
        stdscr.addstr(0, 0, "Scanning: {0}".format(file_path))
        stdscr.clearok(1)
        stdscr.refresh()

1 个答案:

答案 0 :(得分:1)

假设您不想使用窗口,最简单的解决方案是:

  1. 使用addnstr代替addstr永远不会写出比线条更多的字符,
  2. 使用clrtoeol删除新路径后的剩余字符。
  3. 例如:

    from scandir import walk
    import curses
    from os import path
    
    try:
        stdscr = curses.initscr()
        curses.noecho()
        _, width = stdscr.getmaxyx()
        for root, dirs, files in walk("/Users"):
            for file in files:
                file_path = path.join(root, file)
                stdscr.addnstr(0, 0, "Scanning: {0}".format(file_path), width-1)
                stdscr.clrtoeol()
                stdscr.clearok(1)
                stdscr.refresh()
    finally:
        curses.endwin()
    

    如果您想通过创建一个大于全屏的窗口并将其剪切到终端来完成此操作,请阅读newpad。对于一个简单的案例线,它不会更简单,但对于更复杂的情况,它可能是你正在寻找的:

    from scandir import walk
    import curses
    from os import path
    
    try:
        stdscr = curses.initscr()
        curses.noecho()
        height, width = stdscr.getmaxyx()
        win = curses.newpad(height, 16383)
        for root, dirs, files in walk("/Users"):
            for file in files:
                file_path = path.join(root, file)
                win.addstr(0, 0, "Scanning: {0}".format(file_path))
                win.clrtoeol()
                win.clearok(1)
                win.refresh(0, 0, 0, 0, height-1, width-1)
    finally:
        curses.endwin()