我正在尝试使用 python curses 将一些文本写入窗口。但是当我到达窗口的尽头时,我得到 addstr() returned ERR
如何逐页或逐行滚动输出。?如何绑定(bind)空格键或向下箭头?
这是我的代码:
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.scrollok(1)
screen.border(0)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
linenumber = 1
for line in getline(output):
if linenumber <= 2:
# First two lines are header, mark bold
screen.addstr(linenumber, 2, line, curses.color_pair(1)|curses.A_BOLD)
else:
screen.addstr(linenumber, 2, line)
linenumber += 1
screen.getch()
curses.endwin()
except Exception, e:
print "\n\033[1;91m[FAILED]\033[0m Interrupt ", e
logging.error(e, exc_info=True)
curses.endwin()
问题是您对 screen.addstr
的调用要求输入屏幕末尾的行号。考虑到您在屏幕上绘制的框,更好的方法是在框内创建一个新窗口(例如使用 curses.newwin
)并在该窗口内编写 addstr
调用.
您的示例未按给定的方式编译。这是一个工作示例:
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)
我是一名优秀的程序员,十分优秀!