I'd like my curses application to display the absolute path of the current file that it is working with as it iterates. These can get longer than the window, running into the next line. If the next file path is shorter, difference in length is not overwritten, leading to mangled strings. What is the best practice way of fixing this problem?
Edit: Python 3 sample code on Mac OS X
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()
Assuming you don't want to use a window, the simplest solution is:
addnstr
instead of addstr
to never write more characters than fit on the line, and clrtoeol
to erase any leftover characters after the new path. For example:
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()
If you want to do this by creating a larger-than-fullscreen window and clipping it to the terminal, read up on newpad
. For a trivial case line this, it won't be any simpler, but for more complex cases it might be what you're looking for:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.