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

3
我希望我的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()

2
这取决于您如何显示文本。请提供一个简短完整的程序来演示问题。 - Robᵩ
看起来你需要截取字符串、创建一个足够大的滚动窗口来容纳你的字符串,或者在你的字符串后清除至行末。我不确定这三种方法中哪一种是最适合你的;正如@Robᵩ所说,如果没有看到你的代码,并且最好能够获得你程序的更完整描述,那么很难猜测。 - abarnert
@abarnet 添加了示例代码。 - Sean W.
请提供实际可工作的示例代码;您至少需要在此处使用 from os import path 或类似的语句。此外,一个 最小化、完整化、可验证化的示例 不应包含与问题无关的第三方依赖项;为什么不直接使用 os.walk 而不是 scandir.walk 来演示呢? - abarnert
1个回答

3
假设您不想使用窗口,最简单的解决方案是:
  1. 使用 addnstr 替代 addstr,以确保写入行的字符数量不超过该行容量。
  2. 使用 clrtoeol 擦除新路径后多余的任何字符。
例如:
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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接